### Scaffold Factorial App Example Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/harnessapi/examples/factorial_app/README.md Installs harnessapi and scaffolds the factorial app example. Use `uv tool install harnessapi` for recommended installation. ```bash # Install harnessapi if you haven't already uv tool install harnessapi # recommended # pip install harnessapi # alternative # List all bundled examples harnessapi examples # Scaffold into ./factorial_app/ harnessapi examples factorial_app # Or scaffold into a custom directory harnessapi examples factorial_app my-factorial ``` -------------------------------- ### Navigate to Example Directory Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/harnessapi/examples/agentic-rag/README.md Change the current directory to the agentic-rag example folder. This is the first step before installing dependencies or running the application. ```bash cd examples/agentic-rag ``` -------------------------------- ### Setup Factorial App Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/harnessapi/examples/factorial_app/README.md Navigates into the scaffolded directory and installs dependencies. ```bash cd factorial_app uv sync ``` -------------------------------- ### Scaffold and Install Harness API Example Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/examples/agentic-rag.mdx Installs the Harness API tool and scaffolds a new agentic RAG example project. Then, it synchronizes project dependencies. ```bash uv tool install harnessapi # recommended harnessapi examples agentic-rag # scaffolds into ./agentic-rag/ cd agentic-rag ``` ```bash uv sync ``` -------------------------------- ### Complete HarnessAPI Multi-tenancy Setup Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/multi-tenancy/api-reference.md A full example demonstrating the setup of HarnessAPI with multi-tenancy. Includes defining a custom API key authentication middleware and configuring a TenantBackend with SQLite storage. ```python import os from pathlib import Path from starlette.responses import JSONResponse from harnessapi import HarnessAPI from harnessapi.multitenancy import TenantBackend, SQLiteStorageBackend, SandboxRegistry async def require_api_key(request, call_next): if request.headers.get("X-Admin-Key") != os.environ["ADMIN_KEY"]: return JSONResponse({"detail": "Forbidden"}, status_code=403) return await call_next(request) backend = TenantBackend( tenant_extractor=lambda req: req.headers.get("X-Tenant-ID"), storage=SQLiteStorageBackend(path="./variants.db"), sandbox_registry=SandboxRegistry(), sandbox_provider="local_subprocess", auto_promote=False, max_variants_per_tenant_per_skill=5, sandbox_run_timeout_secs=10.0, ) app = HarnessAPI( skills_dir=Path(__file__).parent / "skills", tenant_backend=backend, enable_admin_mcp=True, admin_mcp_auth=require_api_key, ) ``` -------------------------------- ### Install harnessapi from source Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/guides/installation.md For contributors, clone the repository and use uv sync to install the project and its development dependencies from the lockfile. ```bash git clone https://github.com/edwinjosechittilappilly/harnessapi cd harnessapi uv sync ``` -------------------------------- ### Install uv Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/guides/installation.md If you don't have uv installed, use this command to download and install it. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Scaffold and Run HarnessAPI Agent Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/public/llms-full.txt Install the HarnessAPI tool, scaffold an example agent, install dependencies, set your OpenAI API key, and run the agent. The agent will download embedding models on first run. ```bash uv tool install harnessapi # recommended harnessapi examples agentic-rag # scaffolds into ./agentic-rag/ cd agentic-rag ``` ```bash uv sync ``` ```bash cp .env.example .env # edit .env → OPENAI_API_KEY=sk-... # or: export OPENAI_API_KEY=sk-... ``` ```bash harnessapi run # or: uvicorn main:app --reload ``` ```text INFO: Started server process INFO: Discovered skills: ingest, list_docs, search INFO: MCP endpoint: http://localhost:8000/mcp INFO: Admin MCP: http://localhost:8000/admin-mcp INFO: Swagger UI: http://localhost:8000/docs ``` -------------------------------- ### Scaffold Agentic RAG Example with Harness API CLI Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/harnessapi/examples/agentic-rag/README.md Install and scaffold the agentic RAG example using the Harness API CLI. This command downloads all necessary files for the example project. ```bash # Install harnessapi if you haven't already uv tool install harnessapi # recommended # pip install harnessapi # alternative # List all bundled examples harnessapi examples # Scaffold into ./agentic-rag/ harnessapi examples agentic-rag # Or scaffold into a custom directory harnessapi examples agentic-rag my-rag-project ``` -------------------------------- ### Run HarnessAPI Server Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/examples/web-scraper.mdx Starts the harnessapi development server to make skills accessible. ```bash harnessapi run ``` -------------------------------- ### Install Dependencies with uv Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/harnessapi/examples/agentic-rag/README.md Install project dependencies using the `uv` package manager. This is the recommended method for faster installation. ```bash uv sync ``` -------------------------------- ### HarnessAPI Single-Tenant Setup Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/public/llms-full.txt Initializes HarnessAPI for a single-tenant application. ```python app = HarnessAPI(skills_dir="./skills") ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/README.md Run this command in the root of your project to install all the necessary dependencies listed in `package.json`. ```bash npm install ``` -------------------------------- ### Install optional extras for harnessapi Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/guides/installation.md Install additional providers for per-tenant sandboxes if you are using the multi-tenancy sandbox feature. The base install supports local_subprocess sandboxes out of the box. ```bash # Docker sandbox provider uv add "harnessapi[docker]" ``` ```bash # Kubernetes sandbox provider uv add "harnessapi[kubernetes]" ``` ```bash # Both uv add "harnessapi[docker,kubernetes]" ``` -------------------------------- ### Start Local Development Server Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/README.md This command starts a local development server, typically at `localhost:4321`, allowing you to see your site changes in real-time. ```bash npm run dev ``` -------------------------------- ### Clone and Run Harness API Application Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/examples/factorial.mdx Commands to clone the harnessapi repository, install dependencies, and run the Uvicorn server for the factorial example. ```bash git clone https://github.com/edwinjosechittilappilly/harnessapi cd harnessapi uv sync uv run uvicorn examples.factorial_app.main:app --reload ``` -------------------------------- ### Example Input/Output Pair JSON Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/concepts/skill-folders.md Shows an input/output example pair that will be displayed in the Swagger schema. Additional examples follow a similar pattern. ```json { "input": { "text": "Python is a high-level programming language.", "max_length": 20 }, "output": { "summary": "Python is a high-lev", "word_count": null } } ``` -------------------------------- ### Install harnessapi with pip Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/guides/installation.md A standard method to install harnessapi using pip. ```bash pip install harnessapi ``` -------------------------------- ### Install Dependencies Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/examples/summarizer.mdx Add harnessapi and openai to your project's dependencies. ```bash uv add harnessapi openai ``` -------------------------------- ### Custom Backend Integration Example Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/multi-tenancy/storage.md Pass an instance of your custom storage backend directly to the TenantBackend constructor. ```python backend = TenantBackend( tenant_extractor=..., storage=MyPostgresBackend(dsn=os.environ["DATABASE_URL"]), ) ``` -------------------------------- ### Start harnessapi with Explicit Application Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/reference/run.md Starts the harnessapi development server, explicitly specifying the application module and attribute, with auto-detection and auto-reload enabled. ```bash harnessapi run --app mymodule:app ``` -------------------------------- ### Verify harnessapi installation Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/guides/installation.md Run this command to confirm that harnessapi has been installed correctly and is accessible from your command line. ```bash harnessapi --help ``` -------------------------------- ### Harness API Application Setup Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/examples/factorial.mdx Initializes the HarnessAPI application, specifying the directory for skills and providing basic metadata. ```python from pathlib import Path from harnessapi import HarnessAPI app = HarnessAPI( skills_dir=Path(__file__).parent / "skills", title="Factorial Harness", description="Demo: factorial as a streaming skill + MCP tool", ) ``` -------------------------------- ### Install Dependencies with pip Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/harnessapi/examples/agentic-rag/README.md Install project dependencies using `pip`. This is an alternative if `uv` is not available. ```bash pip install -e . ``` -------------------------------- ### Run Factorial App Server Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/harnessapi/examples/factorial_app/README.md Starts the harnessapi server. The server will be accessible at `http://localhost:8000`. ```bash harnessapi run # or: uvicorn main:app --reload ``` -------------------------------- ### Server Startup Information Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/harnessapi/examples/agentic-rag/README.md This output indicates that the server has started successfully and provides URLs for accessing the API documentation (Swagger UI) and management endpoints. ```text INFO: Started server process INFO: Discovered skills: ingest, list_docs, search INFO: MCP endpoint: http://localhost:8000/mcp INFO: Admin MCP: http://localhost:8000/admin-mcp INFO: Swagger UI: http://localhost:8000/docs ``` -------------------------------- ### Install harnessapi with uv Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/guides/installation.md Use uv to add harnessapi to your project. uv is recommended for its speed and automatic lockfile generation. ```bash uv add harnessapi ``` -------------------------------- ### Install Dependencies and Set API Key Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/examples/image-captioner.mdx Installs the harnessapi and openai Python packages and sets the OPENAI_API_KEY environment variable. ```bash uv add harnessapi openai export OPENAI_API_KEY=sk-... ``` -------------------------------- ### main.py: HarnessAPI App Setup Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/examples/agentic-rag.mdx Sets up the HarnessAPI application with multi-tenancy, custom middleware for tenant context, and an admin key authentication for the MCP. Use this for initializing your agentic RAG application. ```python import os from pathlib import Path from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests import Request from starlette.responses import JSONResponse from harnessapi import HarnessAPI from harnessapi.multitenancy import TenantBackend, SQLiteStorageBackend, SandboxRegistry from skills.shared.context import tenant_id_var class TenantContextMiddleware(BaseHTTPMiddleware): """Copies tenant_id from request.state into a ContextVar for skill handlers.""" async def dispatch(self, request: Request, call_next): tid = getattr(request.state, "tenant_id", None) or "default" token = tenant_id_var.set(tid) try: return await call_next(request) finally: tenant_id_var.reset(token) async def require_admin_key(request: Request, call_next): key = request.headers.get("X-Admin-Key") expected = os.environ.get("ADMIN_KEY", "dev-secret") if key != expected: return JSONResponse({"detail": "Forbidden — provide X-Admin-Key header"}, status_code=403) return await call_next(request) backend = TenantBackend( tenant_extractor=lambda req: req.headers.get("X-Tenant-ID") or "default", storage=SQLiteStorageBackend(path="./variants.db"), sandbox_registry=SandboxRegistry(), sandbox_provider="local_subprocess", auto_promote=False, ) app = HarnessAPI( skills_dir=Path(__file__).parent / "skills", title="Agentic RAG", description="Per-tenant document ingestion and semantic search with harnessapi + multi-tenancy", tenant_backend=backend, enable_admin_mcp=True, admin_mcp_auth=require_admin_key, ) app.add_middleware(TenantContextMiddleware) ``` -------------------------------- ### Start harnessapi with Custom Port Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/reference/run.md Starts the harnessapi development server on a specified custom port, with auto-detection and auto-reload enabled. ```bash harnessapi run --port 8080 ``` -------------------------------- ### Install Dependencies Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/examples/web-scraper.mdx Installs the necessary Python packages for the web scraper skill. ```bash uv add harnessapi httpx beautifulsoup4 ``` -------------------------------- ### HarnessAPI help output Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/public/llms-full.txt This is the expected output when running `harnessapi --help`, confirming the CLI is installed and functional. ```text Usage: harnessapi [OPTIONS] COMMAND [ARGS]... harnessapi — skill-first streaming API and MCP tool framework. Options: --help Show this message and exit. Commands: init Scaffold a new harnessapi project or skill. run Start the harnessapi development server. ``` -------------------------------- ### Run harnessapi server with uvx Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/guides/quickstart.mdx Execute `uvx harnessapi run` to start the harnessapi server. It will scan the `skills/` directory, register available skills, and begin listening on port 8000. ```bash uvx harnessapi run ``` -------------------------------- ### Provision a Sandbox for a Tenant Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/public/llms-full.txt Initiate a new sandbox environment for a specific tenant. This command starts a new harnessapi server instance for the tenant. ```bash curl -X POST http://localhost:8000/tenants/user-a/sandbox/provision \ -H "Content-Type: application/json" \ -d '{"skills_dir": "./skills"}' ``` -------------------------------- ### Tenant Extractor Examples Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/multi-tenancy/index.md Examples of different strategies for extracting tenant information from incoming requests. Choose a method that aligns with your request structure. ```python # From a header (most common) tenant_extractor=lambda req: req.headers.get("X-Tenant-ID") ``` ```python # From a JWT sub-claim (async) async def from_jwt(req): token = req.headers.get("Authorization", "").removeprefix("Bearer ") return decode_jwt(token).get("sub") ``` ```python # From a query parameter tenant_extractor=lambda req: req.query_params.get("tenant") ``` ```python # From a path segment (useful with API gateways) tenant_extractor=lambda req: req.path_params.get("tenant_id") ``` -------------------------------- ### Run the Application with Uvicorn Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/harnessapi/examples/agentic-rag/README.md Start the application using `uvicorn` directly. This provides more control over the server startup, such as enabling hot-reloading. ```bash # or: uvicorn main:app --reload ``` -------------------------------- ### Railway Deployment Start Command Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/guides/deploy.md Use this command to start your harnessapi application on Railway. Ensure your OpenAI API key is set as an environment variable. ```bash uvicorn main:app --host 0.0.0.0 --port $PORT ``` -------------------------------- ### Install HarnessAPI with Docker sandbox provider Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/public/llms-full.txt Install the Docker sandbox provider for HarnessAPI by adding the '[docker]' extra. This is only needed if you plan to use the multi-tenancy sandbox feature with Docker. ```bash uv add "harnessapi[docker]" ``` -------------------------------- ### Error Event Example Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/public/llms-full.txt Example of an 'error' event emitted when an exception occurs in a handler. ```text event: error data: ValueError: Input too long event: (stream closes) ``` -------------------------------- ### Install HarnessAPI with both Docker and Kubernetes sandbox providers Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/public/llms-full.txt Install both the Docker and Kubernetes sandbox providers for HarnessAPI by including both extras. This is required if you intend to use the multi-tenancy sandbox feature with both Docker and Kubernetes. ```bash uv add "harnessapi[docker,kubernetes]" ``` -------------------------------- ### Scrape Skill Output Example Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/public/llms-full.txt Example of the streamed output from the scrape skill when processing a webpage. ```text event: chunk data: This domain is for use in illustrative examples in documents. event: chunk data: You may use this domain in literature without prior coordination. event: done data: ``` -------------------------------- ### Install HarnessAPI with Kubernetes sandbox provider Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/public/llms-full.txt Install the Kubernetes sandbox provider for HarnessAPI by adding the '[kubernetes]' extra. This is only needed if you plan to use the multi-tenancy sandbox feature with Kubernetes. ```bash uv add "harnessapi[kubernetes]" ``` -------------------------------- ### Run test suite from source Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/guides/installation.md After installing from source, use uv run pytest to execute the project's test suite. ```bash uv run pytest ``` -------------------------------- ### Copy Environment File Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/harnessapi/examples/agentic-rag/README.md Copy the example environment file to a new file named `.env`. This file will store sensitive information like API keys. ```bash cp .env.example .env ``` -------------------------------- ### Web Scraper Skill Example Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/public/llms-full.txt This example demonstrates wrapping an existing Python function (httpx + BeautifulSoup web scraper) as a streaming Harness API skill. It shows how to stream multi-section content and use it as an MCP tool with Claude or Cursor. ```python # Example usage of wrapping a web scraper as a harnessapi skill # (Actual code for the scraper is not provided in the source text) # from harnessapi import harnessapi_init_function # # @harnessapi_init_function # def scrape_website(url: str) -> str: # # ... httpx + BeautifulSoup scraping logic ... # return "Scraped content" ``` -------------------------------- ### Example Streaming Output Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/examples/summarizer.mdx Illustrates the expected Server-Sent Events (SSE) output format for a streaming summary. ```text event: chunk data: Large language models are event: chunk data: neural networks trained event: chunk data: on massive text datasets. event: done data: ``` -------------------------------- ### Scaffold and Run Harness API Project with uvx Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/README.md Use `uvx` to scaffold a new Harness API project and then run it in an isolated environment. No installation is required for `uvx`. ```bash # Scaffold a new project uvx harnessapi init my-project # Enter and run it cd my-project uvx harnessapi run ``` -------------------------------- ### Configure Docker Sandbox Provider Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/multi-tenancy/sandboxes.md Example of passing provider-specific configuration to the TenantBackend for the Docker sandbox provider. This includes image details and resource limits. ```python backend = TenantBackend( ..., sandbox_provider="docker", sandbox_provider_config={ "image": "my-org/harnessapi-sandbox:latest", "memory_limit": "512m", "cpu_period": 100000, "cpu_quota": 50000, }, ) ``` -------------------------------- ### SSE Response from Factorial Skill Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/examples/factorial.mdx Example output demonstrating the Server-Sent Events (SSE) format for streaming factorial calculation steps. ```text event: chunk data: start: 1 event: chunk data: 2: 2 event: chunk data: 3: 6 event: chunk data: 4: 24 event: chunk data: 5: 120 event: done data: ``` -------------------------------- ### Set OpenAI API Key Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/examples/agentic-rag.mdx Copies the example environment file and instructs on setting the OpenAI API key either by editing the file or exporting it as an environment variable. ```bash cp .env.example .env # edit .env → OPENAI_API_KEY=sk-... # or: export OPENAI_API_KEY=sk-... ``` -------------------------------- ### Expose harnessapi Server to Network Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/reference/run.md Starts the harnessapi development server, binding to all network interfaces (0.0.0.0) on a specified port, with auto-detection and auto-reload enabled. ```bash harnessapi run --host 0.0.0.0 --port 8000 ``` -------------------------------- ### InProcessStorageBackend Example Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/multi-tenancy/storage.md Use InProcessStorageBackend for local development and tests where persistence is not needed. It's the default when no storage argument is passed to TenantBackend. ```python from harnessapi.multitenancy import TenantBackend, InProcessStorageBackend backend = TenantBackend( tenant_extractor=lambda req: req.headers.get("X-Tenant-ID"), storage=InProcessStorageBackend(), # default — can be omitted ) ``` -------------------------------- ### Scaffold a new harnessapi project Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/guides/quickstart.mdx Use `uvx harnessapi init` to create a new project with a sample skill. Navigate into the created directory to proceed. ```bash uvx harnessapi init my-project cd my-project ``` -------------------------------- ### Get Help with Astro CLI Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/README.md If you need assistance with the Astro CLI or want to see available options, use this command to display the help information. ```bash npm run astro -- --help ``` -------------------------------- ### Clone Base Skill Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/public/llms-full.txt Clones the base skill to start development. The response provides the source code for the base handler. ```APIDOC ## POST /tenants/{tenant_id}/skills/{base_skill_name}/clone ### Description Clones the base skill to start development. The response provides the source code for the base handler. ### Method POST ### Endpoint /tenants/{tenant_id}/skills/{base_skill_name}/clone ### Request Body - **variant_id** (string) - Required - The ID of the variant to clone. - **tenant_id** (string) - Required - The ID of the tenant. - **base_skill_name** (string) - Required - The name of the base skill. - **status** (string) - Required - The status of the skill (e.g., "sandbox"). - **source_code** (string) - Required - The source code of the base handler. ### Response #### Success Response (200) - **message** (string) - A success message. - **variant_id** (string) - The ID of the newly created variant. - **tenant_id** (string) - The ID of the tenant. - **base_skill_name** (string) - The name of the base skill. - **status** (string) - The status of the skill. - **source_code** (string) - The source code of the base handler. ``` -------------------------------- ### Server-Sent Events (SSE) Client Example Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/README.md Illustrates the format of Server-Sent Events (SSE) that clients receive when a Harness API skill streams data. ```text event: chunk data: The answer is event: chunk data: 42. event: done data: ``` -------------------------------- ### Run harnessapi commands with uvx Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/guides/installation.md Use uvx to execute harnessapi commands in a temporary environment without a formal installation. This is useful for quick testing or CI environments. ```bash # Scaffold and run a new project uvx harnessapi init my-project cd my-project uvx harnessapi run ``` -------------------------------- ### Real LLM Streaming Example with Python Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/concepts/streaming.md This Python code demonstrates how to implement streaming with an OpenAI-compatible API. The client will receive each token as a 'chunk' event. ```python from openai import AsyncOpenAI from .models import Input client = AsyncOpenAI() async def handle(input: Input): stream = await client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": input.prompt}], stream=True, ) async for chunk in stream: delta = chunk.choices[0].delta.content if delta: yield delta ``` -------------------------------- ### Create a New harnessapi Project Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/reference/init.md Use this command to scaffold a new harnessapi project with a sample 'greet' skill. If run in an empty directory, it scaffolds in-place. ```bash harnessapi init my-project ``` -------------------------------- ### Run HarnessAPI Development Server Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/public/llms-full.txt Starts the HarnessAPI development server using uvicorn with auto-reload enabled. Options allow specifying the app module, host, port, and disabling auto-reload. ```bash harnessapi run [options] ``` -------------------------------- ### Provision a Sandbox Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/public/llms-full.txt Provisions a new sandbox environment for a specific tenant. This starts a new harnessapi server with base skills loaded, accessible only from the main server. ```APIDOC ## POST /tenants/{tenant_id}/sandbox/provision ### Description Provisions a new sandbox environment for a specific tenant. ### Method POST ### Endpoint /tenants/{tenant_id}/sandbox/provision ### Parameters #### Path Parameters - **tenant_id** (string) - Required - The ID of the tenant for whom to provision a sandbox. #### Request Body - **skills_dir** (string) - Required - The directory containing the skills to load into the sandbox. ### Request Example ```bash curl -X POST http://localhost:8000/tenants/user-a/sandbox/provision \ -H "Content-Type: application/json" \ -d '{"skills_dir": "./skills"}' ``` ### Response #### Success Response (200) - **tenant_id** (string) - The ID of the tenant. - **endpoint_url** (string) - The URL to access the sandbox. - **sandbox_type** (string) - The type of sandbox provisioned (e.g., "local_subprocess"). - **pid** (integer) - The process ID of the sandbox server. - **status** (string) - The current status of the sandbox (e.g., "running"). #### Response Example ```json { "tenant_id": "user-a", "endpoint_url": "http://127.0.0.1:43721", "sandbox_type": "local_subprocess", "pid": 9182, "status": "running" } ``` ``` -------------------------------- ### Provision a Sandbox Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/multi-tenancy/sandboxes.md Provisions a new sandbox environment for a specific tenant. This command starts a fresh harnessapi server within the sandbox, loaded with base skills. The sandbox is only accessible from the main server. ```bash curl -X POST http://localhost:8000/tenants/user-a/sandbox/provision \ -H "Content-Type: application/json" \ -d '{"skills_dir": "./skills"}' ``` ```json { "tenant_id": "user-a", "endpoint_url": "http://127.0.0.1:43721", "sandbox_type": "local_subprocess", "pid": 9182, "status": "running" } ``` -------------------------------- ### Full Skill Folder Structure Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/concepts/skill-folders.md An expanded skill structure includes optional configuration files like `skill.toml`, documentation (`SKILL.md`), and example data for testing and documentation. ```tree skills/ └── my-skill/ ├── handler.py ← required: async handle() function ├── models.py ← required: Pydantic Input + Output ├── skill.toml ← optional: name, description, tags, timeout ├── SKILL.md ← optional: agentskills.io compatible metadata ├── defaults/ │ └── input.json ← optional: default values shown in /docs └── examples/ └── 01.json ← optional: {input, output} pairs for /docs ``` -------------------------------- ### Search Tenant-1 Documents Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/public/llms-full.txt Search for information within a specific tenant's documents. This example queries for Moon landing information and expects results only from tenant-1. ```bash curl -X POST http://localhost:8000/skills/search \ -H "Content-Type: application/json" \ -H "Accept: application/json" \ -H "X-Tenant-ID: tenant-1" \ -d '{"query": "When did humans first land on the Moon?", "top_k": 3}' ``` ```json {"chunks": [ "Humans first landed on the Moon on **July 20, 1969**, during the Apollo 11 mission.", " Neil Armstrong and Buzz Aldrin descended to the surface while Michael Collins orbited.\n\n", "---\nSources (1 documents):\n", " • apollo-history (similarity: 0.921) — title: Apollo Program, source: history-book\n"] } ``` -------------------------------- ### LocalFileStorageBackend Example Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/multi-tenancy/storage.md LocalFileStorageBackend writes one JSON file per variant to a specified directory. It's suitable for single-worker deployments as it lacks atomic transactions and concurrent-write safety. ```python from harnessapi.multitenancy import TenantBackend, LocalFileStorageBackend backend = TenantBackend( tenant_extractor=lambda req: req.headers.get("X-Tenant-ID"), storage=LocalFileStorageBackend(variants_dir="./variants"), ) ``` -------------------------------- ### harnessapi init Usage Examples Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/reference/init.md These are the general usage patterns for the harnessapi init command. They cover creating new projects, adding API layers to existing skills, converting entire skill directories, and wrapping Python functions. ```bash harnessapi init [project-name] ``` ```bash harnessapi init --skill ``` ```bash harnessapi init --skills-dir ``` ```bash harnessapi init --function [--output ] ``` -------------------------------- ### Ingest Document for Tenant-1 Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/public/llms-full.txt Ingest a document into the HarnessAPI for a specific tenant. This example uses `curl` to send a POST request to the `/skills/ingest` endpoint with document content, ID, and metadata. ```bash curl -X POST http://localhost:8000/skills/ingest \ -H "Content-Type: application/json" \ -H "Accept: application/json" \ -H "X-Tenant-ID: tenant-1" \ -d '{ \ "text": "The Apollo program was a series of NASA missions from 1961 to 1972. Apollo 11 landed the first humans on the Moon on July 20, 1969. Neil Armstrong and Buzz Aldrin walked on the lunar surface while Michael Collins orbited above. Six Apollo missions successfully landed on the Moon.", \ "doc_id": "apollo-history", \ "metadata": {"title": "Apollo Program", "source": "history-book"} \ }' ``` ```json {"chunks": [ "Chunking document 'apollo-history'வைக்...", "Created 2 chunks (size=500, overlap=50)", "Embedding chunks...", "Indexed chunks 1–2 / 2", "Done. 2 chunks indexed for doc 'apollo-history' (tenant: tenant-1)" ]} ``` -------------------------------- ### Initialize HarnessAPI App Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/examples/web-scraper.mdx Sets up the HarnessAPI application, specifying the directory where skills are located. ```python from pathlib import Path from harnessapi import HarnessAPI app = HarnessAPI(skills_dir=Path(__file__).parent / "skills") ``` -------------------------------- ### TenantBackend Configuration Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/multi-tenancy/api-reference.md Illustrates the configuration of the `TenantBackend`, covering tenant extraction, storage, sandbox settings, and provider options. ```python from harnessapi.multitenancy import TenantBackend, SQLiteStorageBackend, SandboxRegistry backend = TenantBackend( # Required tenant_extractor=lambda req: req.headers.get("X-Tenant-ID"), # Storage (default: InProcessStorageBackend — ephemeral) storage=SQLiteStorageBackend(path="./variants.db"), # Validation sandbox_import_blocklist=["os", "subprocess", "socket", "sys", "importlib", "builtins"], # Behaviour auto_promote=False, # promote immediately on customize max_variants_per_tenant_per_skill=10, # 409 Conflict when exceeded sandbox_run_timeout_secs=10.0, # timeout for /run and sandbox-forwarded calls # Per-tenant sandboxes (optional) sandbox_registry=SandboxRegistry(), sandbox_provider="local_subprocess", # or "docker", "kubernetes", or a custom instance sandbox_provider_config={}, ) ``` -------------------------------- ### Python SSE Stream and JSON Response Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/public/llms-full.txt Demonstrates calling a Harness API skill using Python's httpx library. Includes examples for processing Server-Sent Events (SSE) as they arrive and for receiving a complete JSON response. ```python import httpx # SSE stream — process each chunk as it arrives with httpx.Client() as client: with client.stream( "POST", "http://localhost:8000/skills/chat", json={"prompt": "What is 6 * 7?"}, ) as response: for line in response.iter_lines(): if line.startswith("data:"): chunk = line[5:].strip() if chunk: print(chunk, end="", flush=True) # JSON — block until complete response = httpx.post( "http://localhost:8000/skills/chat", json={"prompt": "What is 6 * 7?"}, headers={"Accept": "application/json"}, ) print(response.json()) ``` -------------------------------- ### Harness API JSON Response Example Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/README.md An example of a typical JSON response from a Harness API skill. ```json {"message": "Hello, world! Welcome to harnessapi.", "length": 36} ``` -------------------------------- ### Valid streaming handler function Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/public/llms-full.txt This is a valid example of a streaming handler function. It must be named `handle` and accept one positional parameter. The function yields words from the input text. ```python # Valid — streaming async def handle(input: Input): for word in input.text.split(): yield word ``` -------------------------------- ### Stream Summary using cURL Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/public/llms-full.txt Send a POST request to the /skills/summarize endpoint to get a streaming summary. The request includes text, max_words, and style parameters. The response streams chunks of data and a final done event. ```bash curl -X POST http://localhost:8000/skills/summarize \ -H "Content-Type: application/json" \ -d '{ "text": "Large language models are neural networks trained on vast text...", "max_words": 20, "style": "concise" }' ``` ```text event: chunk data: Large language models are event: chunk data: neural networks trained event: chunk data: on massive text datasets. event: done data: ``` -------------------------------- ### Streaming Search Results (SSE) Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/public/llms-full.txt Perform a search and receive results as a Server-Sent Events (SSE) stream. Omit the `Accept: application/json` header to enable streaming. This example queries for Moon landing counts. ```bash curl -X POST http://localhost:8000/skills/search \ -H "Content-Type: application/json" \ -H "X-Tenant-ID: tenant-1" \ -d '{"query": "How many Moon landings were there?"}' ``` ```text event: chunk data: There were event: chunk data: six successful Apollo Moon landings... event: done data: ``` -------------------------------- ### HarnessAPI Initialization with Multi-Tenancy Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/multi-tenancy/api-reference.md Demonstrates how to initialize HarnessAPI with multi-tenancy enabled using the `tenant_backend` parameter, and optionally configure the admin management console with `enable_admin_mcp` and `admin_mcp_auth`. ```APIDOC ## HarnessAPI Initialization with Multi-Tenancy ### Description This section details the parameters for initializing `HarnessAPI` to support multi-tenancy and an administrative management console. ### Parameters #### Initialization Parameters - **`tenant_backend`** (`TenantBackend | None`) - Required - Enables multi-tenancy and the `/tenants/*` management API. - **`enable_admin_mcp`** (`bool`) - Optional - Mounts the admin MCP server at `/admin-mcp`. Defaults to `False`. - **`admin_mcp_auth`** (`Callable | None`) - Optional - Async middleware for `/admin-mcp`. Signature: `async (request, call_next) -> Response`. Defaults to `None`. ### Code Example ```python from harnessapi import HarnessAPI from harnessapi.multitenancy import TenantBackend # Assuming 'backend' is an initialized TenantBackend instance app = HarnessAPI( skills_dir="./skills", tenant_backend=backend, # enables multi-tenancy enable_admin_mcp=True, # mounts /admin-mcp admin_mcp_auth=require_api_key, # protects /admin-mcp ) ``` ### Related Concepts - **`TenantBackend`**: The core component for managing multi-tenancy. - **`SQLiteStorageBackend`**: An example storage backend for tenant data. - **`SandboxRegistry`**: Manages sandboxes for tenant environments. - **`require_api_key`**: An example authentication middleware for the admin MCP. ``` -------------------------------- ### Start harnessapi Server without Reload Source: https://github.com/edwinjosechittilappilly/harnessapi/blob/main/docs/src/content/docs/reference/run.md Starts the harnessapi development server with auto-detection and default port, but disables the auto-reload feature. ```bash harnessapi run --no-reload ```