# CUGA configuration and development guide Detailed model setup, SDK usage, skills, knowledge, supervisor agents, execution modes, and testing. For the product overview and the first run, start with the [README](../../README.md).
LLM Configuration - Advanced Options --- Refer to: [`.env.example`](../../.env.example) for detailed examples. CUGA supports multiple LLM providers with flexible configuration options. You can configure models through TOML files or override specific settings using environment variables. ## Supported Platforms - **OpenAI** - GPT models via OpenAI API (also supports LiteLLM via base URL override) - **IBM WatsonX** - IBM's enterprise LLM platform - **Azure OpenAI** - Microsoft's Azure OpenAI service - **Groq** - High-performance inference platform with fast LLM models - **Google Gemini** - Google GenAI models (`settings.google.toml`) - **MiniMax** - MiniMax models (`settings.minimax.toml`) - **Ollama** - Local models through an OpenAI-compatible endpoint (`settings.ollama.toml`) - **RITS** - Internal IBM research platform - **OpenRouter** - LLM API gateway provider - **watsonx Orchestrate (wxO)** - Routes LLM calls through an Orchestrate tenant for tracing, guardrails, and entitlement-based billing Current presets are in [`src/cuga/configurations/models/`](../../src/cuga/configurations/models/); see the [model documentation](https://docs.cuga.dev/docs/configure/models/) for provider-specific setup. ## Configuration Priority 1. **Environment Variables** (highest priority) 2. **TOML Configuration** (medium priority) 3. **Default Values** (lowest priority) ### Option 1: OpenAI **Setup Instructions:** 1. Create an account at [platform.openai.com](https://platform.openai.com) 2. Generate an API key from your [API keys page](https://platform.openai.com/api-keys) 3. Add to your `.env` file: ```env # OpenAI Configuration OPENAI_API_KEY=sk-...your-key-here... AGENT_SETTING_CONFIG="settings.openai.toml" # Optional overrides MODEL_NAME=gpt-4o # Override model name OPENAI_BASE_URL=https://api.openai.com/v1 # Override base URL OPENAI_API_VERSION=2024-08-06 # Override API version ``` **Default Values:** - Model: `gpt-4o` - API Version: OpenAI's default API Version - Base URL: OpenAI's default endpoint ### Option 2: IBM WatsonX **Setup Instructions:** 1. Access [IBM WatsonX](https://www.ibm.com/watsonx) 2. Create a project or space and get your credentials: - Project ID or Space ID - API Key - Region/URL 3. Add to your `.env` file: ```env # WatsonX Configuration WATSONX_API_KEY=your-watsonx-api-key WATSONX_PROJECT_ID=your-project-id # WATSONX_SPACE_ID=your-space-id # Alternative to WATSONX_PROJECT_ID WATSONX_URL=https://us-south.ml.cloud.ibm.com # or your region AGENT_SETTING_CONFIG="settings.watsonx.toml" # Optional override MODEL_NAME=meta-llama/llama-4-maverick-17b-128e-instruct-fp8 # Override model for all agents ``` **Default Values:** - Model: `meta-llama/llama-4-maverick-17b-128e-instruct-fp8` ### Option 3: Azure OpenAI **Setup Instructions:** 1. Add to your `.env` file: ```env AGENT_SETTING_CONFIG="settings.azure.toml" # Default config uses ETE AZURE_OPENAI_API_KEY="" AZURE_OPENAI_ENDPOINT="" OPENAI_API_VERSION="2024-08-01-preview" ``` ### Option 4: LiteLLM Support CUGA supports LiteLLM through the OpenAI configuration by overriding the base URL: 1. Add to your `.env` file: ```env # LiteLLM Configuration (using OpenAI settings) OPENAI_API_KEY=your-api-key AGENT_SETTING_CONFIG="settings.openai.toml" # Override for LiteLLM MODEL_NAME=Azure/gpt-4o # Override model name OPENAI_BASE_URL=https://your-litellm-endpoint.com # Override base URL OPENAI_API_VERSION=2024-08-06 # Override API version ``` ### Option 5: Groq Support **Setup Instructions:** 1. Create an account at [groq.com](https://groq.com) 2. Generate an API key from your [API keys page](https://console.groq.com/keys) 3. Add to your `.env` file: ```env # Groq Configuration GROQ_API_KEY=your-groq-api-key-here AGENT_SETTING_CONFIG="settings.groq.toml" # Optional override MODEL_NAME=llama-3.1-70b-versatile # Override model name ``` **Default Values:** - Model: Configured in `settings.groq.toml` - Base URL: Groq's default endpoint ### Option 6: OpenRouter Support **Setup Instructions:** 1. Create an account at [openrouter.ai](https://openrouter.ai) 2. Generate an API key from your account settings 3. Add to your `.env` file: ```env # OpenRouter Configuration OPENROUTER_API_KEY=your-openrouter-api-key AGENT_SETTING_CONFIG="settings.openrouter.toml" OPENROUTER_BASE_URL="https://openrouter.ai/api/v1" # Optional override MODEL_NAME=openai/gpt-4o # Override model name ``` ### Option 7: RITS Support **Setup Instructions:** 1. Obtain a RITS API key from the RITS platform admin. 2. Add to your `.env` file: ```env # RITS Configuration — direct RITS endpoint (default preset) RITS_API_KEY=your-rits-api-key # pragma: allowlist secret AGENT_SETTING_CONFIG="settings.rits.toml" # Optional overrides — update MODEL_NAME and RITS_BASE_URL together for # direct RITS setups, since each model has a model-specific URL path. # Setting MODEL_NAME alone will leave you pointed at the previous model's URL. MODEL_NAME=google/gemma-4-31B-it RITS_BASE_URL="https://inference-3scale-apicast-production.apps.rits.fmaas.res.ibm.com/google-gemma-4-31b-it-a100/v1" ``` To front RITS with a local LiteLLM proxy instead, use `AGENT_SETTING_CONFIG="settings.rits.proxy.toml"`. **Default Values:** - Model: `google/gemma-4-31B-it` (direct preset) - Base URL: gemma-4-31B-it `/v1` endpoint on the RITS 3scale apicast host (direct preset) - Local proxy URL: `http://localhost:4000` (proxy preset) ### Option 8: watsonx Orchestrate (wxO) Support Routes every agent role's LLM calls through your watsonx Orchestrate tenant instead of a provider directly — calls become traced/observable in the tenant, pass through its guardrails, and are billed against its entitlement. **Setup Instructions:** 1. Install the optional SDK (requires Python >= 3.11): `pip install "cuga[wxo]"` or `uv sync --extra wxo`. 2. In watsonx Orchestrate, go to **Settings -> API details** and click **Generate API key**; copy the **Service instance URL** shown on the same page. 3. Add to your `.env` file: ```env # watsonx Orchestrate Configuration WXO_API_KEY=your-wxo-api-key # pragma: allowlist secret WXO_INSTANCE_URL=https://api.dl.watson-orchestrate.ibm.com/instances/your-instance-id AGENT_SETTING_CONFIG="settings.wxo.toml" # Optional override — model ids are provider-prefixed per your tenant's Settings -> Models list MODEL_NAME=groq/openai/gpt-oss-120b # e.g. the Groq-hosted variant, ~25% faster than the Bedrock one ``` To target a local ADK dev server instead of a hosted tenant, set `WXO_INSTANCE_URL=http://localhost:4321` and omit `WXO_API_KEY` — local instances are auto-detected and don't require a key. **Default Values:** - Model: `watsonx/openai/gpt-oss-120b` - Instance URL: `http://localhost:4321` (local ADK dev server) ## Using CUGA in mainland China CUGA does not require OpenAI: OpenAI-compatible endpoints work through the standard override, including Chinese providers. Two services are commonly unreachable from mainland China and have workarounds: - **PyPI is slow:** use a local mirror, for example `pip install cuga -i https://pypi.tuna.tsinghua.edu.cn/simple`. With uv, set `UV_DEFAULT_INDEX=https://pypi.tuna.tsinghua.edu.cn/simple` rather than adding a `uv.toml` to the project root, which would make uv ignore the `[tool.uv]` section of `pyproject.toml`. A changed index re-resolves `uv.lock`; don't commit that change. torch and torchvision still come from the PyTorch CPU index pinned in `pyproject.toml`, not the mirror. Without Python 3.12, uv downloads it from GitHub, which can be slow; install it yourself first or set `UV_PYTHON_INSTALL_MIRROR`. - **Hugging Face is blocked:** with the default `[storage.embedding] provider = "local"`, policies and knowledge download small embedding models from Hugging Face on first use. Set `HF_ENDPOINT=https://hf-mirror.com`, or preload the models ahead of time (this also needs `HF_ENDPOINT` set): ```bash export FASTEMBED_CACHE_PATH="$HOME/.cache/cuga/fastembed" uv run python src/scripts/preload_models.py ``` The export points the script at the cache directory CUGA reads; without it, the models land in a temporary directory and CUGA downloads them again on first use. The script skips a failed download instead of stopping, so check that no `fastembed` line in its output says `preload skipped`. Example `.env` for Alibaba Model Studio (Qwen), replacing the default Groq lines; the key must match the endpoint's region: ```dotenv AGENT_SETTING_CONFIG=settings.openai.toml OPENAI_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1 OPENAI_API_KEY=your-dashscope-api-key # pragma: allowlist secret MODEL_NAME=qwen-plus ``` If Discord is unreachable, use [GitHub Discussions](https://github.com/cuga-project/cuga-agent/discussions). A Chinese-language summary of the README is at [README.zh-CN.md](README.zh-CN.md). ## Configuration Files CUGA uses TOML configuration files located in `src/cuga/configurations/models/`: - `settings.openai.toml` - OpenAI configuration (also supports LiteLLM via base URL override) - `settings.watsonx.toml` - WatsonX configuration - `settings.azure.toml` - Azure OpenAI configuration - `settings.groq.toml` - Groq configuration - `settings.openrouter.toml` - OpenRouter configuration - `settings.rits.toml` - RITS configuration (direct endpoint) - `settings.rits.proxy.toml` - RITS configuration (local LiteLLM proxy fronting RITS) - `settings.wxo.toml` - watsonx Orchestrate configuration Each file contains agent-specific model settings that can be overridden by environment variables.
## Agent skills Agent skills are reusable instruction packs: each skill is a `SKILL.md` file with YAML frontmatter and markdown body. CUGA discovers them at startup, lists short descriptions in the agent prompt, and exposes a **`load_skill`** tool so the model pulls the full body only when a task matches that skill—similar to opening a playbook instead of stuffing every procedure into the system prompt. **Where skills live** Configure a single root in [`settings.toml`](../../src/cuga/settings.toml) (`[skills] root`, default **`cuga`**) or via **`DYNACONF_SKILLS__ROOT`** env var. CUGA scans one directory only — no merge across paths. | `skills.root` | Project path | Use when | | ------------- | ------------ | -------- | | `cuga` (default) | `/skills/**/SKILL.md` (e.g. `.cuga/skills/`) | CUGA-native layout; keeps skills with other CUGA config | | `agents` | `.agents/skills/**/SKILL.md` | [skills.sh](https://skills.sh) / `npx skills` universal installs | | `global_agents` | `~/.config/agents/skills/` | Global `npx skills -g` installs | | `global_cuga` | `~/.config/cuga/skills/` | Legacy global CUGA path | **Why default `cuga`?** CUGA already uses `.cuga/` for policy, workspace, and uploads. Keeping skills there avoids colliding with other agents that write `.agents/skills/`. If you install skills with `npx skills`, set `root = "agents"` or copy skills into `.cuga/skills/`. **`SKILL.md` shape** Frontmatter must include **`name`** and **`description`** (shown in the available-skills list). You can add optional **`requirements`** (string or list). The markdown below the frontmatter is the full instruction text returned by `load_skill`. **Try it** From the repository root: ```bash npx skills add https://github.com/anthropics/skills --skill pptx -a universal cuga start demo_skills ``` That preset turns on skills for the run and uses **`[advanced_features] sandbox_mode`** in [`settings.toml`](../../src/cuga/settings.toml) (default **`native`**). For **`opensandbox`**, run **`uv sync --extra opensandbox`** first so the client deps are installed and OpenSandbox can be reached. Skills do not turn off the security checks on generated code. Those checks have their own setting, **`[execution] enforce_code_security`** (default **`true`**), which is separate from `sandbox_mode`: `sandbox_mode` picks where code runs, and `enforce_code_security` picks whether the import allowlist, AST checks and restricted builtins apply. Set it to `false` only for trusted runs such as AppWorld benchmarks. For Docker/Podman isolation instead, use **`uv sync --group sandbox`** then **`cuga start demo --sandbox`** and enable **`[skills]`**—see [Configurations](#configurations). For settings you keep beyond a one-off run, configure `[skills]` and `[advanced_features]` in [`settings.toml`](../../src/cuga/settings.toml) (Dynaconf env overrides apply as documented there). **Install a sample skill (Anthropic `pptx`)** The [Anthropic skills repo](https://github.com/anthropics/skills) publishes ready-made folders such as [`skills/pptx`](https://github.com/anthropics/skills/tree/main/skills/pptx) (`SKILL.md`, scripts, and helper markdown). Install the `pptx` skill into the project-local universal agent skills folder from the repository root: ```bash npx skills add https://github.com/anthropics/skills --skill pptx -a universal ``` This creates `.agents/skills/pptx/SKILL.md` for the current project (or set `[skills] root = "agents"` in `settings.toml`). To use the CUGA default layout instead, copy or symlink skills into `.cuga/skills/`. Restart `cuga start demo_skills` (or your app) so skills are rescanned. Add `-g` if you want the skill installed globally under `~/.config/agents/skills/` instead. --- ## Using CUGA as a Python SDK CUGA can be easily integrated into your Python applications as a library. The SDK provides a clean, minimal API for creating and invoking agents with custom tools. **SDK Documentation**: [SDK Documentation](https://docs.cuga.dev/docs/build/cuga-agent/) ### Quick Start ```python from cuga import CugaAgent from langchain_core.tools import tool import asyncio @tool def add_numbers(a: int, b: int) -> int: '''Add two numbers together''' return a + b @tool def multiply_numbers(a: int, b: int) -> int: '''Multiply two numbers together''' return a * b # Create agent with tools agent = CugaAgent(tools=[add_numbers, multiply_numbers]) async def main(): # Add an Intent Guard to block specific operations await agent.policies.add_intent_guard( name="Block Delete Operations", description="Prevents deletion of critical data", keywords=["delete", "remove", "erase"], response="Deletion operations are not permitted for security reasons.", priority=100 # Higher priority = checked first ) # Add a Playbook to provide step-by-step guidance for complex workflows await agent.policies.add_playbook( name="Budget Analysis Workflow", description="Multi-step process for analyzing financial budgets", natural_language_trigger=["When user asks to analyze their budget"], content="""# Budget Analysis Workflow ## Step 1: Calculate Total Expenses - Sum all expense categories using add_numbers - Document each category amount ## Step 2: Calculate Total Revenue - Sum all revenue streams using add_numbers - Include all income sources ## Step 3: Calculate Profit Margin - Use multiply_numbers to calculate profit (revenue - expenses) - Calculate margin percentage ## Step 4: Generate Recommendations - Compare against target budget - Identify areas for optimization - Provide actionable insights""", priority=50 ) result = await agent.invoke("Analyze my budget: expenses are 5000 and 3000, revenue is 12000") print(result.answer) # The agent's response if __name__ == "__main__": asyncio.run(main()) ``` ### Key Features - **Simple API**: `CugaAgent(tools=[...])` → `await agent.invoke(message)` - **Streaming**: Monitor execution in real-time with `agent.stream()` - **State Isolation**: Per-user sessions with `thread_id` - **Durable Conversations**: Continue a `thread_id` after a restart with `checkpointer=` (see [SDK: durable conversations](#sdk-durable-conversations)) - **LangGraph Integration**: Access underlying graph for advanced use cases - **Flexible Tools**: Direct tools or custom tool providers - **Policy System**: Comprehensive policy framework with 5 types: - **Intent Guard**: Block or modify specific user intents - **Playbook**: Step-by-step guidance for complex workflows - **Tool Approval**: Require human approval before executing tools - **Tool Guide**: Enhance tool descriptions with additional context - **Output Formatter**: Format agent responses based on triggers **Documentation**: [SDK Guide](https://docs.cuga.dev/docs/build/cuga-agent/) | [Policies Guide](https://docs.cuga.dev/docs/build/policies/) ### Run Receipt Answer "where did the tokens and the time go?" without an external observability stack. Enable the flag and every `invoke()` returns a per-run receipt: ```toml # settings.toml [advanced_features] run_receipt = true # default: false — zero overhead when disabled ``` ```python result = await agent.invoke("how many accounts are there?") print(result.receipt) # ┌─ Run Receipt ─────────────────────────────────┐ # │ model: gpt-4o │ # │ tokens: 18,342 in / 2,101 out (20,443) │ # │ llm calls: 7 tool calls: 4 │ # │ time: 9.4s (llm 6.1s / tools 2.8s) │ # │ slowest tool: get_accounts 1.9s │ # └───────────────────────────────────────────────┘ result.receipt.input_tokens # 18342 result.receipt.tool_timings # per-tool call counts and total durations ``` **Tokens, not cost** — CUGA runs against self-hosted and internal deployments whose prices we don't know, so multiply by your own rates. `cache_read_tokens` and `reasoning_tokens` are included when the provider reports them. Enabling it puts tool tracking in a **timings-only** mode unless you passed `track_tool_calls=True`: only name, app and duration are recorded — never arguments, results or errors. Coverage matches `track_tool_calls` (registry/MCP tools and `@tracked_tool` functions). ### Configuring the final answer Everything about the final answer lives behind four knobs — this table is the map: | What | Where | Notes | |---|---|---| | Which LLM composes it | `[agent.final_answer.model]` (model TOMLs) | existing | | Whether the composer runs | `features.final_answer` (mode TOMLs) | `fast` mode disables it | | Guidance for the composer | `[final_answer].instructions` | fills the composer prompt's instructions slot — **ignored in default Lite mode**; use `special_instructions` / SDK `final_answer="..."` there | | Deterministic shaping | `[final_answer].function` | dotted path to a pure `(str) -> str` — imported **and called** with the answer, so point only at trusted code | ```toml [final_answer] instructions = "Answer with the bare value only — no units, no prose." function = "my_pkg.formats.bare" # applied to the delivered answer, before citations ``` Or from the SDK: ```python agent = CugaAgent(final_answer="Answer with the bare value only.") # LLM guidance agent = CugaAgent(final_answer=my_fn) # deterministic function agent = CugaAgent(final_answer=FinalAnswerConfig(instructions="...", function=my_fn)) ``` The function contract: **pure and deterministic** (idempotent recommended), applied once per delivered answer, and it can never break delivery — any failure logs and returns the answer unchanged. It runs after harmony-token sanitization and before citation resolution; sanitization is not replaceable. `instructions` guide the `FinalAnswerAgent` composer (full pipeline); in the default CugaLite mode the answer is composed by CugaLite itself — use `special_instructions` there (the SDK `final_answer="..."` form does this for you). Deterministic contracts (e.g. benchmark answer shapes) belong in `function`, not `instructions` — prompts cannot guarantee an exact string. Scope notes: answers synthesized by a `CugaSupervisor` itself (as opposed to forwarded sub-agent answers) are not shaped in this version. The AppWorld benchmark path keeps its own answer pipeline — its SDK post-processing re-extracts the answer and overwrites `InvokeResult.answer`, so in-graph shaping does not survive there. The chat transcript deliberately carries the pre-finalize text — the function shapes `result.answer`, and is not a redaction mechanism. ### Knowledge Base CUGA includes a built-in knowledge base powered by LangChain and local vector stores. **Docling** is integrated for document ingestion: it parses and normalizes PDFs, Office files, HTML, Markdown, images, and other supported types before chunking and embedding, so the pipeline stays self-contained with no external document services. When enabled, the agent can search, ingest, and manage documents. The default embedding model is `intfloat/multilingual-e5-small`, which covers about 100 languages and runs locally as an int8 ONNX model. Knowledge bases built with another model keep that model: a server keeps the model its saved agent config names, and an SDK knowledge base keeps the model it was built with. To move a server agent to another model, change it in the knowledge settings and select **Re-index now**. To rebuild an SDK knowledge base, add its documents again in new storage: a new `knowledge.persist_dir` and, with `storage.mode = "prod"`, a new database for `storage.postgres_url` and for `knowledge.pgvector_connection_string` if you set it. The `storage.postgres_url` database also holds other data, such as policies, so move what you still need first. The rebuilt knowledge base uses the configured model: the profile's, or `DYNACONF_KNOWLEDGE__EMBEDDINGS__MODEL` when that is set. Offline, searching an existing knowledge base needs only the model it was built with, so an air-gapped install keeps searching it after an upgrade. Everything else must be in the model cache before going offline: the model for new knowledge bases (`multilingual-e5-small` under the `standard` and `speed` profiles), Docling's models to parse PDFs, and, under `balanced` or `max_quality`, that profile's embedding and reranker models. The preload script in [Using CUGA in mainland China](#using-cuga-in-mainland-china) fetches the first two; for the others, start CUGA once with that profile while online, which loads them. **Try the knowledge demo:** same as the main demo but with the knowledge engine on (upload documents and query them): ```bash cuga start demo_knowledge ``` > Walk through a full HR-Benefits demo with sample documents and example prompts: > **[docs/examples/knowledge_demo/](../../docs/examples/knowledge_demo)** Knowledge is **enabled by default** via `settings.toml`. The SDK auto-injects knowledge tools and awareness into the agent, so it knows what documents are available and how to search them. #### Programmatic Access ```python from cuga import CugaAgent import asyncio agent = CugaAgent(enable_knowledge=True) async def main(): # Ingest a document await agent.knowledge.ingest("/path/to/quarterly_report.pdf") # The agent now automatically knows about this document result = await agent.invoke("What does the report say about Q4 revenue?") print(result.answer) # Agent searches knowledge base and answers # Direct search results = await agent.knowledge.search("Q4 revenue figures") for r in results: print(f"{r['filename']} (page {r['page']}): {r['text'][:100]}") # List documents docs = await agent.knowledge.list_documents() # Clean up await agent.aclose() asyncio.run(main()) ``` #### Session-Scoped Knowledge Documents can be scoped to a specific conversation thread: ```python thread_id = "user-session-123" # Ingest into session scope (temporary, per-conversation) await agent.knowledge.ingest("/path/to/file.pdf", scope="session", thread_id=thread_id) # Search session documents results = await agent.knowledge.search("query", scope="session", thread_id=thread_id) # Agent scope (default) — permanent, shared across conversations await agent.knowledge.ingest("/path/to/file.pdf", scope="agent") ``` #### How search finds documents With the `standard` (default), `balanced` and `max_quality` profiles, every search combines two kinds of match and merges the results: **meaning** (embeddings, so "time off" finds "vacation policy") and **keywords** (exact words, so `INV-2026-0042`, a product name or a rare term finds the document that contains it). Both run on local storage (SQLite) and on production storage (Postgres with pgvector), and both match the same words. Keyword matching works the same way in every language: - Case, full-width forms and the accents or vowel points people usually leave out do not matter: `cafe` finds "café", `STRASSE` finds "Straße", `שלום` finds "שָׁלוֹם". - Words in Hindi, Bengali, Telugu, Tamil and other Indic scripts match as whole words. - Chinese, Japanese, Korean and Thai words are found inside sentences without spaces. - Identifiers match however they are written: `ABC-123` also finds "abc_123", "ABC-123" and an "ABC-123." that ends a sentence, but not "ABC-124". Stemming is not applied, so `invoices` does not match "invoice"; the meaning match usually covers it. Existing collections, on either backend, get their keyword index automatically the first time they are searched or added to. The `speed` profile uses meaning only (`hybrid_mode = "off"` in its profile file under `src/cuga/configurations/knowledge/knowledge_profiles/`). #### Disabling Knowledge ```python agent = CugaAgent(tools=[my_tools], enable_knowledge=False) ``` #### Supported Document Types PDF, DOCX, XLSX, PPTX, HTML, Markdown, images, and more (via Docling). #### Embedding providers + tuning The knowledge engine ships four built-in provider categories — `fastembed` (default, local), `huggingface` (local), `openai` (network, accepts any OpenAI-compatible endpoint via `base_url`), and `ollama` (network) — plus `openrouter` for one-key-many-models access to embedding models on [openrouter.ai/models](https://openrouter.ai/models?output_modalities=embeddings). Provider, model, batch size, and concurrency are all set under `[knowledge.embeddings]` in `settings.toml` or via CLI overrides (`--embeddings-provider`, `--embeddings-base-url`, `--embeddings-api-key`, `--embeddings-model`, `--embeddings-batch-size`, `--embeddings-concurrency`). > **Full provider matrix + tuning guide** — see the > [knowledge engine docs](https://docs.cuga.dev/docs/build/knowledge/). > Switching provider or model invalidates existing vectors (different > dim), so the manage UI surfaces a "Re-index recommended" banner > automatically. ### SDK: durable conversations By default `CugaAgent` keeps conversation state in an in-process `MemorySaver`, so a thread is gone when the process exits. Pass an async LangGraph saver with the keyword-only `checkpointer=` argument, then call the agent again with the same `thread_id`, from the same process or a new one. The thread's messages, variables, and any pending approval are loaded from the saver. ```python import asyncio import aiosqlite from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver from cuga import CugaAgent from cuga.backend.storage.checkpoint.serde import build_checkpoint_serde async def main(): async with aiosqlite.connect("./agent_state.db") as conn: saver = AsyncSqliteSaver(conn, serde=build_checkpoint_serde()) agent = CugaAgent(tools=[...], checkpointer=saver) await agent.invoke("What is the revenue for account acc_01?", thread_id="t-1") # Later, or in another process with the same file: result = await agent.invoke("And how does that compare to last year?", thread_id="t-1") print(result.answer) asyncio.run(main()) ``` - Any `BaseCheckpointSaver` with async methods works, for example `AsyncPostgresSaver` (call `await saver.setup()` once to create its tables). Sync-only savers (`SqliteSaver`, `PostgresSaver`) are rejected with `TypeError` when the graph is compiled. - `build_checkpoint_serde()` registers CUGA's state types. Without it LangGraph logs a warning for each one, and blocks them when `LANGGRAPH_STRICT_MSGPACK=true`. Your own pydantic models, dataclasses, and Enums stored in variables come back as plain values unless you add them to the allowlist (`CUGA_ALLOWED_MSGPACK_TYPES`). - `CugaSupervisor(checkpointer=...)` works the same way for the supervisor graph. Its internal sub-agents keep their own in-memory savers. - **The SDK does not check ownership, expire threads, or validate a paused thread against changed code.** Anyone who can pass a `thread_id` can continue that conversation, so use unguessable IDs and check ownership in your application. Delete a thread with `await saver.adelete_thread(thread_id)`. - **Resume an approval** by building the agent with the same tools, policies and saver, and calling `agent.invoke(None, thread_id=thread_id, action_response=...)`. On the compiled graph, use `Command(resume=action_response.model_dump())`; `aupdate_state()` followed by `ainvoke(None)` does not resume the pause. - **Use the async state methods.** Async savers refuse synchronous calls on the event loop, so `agent.graph.get_state()` / `update_state()` must become `aget_state()` / `aupdate_state()`. --- ## CugaSupervisor (Multi-Agent) Orchestrate multiple agents with a single supervisor: delegate tasks to specialized sub-agents, mix local agents with remote A2A agents, and pass data between them. **Documentation**: [CugaSupervisor](https://docs.cuga.dev/docs/build/cuga-supervisor/) **Try the supervisor demo:** run the multi-agent demo (CRM + email sub-agents) with: ```bash cuga start demo_supervisor ``` > [!IMPORTANT] > **Sub-agents are scoped to the registry apps they name.** An agent that lists `apps:` or > `mcp_servers:` receives tools from *those* only; an agent that lists neither still receives > everything. > > Scoping on `apps:` has worked this way since the multi-agent supervisor landed. What is new is > that **`mcp_servers:` entries now count as named apps too.** They did not before, so an agent > declaring only `mcp_servers:` and no `apps:` received the whole registry regardless — if such a > roster named one server while relying on tools from another, it worked by accident and will now > see only what it names. Add the missing entry to `apps:` or `mcp_servers:`. > > Names are matched exactly as written — an app name is whatever key your MCP config registers it > under, and nothing rewrites it in transit. ### Quick Start ```python from cuga import CugaAgent, CugaSupervisor from langchain_core.tools import tool import asyncio @tool def get_customers(limit: int = 10) -> str: """Fetch top customers from CRM with name, email, and revenue. Returns a formatted string.""" customers = [ "Alice (alice@example.com, $250,000)", "Bob (bob@example.com, $180,000)", "Carol (carol@example.com, $120,000)", "Dave (dave@example.com, $95,000)", "Eve (eve@example.com, $88,000)", ] top = customers[: min(limit, len(customers))] return "Top customers by revenue: " + "; ".join(f"{i+1}. {c}" for i, c in enumerate(top)) @tool def send_email(to: str, body: str) -> str: """Send an email. Returns confirmation.""" return f"Email sent successfully to {to}" async def main(): crm_agent = CugaAgent(tools=[get_customers]) crm_agent.description = "CRM and customer data" email_agent = CugaAgent(tools=[send_email]) email_agent.description = "Sending emails and notifications" supervisor = CugaSupervisor(agents={ "crm": crm_agent, "email": email_agent, }) result = await supervisor.invoke("Get our top 5 customers by revenue, then send the top customer a thank-you email") print(result.answer) asyncio.run(main()) ``` To add a remote agent via A2A, pass an external config in `agents`: `"analytics": {"type": "external", "description": "...", "config": {"a2a_protocol": {"endpoint": "http://localhost:9999", "transport": "http"}}}`. ### Supervisor features - **Delegation**: Supervisor hands work to sub-agents and can pass variables between them when needed. - **Internal + external**: Combine local `CugaAgent` instances with external agents via **A2A**, task-only or variables in metadata if enabled. - **Variable passing**: Use `variables=["var_name"]` to pass previous agent outputs or context to the next agent (for internal agents, or A2A when `pass_variables_a2a` is enabled in settings). - **Agent cards**: For A2A agents, capabilities and description are taken from the agent card and shown in the supervisor prompt. You can also load agents from YAML with `CugaSupervisor.from_yaml("path/to/config.yaml")`. Enable the supervisor in `settings.toml` under `[supervisor]` when using the server. ### Agent Client Protocol (ACP) over stdio CUGA implements stable v1 of the [Agent Client Protocol](https://agentclientprotocol.com/) in both local stdio directions. Install the optional SDK with `pip install "cuga[acp]"` (or `uv sync --extra acp` from this repository). To use CUGA from an ACP-compatible editor, configure a custom external agent whose command is the installed `cuga-acp` executable: ```json { "agent_servers": { "CUGA": { "type": "custom", "command": "/absolute/path/to/cuga-acp", "args": [], "env": {} } } } ``` To let a CUGA supervisor delegate to a local ACP coding agent, add an external agent to its YAML roster: ```yaml agents: - name: coding-agent description: "External coding agent over ACP stdio" acp_protocol: enabled: true command: your-acp-agent args: ["--acp"] cwd: . env: [YOUR_API_KEY] startup_timeout: 15 prompt_timeout: 120 shutdown_grace_period: 5 ``` Replace `your-acp-agent` with the command for the coding agent you installed (for example, `gemini --acp`). `env` lists variable names to inherit; secret values do not belong in YAML. Commands are executed directly without a shell, `cwd` must remain inside CUGA's workspace, and every delegation has bounded startup, prompt, and shutdown phases. ACP operation permissions remain independent of supervisor plan approval. An interactive run pauses for the existing CUGA tool-approval action; a headless run denies the request and cleans up the process. Approval is single-use, and stale, duplicate, or expired resumes fail closed. The current integration is text-only. It does not advertise image, audio, embedded-context, filesystem, terminal, or ACP-over-MCP support. Session persistence and remote HTTP/WebSocket transports are deferred; both supported directions use newline-delimited JSON-RPC over stdio. stdout is reserved for protocol frames and bounded diagnostics use stderr. See the [ACP stdio example](../../docs/examples/acp_stdio/README.md) for editor setup, supervisor configuration, cancellation checks, limitations, and troubleshooting. If startup fails, confirm the executable path and optional extra; for protocol errors, remove stdout banners; for timeouts, check login prompts before increasing bounds; for stale permission resumes, start a new delegation. --- ## Configurations
Running with a secure code sandbox Cuga supports isolated code execution using Docker/Podman containers for enhanced security. 1. **Install container runtime**: Download and install [Rancher Desktop](https://rancherdesktop.io/) or Docker. 2. **Install sandbox dependencies**: ```bash uv sync --group sandbox ``` 3. **Start with remote sandbox enabled**: ```bash cuga start demo --sandbox ``` This automatically configures Cuga to use Docker/Podman for code execution instead of local execution. 4. **Test your sandbox setup** (optional): ```bash # Test local sandbox (default) cuga test-sandbox # Test remote sandbox with Docker/Podman cuga test-sandbox --remote ``` You should see the output: `('test succeeded\n', {})` **Note**: Without the `--sandbox` flag, Cuga uses local Python execution (default), which is faster but provides less isolation.
Running with E2B Cloud Sandbox CUGA supports [E2B](https://e2b.dev) for cloud-based code execution in secure, ephemeral sandboxes. This provides better isolation than local execution while being faster than Docker/Podman containers. ### Prerequisites: 1. **Get an E2B API key**: - Sign up at [e2b.dev](https://e2b.dev) - Create an API key from your [dashboard](https://e2b.dev/dashboard) 2. **Set up the E2B template**: ```bash # Install E2B CLI npm install -g @e2b/cli # Login with your API key e2b auth login # Create a template (one-time setup) # This creates a 'cuga-langchain' template that CUGA uses e2b template build --name cuga-langchain ``` 3. **Install E2B dependencies**: ```bash uv sync --group e2b ``` 4. **Configure environment**: Add to your `.env` file: ```env E2B_API_KEY=your-e2b-api-key-here ``` ### Exposing Registry to E2B (Required) E2B runs in the cloud and needs to call your local API registry to execute tools. You need to expose your local registry publicly using a tunneling service like [ngrok](https://ngrok.com). #### Option 1: Expose Registry Directly (Port 8001) Best if you have multiple ports available: ```bash # In a separate terminal, start ngrok tunnel to registry ngrok http 8001 # You'll get a public URL like: https://abc123.ngrok.io # Copy this URL ``` Then edit `./src/cuga/settings.toml`: ```toml [server_ports] function_call_host = "https://abc123.ngrok.io" # Your ngrok URL ``` #### Option 2: Expose CUGA Port with Proxy (Port 7860) Best if you're restricted to 1 port - CUGA will proxy calls to the registry: ```bash # In a separate terminal, start ngrok tunnel to CUGA ngrok http 7860 # You'll get a public URL like: https://xyz789.ngrok.io # Copy this URL ``` Then edit `./src/cuga/settings.toml`: ```toml [server_ports] function_call_host = "https://xyz789.ngrok.io" # Your ngrok URL ``` CUGA automatically proxies `/functions/call` requests to the registry when using the CUGA port. ### Enable E2B in Settings Edit `./src/cuga/settings.toml`: ```toml [advanced_features] e2b_sandbox = true e2b_sandbox_mode = "per-session" # Options: "per-session" | "single" | "per-call" e2b_sandbox_ttl = 600 # Cache TTL in seconds (10 minutes) ``` ### Sandbox Modes: - **`per-session`** (default): One sandbox per conversation thread, cached for reuse - **`single`**: Single shared sandbox across all threads (most cost-effective) - **`per-call`**: New sandbox for each execution (most isolated, highest cost) ### Start CUGA with E2B: ```bash # Make sure ngrok is running in another terminal cuga start demo ``` E2B will automatically execute code in cloud sandboxes. You'll see logs indicating "CODE SENT TO E2B SANDBOX" when E2B is active. ### Troubleshooting: - **Error: "function_call_host not configured"**: Make sure you've set `function_call_host` in settings.toml with your ngrok URL - **Tool execution fails**: Verify ngrok is running and the URL in settings.toml matches your ngrok URL - **Connection timeout**: Check that your firewall allows ngrok connections **Benefits of E2B**: - No Docker/Podman required - Faster than container-based sandboxing - Cloud-native with automatic scaling - Better isolation than local execution - Supports per-session caching for cost optimization **Note**: E2B is a paid service with a free tier. Check [e2b.dev/pricing](https://e2b.dev/pricing) for details.
Remote execd sandbox: isolation model With **`[advanced_features] sandbox_mode = "execd"`**, or with the sandbox turned on in **Manage → Code sandbox**, generated Python, `run_command`, the filesystem tools and the workspace panel run in a remote sandbox behind sandbox-api. Connection settings (`execd_url`, `execd_api_key`, `sandbox_secret_dir`, `sandbox_callback_url`, `execd_package_index`) are described in [`settings.toml`](../../src/cuga/settings.toml). The connection comes from the deployment: the sandbox secret mounted at `sandbox_secret_dir`, or `execd_url` / `execd_api_key`. **Manage → Code sandbox** appears only when one of them is configured, and only switches the sandbox on or off. It does not take a URL or key. **What keeps conversations apart.** The sandbox does, not CUGA. Each conversation gets its own kernel (a separate process) and its own workspace, `/workspace/`. Code in one conversation cannot read, change or list another conversation's files, and cannot reach execd or Jupyter inside the sandbox. This requires a sandbox-api build that passes its workspace isolation test (`scripts/25_test_workspace_isolation.sh` in the sandbox-api repo). **What does not.** Inside its own conversation, agent code runs with the same restrictions as under the local executor: safe builtins, the import allowlist, and only its own tools and variables, not the kernel's helpers. CUGA also answers only the tools a code block names, so tool approval sees every tool that runs. These restrictions run in the same process as the code, so they are not a boundary. Treat the sandbox's filesystem and network policy as the security boundary. **Tools.** Tools run in CUGA, not in the sandbox. The sandbox calls them back at `{sandbox_callback_url}/sandbox/tools/call`. Each code block carries its own signed token, so one conversation cannot call another conversation's tools. **Before you turn it on:** - Allow egress from the sandbox only to `sandbox_callback_url` and to the package index. Egress is denied by default. - Use a sandbox-api version that accepts `envs` on `POST /command`. CUGA sends the venv, the package index and the file-tool operands there. - Do not put credentials in `execd_package_index`. Agent code can read it. - Packages that a conversation installs go into its own venv. The image's packages are shared. - Deleting a conversation releases its kernel. Turning the sandbox off releases the kernels this process holds; kernels from before a restart or on other replicas stay until sandbox-api's TTL. Workspace files stay in the sandbox either way. See the [executors README](../../src/cuga/backend/cuga_graph/nodes/cuga_lite/executors/README.md#isolation-model-execd-mode) for details.
Code generation profiles - fast / balanced / accurate ## Reasoning profiles | Profile | File | Description | | ---------- | -------------------------------------- | ----------------------------------------------- | | `fast` | `./configurations/modes/fast.toml` | Optimized for speed | | `balanced` | `./configurations/modes/balanced.toml` | Balance between speed and precision _(default)_ | | `accurate` | `./configurations/modes/accurate.toml` | Optimized for precision | | `custom` | `./configurations/modes/custom.toml` | User-defined settings | These profiles tune code generation, reflection, and related feature flags. Graph routing is handled by the entry graph (CugaLite, CugaSupervisor, or CugaBrowser).
Task Mode Configuration - Switch between API/Web/Hybrid modes ## Available Task Modes | Mode | Description | | -------- | --------------------------------------------------------------------------- | | `api` | API-only mode - executes API tasks _(default)_ | | `web` | Web-only mode - executes web tasks using browser extension | | `hybrid` | Hybrid mode - executes both API tasks and web tasks using browser extension | ## How Task Modes Work ### API Mode (`mode = 'api'`) - Opens tasks in a regular web browser - Best for API/Tools-focused workflows and testing ### Web Mode (`mode = 'web'`) - Interface inside a browser extension (available next to browser) - Optimized for web-specific tasks and interactions - Direct access to web page content and controls ### Hybrid Mode (`mode = 'hybrid'`) - Opens inside browser extension like web mode - Can execute both API/Tools tasks and web page tasks simultaneously - Starts from configurable URL defined in `demo_mode.start_url` - Most versatile mode for complex workflows combining web and API operations ## Configuration Edit `./src/cuga/settings.toml`: ```toml [demo_mode] start_url = "https://opensource-demo.orangehrmlive.com/web/index.php/auth/login" # Starting URL for hybrid mode [advanced_features] mode = 'api' # 'api', 'web', or 'hybrid' ```
🔍 Tool Shortlisting ## What it is When an app exposes many tools, CUGA shrinks the set before the model sees it. This happens in two places: `find_tools` (the agent asking "what tools exist for X?") and the `bind_tools` provider cap. Both are pluggable. ## Strategies | Strategy | How it ranks | Cost | |---|---|---| | `llm` (default) | asks the model | one LLM call per shortlist | | `embedding` | local cosine similarity | no LLM call for ranking, ~65ms warm | | `hybrid` | cosine cuts to `top_k`, then the LLM picks | one LLM call, much smaller prompt | `embedding` compares one vector built from your question against one vector per tool (name + description + parameter names + return field names). It is strong at **recall** but weak at separating near-identical tools such as `get_contacts` (list) and `get_contact` (by id) — so `hybrid` is usually the better choice for discovery, and `embedding` for the provider cap where only "don't drop the needed tool" matters. Embeddings are local by default (`BAAI/bge-small-en-v1.5` via fastembed) — the same weights policies already load, so there is one ONNX session and nothing extra for airgapped preload to fetch. Ranking makes no network call and is not billed. Setting `embedding_provider = "openai"` trades that away for a hosted model. Either way the *agent* still calls an LLM for its own reasoning — only the shortlister's ranking step is affected. The first call while a local model is still downloading is served by `fallback_strategy`, so **a query never waits on a download**. In **server mode** the catalogue is embedded at startup and again whenever the tool list changes, so the first `find_tools` after boot uses cosine rather than falling back. Vectors are keyed by content hash, so adding a tool embeds one document rather than the whole catalogue. The SDK stays lazy. ## Configuration ### Every option | Key | Default | What it does | |---|---|---| | `strategy` | `"llm"` | `llm` \| `embedding` \| `hybrid` \| a dotted class path | | `fallback_strategy` | `"llm"` | Used when `strategy` cannot run (model still downloading, missing dependency) | | `threshold` | `128` | Engage the cosine stage only **above** this many candidates. `0` = always engage | | `top_k` | `128` | How many candidates the cosine stage keeps (also the `hybrid` prefilter width) | | `max_results` | `10` | `find_tools` only — how many tools are actually shown to the agent | | `min_score` | `0.15` | Cosine floor. Deliberately low: this is a **recall** filter, not a precision knob | | `query_weight` | `0.7` | Blend of step query vs. initial user message when embedding the query (0–1) | | `embedding_provider` | `"local"` | `local` (fastembed, offline, free) or `openai` | | `embedding_model` | `bge-small-en-v1.5` | Any fastembed model, or an OpenAI embedding model | ### Four ways to set it **Precedence, highest first:** 1. raw `shortlister_*` keys you set yourself in `configurable` 2. per-invoke `invoke(..., shortlister=...)` 3. constructor `CugaAgent(shortlister=...)` 4. `[shortlister.discovery]` / `[shortlister.bind_cap]` 5. `[shortlister]` — also where environment variables land 6. built-in defaults Raw keys sit **above** the SDK objects because `_apply_shortlister` merges with `setdefault`: a key you already placed in `configurable` is never overwritten. **1. `settings.toml`** — deployment-wide: ```toml [shortlister] strategy = "hybrid" top_k = 64 # Optional: different settings per call site. [shortlister.discovery] # find_tools strategy = "hybrid" [shortlister.bind_cap] # bind_tools provider cap strategy = "embedding" # no LLM round-trip per call_model ``` **2. Environment** — one-off or per-container: ```bash DYNACONF_SHORTLISTER__STRATEGY=hybrid DYNACONF_SHORTLISTER__TOP_K=64 ``` **3. SDK** — per agent, or per call: ```python from cuga import CugaAgent, Shortlister agent = CugaAgent(tools=[...], shortlister=Shortlister(strategy="hybrid")) await agent.invoke("...", shortlister=Shortlister(top_k=32)) # per-call override ``` **4. Raw `configurable`** — when driving the graph directly: ```python config = {"configurable": {"shortlister_strategy": "embedding", "shortlister_top_k": 32}} ``` ### Which strategy should I use? | Situation | Use | Why | |---|---|---| | Default / unsure | `llm` | Unchanged behavior; nothing to tune | | Large catalogue, accuracy matters | `hybrid` | Cosine cuts the prompt cost; the LLM still makes the final call | | Provider cap on every `call_model` | `embedding` | Removes an LLM round-trip per step, and works on models without native structured output | | Offline / airgapped | `embedding` or `hybrid` with a warm cache | Local model, no network at query time | ### Gotchas **At or below `threshold` candidates nothing changes** — the cosine stage does not run and shortlisting behaves exactly as it always has. Set `threshold = 0` to always engage the configured strategy. > **Two similarly-named thresholds.** `[shortlister] threshold` (128) decides when the *cosine stage* engages inside the shortlister. `advanced_features.shortlisting_tool_threshold` (35) decides when tools are *hidden behind `find_tools`* in the prompt. They are unrelated. **`top_k` never raises the provider cap.** At the `bind_tools` seam the caller's cap is a hard ceiling; a configured `top_k` can lower how many tools are bound, never push past what the provider accepts. **`max_results` exists for a reason.** `find_tools` renders each tool with full parameter and schema docs. Showing 128 of them would exceed `advanced_features.execution_output_max_length` and be silently truncated mid-render, so the rendered count is capped separately from `top_k`. **First call on a cold cache.** The embedding model (~90MB) downloads in the background and that call is served by `fallback_strategy`; subsequent calls use cosine. No query ever blocks on the download. ## Custom strategies Point `strategy` at a dotted class path, or pass an instance: ```python class MyShortlister: name = "mine" async def shortlist(self, request) -> "list[ShortlistCandidate]": ... agent = CugaAgent(tools=[...], shortlister=Shortlister(instance=MyShortlister())) ``` See `docs/design/pluggable-shortlister.md` for the full design.
🔁 Execution mode: CodeAct or native function calling ## What it is By default CUGA Lite works in **CodeAct**: the model writes a Python block and the sandbox runs it. `cuga_lite_execution_mode = "function_calling"` switches to native tool calls: the model emits `tool_calls`, CUGA translates them into a short internal block that the same sandbox runs (same approval check, VERIFY gate, budgets, tracker, timeout and variables), and replies with one `ToolMessage` per call id, so the model reads the results before it calls again or answers. The block is never shown to the model or persisted; its transcript stays native. Tools are advertised through `bind_tools`; a short dedicated prompt replaces the CodeAct prompt. **Step discipline** (`cuga_lite_step_discipline = "one_tool_per_step"`) works in both modes: only the first tool call of a step is attempted — success or error, that is the result the model reads before it decides the next call. CodeAct keeps the block's variables (including that first result); function-calling answers the extra calls with a "deferred" reply. ## Configuration | Key | Default | Values | |---|---|---| | `cuga_lite_execution_mode` | `"codeact"` | `codeact` \| `function_calling` (alias `fc`) | | `cuga_lite_step_discipline` | `"off"` | `off` \| `one_tool_per_step` | | `cuga_lite_fc_prompt_fragments` | `[]` | Opt-in prompt lines for function-calling mode. `evidence_first`: call a tool before answering, never answer from prior knowledge | Precedence, highest first: raw keys in `configurable` → per-invoke `invoke(..., execution_mode=..., step_discipline=...)` → constructor `CugaAgent(execution_mode=..., step_discipline=...)` → per-model runtime profile → `[advanced_features]` in `settings.toml` (also where `DYNACONF_ADVANCED_FEATURES__CUGA_LITE_EXECUTION_MODE` lands). An unknown value falls back to the default with a warning. ```python agent = CugaAgent(tools=[...], execution_mode="function_calling", step_discipline="one_tool_per_step") result = await agent.invoke("...") # native tool calls result = await agent.invoke("...", execution_mode="codeact") # per-call override ``` ## Gotchas - **Tool-approval policies** apply exactly as in CodeAct: the approval check runs on the translated block, so a policy on a tool name pauses the run before the call and the approved call resumes into the sandbox. - Bind mode `none` (the default) is upgraded in function-calling mode to advertise exactly the tools the sandbox could call, plus `find_tools` whenever the prompt advertises it (set `configurable["cuga_lite_bind_tools_include_find_tools"] = False` to opt out). Past `cuga_lite_bind_tools_max_count` (128) the bind-cap shortlister runs every turn; `[shortlister.bind_cap] strategy = "embedding"` avoids the extra LLM call. - Tool names providers reject (over 64 characters, or with characters outside `[A-Za-z0-9_-]`) are bound under a provider-safe alias; the model calls the alias, the real tool runs, and the reply keeps the alias. - A provider that rejects a malformed native call but returns the attempt (Groq `tool_use_failed`) gets it back as a real call; a retryable rejection is retried once, then the turn ends with a clear error. - The bundled CodeAct few-shot demos are not sent in function-calling mode; pass your own through `configurable["mcp_few_shot_examples"]`. - Tools run in-process and sequentially, on the local executor even when `e2b_sandbox` is on. One turn's calls are one block, bounded by `sandbox_execution_timeout` as a whole; results computed before a timeout are kept. The pre-execute VERIFY gate applies in both modes; reflection is CodeAct-only for now. - Each result is kept as a variable (`tool_result_`): a large result is truncated in the reply to `execution_output_max_length` but survives whole for later turns, and a later CodeAct turn on the same thread can use it by name. - Function-calling needs tools bound natively: if `bind_tools` fails or the model does not support it, or the agent has no executable tools, the run stops with a clear error (fail closed) instead of silently answering without tools. A static prompt is ignored in this mode. - A thread can switch modes between turns: results from function-calling turns are shown to a later CodeAct turn as text and as variables. ## What each mode supports | | CodeAct | Function calling | |---|---|---| | Tool-approval policies, pre-execute VERIFY, tool-call budgets, block timeout, variables | Yes | Yes: the same checks, run on the translated block | | Reflection | Yes | No (CodeAct only for now) | | Execution backend | The configured sandbox | Always the local executor, even with `e2b_sandbox = true` | | Step discipline | Yes | Yes | | `find_tools` | Called from code | Bound as a native tool when the prompt advertises it | | Bundled few-shot demos, static prompt | Yes | Not used | | Spawned sub-agents (`agent_spawn`) | Yes | Known gaps, see #1123 | | Supervisor sub-agent | Yes | Yes | | The supervisor itself | Yes | No (the supervisor always runs CodeAct) | | Switching modes between turns of one thread | Yes | Yes | ## CodeAct changes that came with function calling Function calling reuses the CodeAct pipeline, and three CodeAct behaviors changed with it in #777: - **Variables survive a tool-call budget error** (kept by decision in #976). When a call is refused because a budget is spent (`max_tool_calls_per_block`, `max_tool_calls_per_run` or `max_tool_calls_per_thread`), the variables the block computed before that call are kept, as after a timeout or `exit()`. Before, they were dropped with the error. This applies to the local and execd executors, not E2B. - **Saved messages keep their type.** `AgentState` message lists (`CugaAgent` and server threads) are saved by their runtime type and rebuilt as the same message classes on load, so an assistant turn keeps its `tool_calls` and a tool reply its `tool_call_id`. Threads saved before the change still load. - **CodeAct can read native tool replies.** On a thread that switches modes, results from a function-calling turn reach the next CodeAct turn as `Tool result ():` text.
📝 Special Instructions Configuration ## How It Works Custom instructions support `## Plan` for execution guidance and `## Answer` for final-response formatting. Unsectioned text is treated as plan guidance. The default instruction set keeps reusable answer instructions in `answer.md`; runtime plan instructions can be supplied by clients such as Langflow. ## Configuration ``` configurations/ └── instructions/ ├── instructions.toml ├── default/ │ └── answer.md └── [other instruction sets]/ ``` Edit `configurations/instructions/instructions.toml`: ```toml [instructions] instruction_set = "default" # or any instruction set above ```
💾 Conversation checkpointer settings ## Configuration These `[storage]` keys in `settings.toml` control how published agent graphs persist execution state between turns. `checkpointer` defaults to `"memory"`, which keeps the current in-process behavior. Set any key with `DYNACONF_STORAGE__`, for example `DYNACONF_STORAGE__CHECKPOINTER=durable`. A pending approval is tied to the agent configuration and CUGA version that created it. If a publish changes the agent's effective configuration (including the published configuration of a sub-agent that a supervisor references), or CUGA is upgraded, before the approval arrives, the pending approval is cancelled and the client receives a `pending_cancelled` event; the conversation itself continues. Publishing again without changes does not cancel it. When a publish changes the agent, the next turn of a completed conversation starts with a `config_changed` event. | Key | Default | Description | |---|---|---| | `checkpointer` | `"memory"` | `memory` (in-process, lost on restart) \| `durable` (SQLite when `storage.mode = "local"`, Postgres when `"prod"`) | | `checkpoint_db_path` | `""` | Local mode only. SQLite file for checkpoints; empty means `DBS_DIR/checkpoints.db` | | `checkpoint_pool_min_size` | `1` | Prod mode only. Minimum Postgres connection pool size | | `checkpoint_pool_max_size` | `10` | Prod mode only. Maximum Postgres connection pool size | | `thread_lease_ttl_seconds` | `60` | How long a conversation's turn lease lasts without renewal | | `thread_lease_renew_seconds` | `20` | How often a running turn renews its lease | | `checkpoint_retention_days` | `90` | Prod mode only. Conversations with no completed turn for this many days lose their checkpoint and become read-only. The sweep removes the web conversation's checkpoint and its recorded sub-agent checkpoints; session knowledge, workspace files and `/run` or extension checkpoints stay until the conversation is deleted. `0` turns the sweep off | | `checkpoint_prune_interval_minutes` | `60` | Prod mode only. How often the retention sweep runs | **Database rights.** In `prod` mode CUGA creates and alters its tables at startup, so the database user needs DDL rights (`CREATE TABLE`, `CREATE INDEX`, `ALTER TABLE`). Conversation and lease schemas are initialized explicitly before requests or background work start, in both memory and durable checkpoint modes. If either schema cannot be prepared, startup fails; schema errors are not deferred to the first user request. Existing PostgreSQL lease timestamp columns are widened to `DOUBLE PRECISION` during this initialization. **Tables CUGA creates.** - LangGraph checkpoint tables, created by the checkpointer: `checkpoints`, `checkpoint_blobs`, `checkpoint_writes` and `checkpoint_migrations`. In `local` mode they are in the checkpoint SQLite file. - `thread_leases` in the conversation database: one row per running turn, coordinating turns across replicas and routing stop requests to the replica running the turn. Leases provide best-effort isolation; checkpoint writes are not yet fenced against an expired holder. - `runtime_thread_owners` gains two columns when an existing database is first opened: `status` (`new`, `active`, `legacy` or `deleted`) and `last_turn_at` (the end of the last completed turn, used by the retention sweep). **What users see.** A conversation created in the UI can be continued by typing into it, after a restart or on another replica, and keeps its ID and its sidebar entry. API clients create a conversation by omitting the thread ID (the response starts with a `thread_created` event) and continue it by sending that ID in the `X-Thread-ID` header. Conversations from before the upgrade, and conversations idle for longer than `checkpoint_retention_days`, stay readable but are read-only.
## Authentication and access control Configure OIDC sign-in with the provider values shown in the [environment example](../../.env.example): `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`, `OIDC_DISCOVERY_URL`, and `OIDC_REDIRECT_URI`. Set the redirect URI to the externally accessible callback URL for your deployment. Enable authentication and the role checks you want in `settings.toml`: ```toml [auth] enabled = true authorization_enabled = true manage_roles = ["ServiceOwner", "ServiceAdmin"] chat_roles = ["ServiceOwner", "ServiceAdmin", "ServiceUser"] ``` Configure your identity provider and role token source to supply the expected roles. Authentication and authorization are separate settings; role checks are disabled in the repository defaults. See the [deployment guide](../../deployment/README.md) for OIDC environment settings and role token sources. ## Optional: Use Evolve with CUGA
Setup and memory management Evolve can bring task-specific guidance into the prompt before execution and save completed trajectories after the run. This flow is: - **Configured integration** - requires an enabled memory service and a reachable Evolve backend - **Non-blocking** - Evolve failures do not fail the task - **Optional integration** - install `cuga[evolve]` if you want the upstream Evolve package available locally, or let `uvx` fetch it on demand ### Setup Steps: Set a stable service-instance identity in the CUGA environment before using either the registry-managed or bundled integration: ```dotenv DYNACONF_SERVICE__INSTANCE_ID=your-service-instance ``` CUGA uses this identity to scope Evolve operations. A configured model and Evolve connection alone are insufficient for automatic memory reads and writes. 1. Choose how Evolve will be started. Recommended for normal CUGA usage: let the CUGA MCP registry launch Evolve for you. In the manager UI, add an MCP tool with: - Name: `evolve` - Connection type: `Command (stdio)` - Command: `uvx` - Args: `--from "altk-evolve-core[server,cli,fastembed,pgvector,pii-regex]==1.7.1" evolve-mcp` Important: this command starts Evolve in `stdio` mode through the upstream Evolve package. It is intended to be launched by the CUGA registry, not run manually in a separate terminal. Alternative for standalone/manual debugging: run Evolve yourself as an SSE server: If you run Evolve from a checked-out `altk-evolve` repo instead of `uvx`, install the Postgres extras first with `uv sync --extra pgvector`. 2. Add these environment values in the MCP tool UI: ```env EVOLVE_BACKEND=postgres EVOLVE_PG_HOST=localhost EVOLVE_PG_PORT=5432 EVOLVE_PG_USER=postgres EVOLVE_PG_PASSWORD=postgres EVOLVE_PG_DBNAME=evolve EVOLVE_MODEL_NAME=Azure/gpt-4o OPENAI_API_KEY=env://OPENAI_API_KEY OPENAI_BASE_URL=env://OPENAI_BASE_URL ``` Each `env://...` value tells CUGA to read the real secret or setting from its own process environment at runtime, so make sure PostgreSQL is reachable, `pgvector` is available, and the configured OpenAI/LiteLLM-compatible model is one your gateway is allowed to use. 3. **[Optional]** Edit `./src/cuga/settings.toml` to configure Evolve: ```toml [evolve] enabled = true url = "http://127.0.0.1:8201/sse" mode = "auto" app_name = "evolve" save_on_success = true save_on_failure = true async_save = true timeout = 30.0 ``` If you use the recommended registry-managed setup above, keep `mode = "auto"` or set `mode = "registry"`. If you run Evolve manually as a standalone SSE server, keep `url = "http://127.0.0.1:8201/sse"` and set `mode = "direct"` if you want to skip registry lookup entirely. If you use Evolve tip generation, make sure the environment for the Evolve MCP server includes the required Evolve model settings. Otherwise `save_trajectory` may fail later with a LiteLLM/OpenAI model access error even when the MCP connection itself works. 1. Start the same CRM demo with sample workspace files: ```bash cuga start demo_crm --sample-memory-data ``` 1. Run a task that routes through CugaLite, for example: ```text Identify the common cities between my cuga_workspace/cities.txt and cuga_workspace/company.txt ``` ### What happens during a run? 1. CUGA derives the task description from the current sub-task or first user message 2. CUGA asks Evolve for relevant guidelines 3. Returned guidelines are appended to the system prompt under an `Evolve Guidelines` section 4. The task executes normally 5. The user / assistant trajectory is saved back to Evolve after completion ### Notes - `async_save = true` saves trajectories in the background and avoids blocking the response - `save_on_success` and `save_on_failure` let you control which runs are recorded - `mode = "auto"` lets CUGA use a registry-managed Evolve MCP server when available and fall back to the direct SSE URL otherwise - `mode = "registry"` is best when you want Evolve to be fully managed as a normal CUGA MCP tool - `mode = "direct"` is best when you are manually running an SSE Evolve server outside CUGA - If Evolve is unavailable, times out, or returns no guidance, CUGA continues normally ### Inspect and manage memory When the service exposes memory features, open **Memory** from the chat navigation to inspect stored guidance, preferences, source conversations, and usage. Users can control memory for their conversations and forget records. Administrators can configure service memory and episodic memory, inspect memory records, and manage retention where the backend supports it. Durable retention requires PostgreSQL storage and the bundled Evolve HTTP service. Its administrator UI includes retention rules, schedules, and activity. The MCP-only integration can still retrieve guidance and save trajectories; native retention APIs require the bundled HTTP service. See the [sample retention screen](media.md#memory-retention-controls). ### Use bundled memory management and retention Use the [UBI image](../../Dockerfile.ubi), which installs the Evolve extra and starts its private HTTP worker through the [container launcher](../../scripts/container_services.py). Build it with `docker build -f Dockerfile.ubi -t cuga:memory .`, or use this image in your [deployment](../../deployment/README.md). Configure the container environment for a PostgreSQL server with pgvector available: ```dotenv DYNACONF_SERVICE__INSTANCE_ID=your-service-instance DYNACONF_EVOLVE__ENABLED=true DYNACONF_EVOLVE__MODE=direct DYNACONF_EVOLVE__URL=http://127.0.0.1:8201/sse CUGA_EMBEDDED_EVOLVE=true EVOLVE_BACKEND=postgres EVOLVE_PG_HOST=your-postgres-host EVOLVE_PG_PORT=5432 EVOLVE_PG_USER=your-evolve-user EVOLVE_PG_PASSWORD=your-evolve-password EVOLVE_PG_DBNAME=evolve ``` Also supply the Evolve model settings described above, and configure [authentication](#authentication-and-access-control) for signed-in memory management. The bundled launcher supplies the private API credential used between CUGA and Evolve. Evolve's PostgreSQL settings are independent of CUGA's `DYNACONF_STORAGE__POSTGRES_URL`; configure both storage connections when using PostgreSQL for both services.
## Advanced Usage
Adding Tools: Comprehensive Examples CUGA supports three types of tool integrations. Each approach has its own use cases and benefits: ## **Tool Types Overview** | Tool Type | Best For | Configuration | Runtime Loading | | ------------- | -------------------------------------- | ------------------ | --------------- | | **OpenAPI** | REST APIs, existing services | `mcp_servers.yaml` | Build | | **MCP** | Custom protocols, complex integrations | `mcp_servers.yaml` | Build | | **LangChain** | Python functions, rapid prototyping | Direct import | Runtime | ## **Additional Resources** - **Tool Registry**: [./src/cuga/backend/tools_env/registry/README.md](../../src/cuga/backend/tools_env/registry/README.md) - **Comprehensive example with different tools + MCP**: [Adding tools](../examples/cuga_with_runtime_tools/README.md) - **CUGA as MCP**: [CUGA as MCP](../examples/cuga_as_mcp/README.md) - **Knowledge Engine demo**: [./docs/examples/knowledge_demo/README.md](../../docs/examples/knowledge_demo) — agent-level + session-level knowledge walkthrough
### Test Scenarios - E2E All tests run through pytest (configured in `pyproject.toml`): **Unit Tests** - Registry: OpenAPI integration, MCP server functionality, service configurations - Variables Manager: Core functionality, metadata handling, singleton pattern - Code Executors: Local sandbox and E2B lite execution **Policy Integration Tests** (`src/cuga/backend/cuga_graph/policy/tests/`) - Intent Guard: Blocking behavior, priority resolution, multiple guard scenarios - Playbook: Guidance injection, plan refinement, workflow execution - Tool Approval: Human-in-the-loop approval flows (approve/deny) - Tool Guide: Context enhancement and metadata injection - Output Formatter: Response formatting and routing - NL Trigger Conflict Resolution: Embedding-based similarity search with LLM conflict resolution - Embedding Similarity: Vector search, policy matching, threshold validation - Keyword Operators: AND/OR logic, case sensitivity, multi-keyword matching **SDK Integration Tests** (`src/cuga/sdk_core/tests/`) - SDK functionality: Agent invocation, streaming, tool integration - Policy management: Policy loading, matching, and execution via SDK **Stability Tests** (`@pytest.mark.stability` in `src/system_tests/e2e/`) - Fast Mode: Get top account by revenue, list accounts, find VP sales high-value accounts - CRM Workflows: Contacts management, email operations, tool discovery - HF Utterances: Account queries, revenue calculations, playbook execution - Execution: Sequential (`-n0`) so the 87% pass-rate gate aggregates on the controller; CI uses `--stability-threshold 87` (one LLM flake allowed on the 8-test suite) ## Running Tests Lint: ```bash uv run ruff check && uv run ruff format --check ``` Run the default suite (excludes manual and pgvector; pgvector needs a container): ```bash uv run pytest ``` Run the CI-equivalent subset (mocked unit/load; live LLM jobs are split in `tests.yml`): ```bash uv run pytest -m "not stability and not pgvector and not manual and not e2e and not load" uv run pytest src/system_tests/load/load_test_with_mocked_llm.py -m load --load-test-users 5 ``` Stability tests, the CI equivalent (87% pass-rate gate; use `-n0` so the threshold aggregates correctly): ```bash uv run pytest src/system_tests/e2e -m stability --stability-threshold 87 -n0 ``` Run a faster local loop: ```bash uv run pytest -m "not stability and not slow and not pgvector and not manual and not e2e and not load" ``` Run pgvector tests (requires a running pgvector container): ```bash uv run pytest -m pgvector -o addopts="-ra --strict-markers --import-mode=importlib" ``` ## Evaluation For information on how to evaluate, see the [CUGA Evaluation Documentation](../../src/cuga/evaluation/README.md)