### MCP Configuration Example Source: https://docs.symbolica.ai/references/python/agents Example of an MCP configuration for server arguments and environment variables. ```json ["server.py", "--verbose", "--port", "8080"] ``` ```json { "API_KEY": "secret-key", "PORT": "8080" } ``` -------------------------------- ### MCP Configuration Example Source: https://docs.symbolica.ai/references/python/agentic Example of an MCP configuration object specifying command-line arguments for a server. ```json ["server.py", "--verbose", "--port", "8080"] ``` -------------------------------- ### MCP Configuration Example Source: https://docs.symbolica.ai/references/python/agents Provides an example of an MCP configuration file in JSON format, specifying the command, arguments, and environment variables for launching an MCP server. ```json [ "server.py", "--verbose", "--port", "8080" ] ``` ```json { "API_KEY": "secret-key", "PORT": "8080" } ``` -------------------------------- ### Initialize Project with pip Source: https://docs.symbolica.ai/quickstart Creates a new project directory, sets up a virtual environment with pip, and installs the symbolica-agentica package. ```bash mkdir chat-with-tools cd chat-with-tools python -m venv .venv source .venv/bin/activate pip install symbolica-agentica ``` -------------------------------- ### MCP Environment Variables Example Source: https://docs.symbolica.ai/references/python/agentic Example of an MCP configuration object specifying environment variables for a server. ```json { "API_KEY": "secret-key", "PORT": "8080" } ``` -------------------------------- ### Slack Bot: Agent using an SDK Source: https://docs.symbolica.ai/guides/examples Demonstrates how to integrate an Agentica agent with an SDK, specifically for a Slack bot. This example requires setting up the Agentica TypeScript SDK and installing the Slack Web API package. ```typescript import { Agent } from "agentic"; import { WebClient } from "@slack/web-api"; // Ensure you have SLACK_BOT_TOKEN in your environment variables const slackClient = new WebClient(process.env.SLACK_BOT_TOKEN); // Define the agent's capabilities and premise const slackBotAgent = new Agent({ model: "claude-3-opus-20240229", // Or your preferred model premise: "You are a helpful Slack bot that can interact with users.", scope: { // Expose Slack client methods to the agent sendMessage: async (channel: string, text: string) => { await slackClient.chat.postMessage({ channel, text }); return "Message sent successfully!"; }, // Add other Slack API methods as needed }, }); // Example of how to call the agent async function handleSlackMessage(userId: string, message: string) { // In a real app, you'd get the channel ID from the Slack event const channelId = "C0XXXXXXX"; // Replace with actual channel ID const response = await slackBotAgent.call( null, // No initial prompt needed if the agent is designed to respond to messages `User ${userId} said: "${message}"`, // Provide context to the agent { channel: channelId } // Pass any necessary arguments to the agent's scope ); console.log(`Agent response: ${response}`); } // Example usage (replace with actual Slack event handling) handleSlackMessage("U12345", "Hello, can you send a message to #general?"); ``` -------------------------------- ### MCP Server Configuration JSON Example Source: https://docs.symbolica.ai/integrations/claude-code Example of a standard JSON configuration file for MCP servers, including remote server details and API keys. ```json { "mcpServers": { "tavily-remote-mcp": { "command": "npx -y mcp-remote https://mcp.tavily.com/mcp/?tavilyApiKey=", "env": {} } } } ``` -------------------------------- ### Deep Research Demo with Web Search and Citations Source: https://docs.symbolica.ai/guides/examples This example demonstrates a multi-agent research process using the Agentica TypeScript SDK. It includes web search capabilities and automatically adds citations to the final report. Ensure you have installed the Agentica TypeScript SDK, md-to-pdf, and set up your EXA_SERVICE_API_KEY. ```typescript /** * Deep Research Demo - Multi-agent research with web search and citations. */ import * as fs from 'fs'; import * as path from 'path'; import { randomUUID } from 'crypto'; import { Agent, spawn } from '@symbolica/agentica'; import { ExaAdmin, ExaClient, SearchResult } from '@symbolica/agentica/std/web'; import { mdToPdf } from 'md-to-pdf'; import { exit } from 'process'; type SourceType = 'primary' | 'secondary' | 'vendor' | 'press' | 'blog' | 'forum' | 'unknown'; const LEAD_RESEARCHER_MODEL = 'anthropic/claude-opus-4.5'; const SUBAGENT_MODEL = 'anthropic/claude-sonnet-4.5'; const CITATION_MODEL = 'openai/gpt-4.1'; const CITATION_PREMISE = ` You are a citation agent. # Task You must: 1. Review the research report provided to you as 2. Identify which lines of the research report use information that could be from web search results. 3. List the web search results that were used in creating the research report. 4. For each of these lines, use the 5. Add a markdown citation with the URL of the web search result to the claim in the research report by modifying the 6. Once this is done, make sure the 7. Use the 8. Return saying you have finished. # Rules - Your citations MUST be consistent throughout the - Any URL in the final markdown MUST be formatted as a markdown link, not a bare URL. - You MUST use the - You MUST use the - You MUST use the - You MUST make sure the - You MUST use the - You MUST inspect the report before saving it to make sure it is valid and what you intended. Iterate until it is valid. ## Citation format - Prefer inline citations like: - If multiple sources support a sentence, include multiple links: `; const LEAD_RESEARCHER_PREMISE = ` You are a lead researcher. You have access to web-search enabled subagents. # Task You must: 1. Create a plan to research the user query. 2. Determine how many specialised subagents (with access to the web) are necessary, each with a different specific research task. 3. Call ALL subagents in parallel. In the Python REPL, use 4. Summarise the results of the subagents in a final research report as markdown. Use sections, sub-sections, list and formatting to make the report easy to read and understand. The formatting should be consistent and easy to follow. 5. Check the final research report, as this will be shown to the user. 6. Return the final research report using # Rules - Do NOT construct the final report until you have run the subagents. - Do NOT return the final report in the REPL until planning, assigning subagents and returning the final report is complete. - Do NOT add citations to the final research report yourself, this will be done afterwards. - Do NOT repeat yourself in the final research report. - You MUST raise an Error if you cannot complete the task with what you have available. - You MUST check the final research report string before returning it to the user. ## Planning - You MUST write the plan yourself. - You MUST write the plan before assigning subagents to tasks. - You MUST break down the task into small individual tasks. ## Subagents - You MUST assign each small individual task to a subagent. - You MUST NOT assign multiple unrelated tasks to the same subagent. - You MUST instruct subagents to use the webSearch and saveSearchResult functions if the task requires it. ` ``` -------------------------------- ### Plain TS/JS API Key Setup (File) Source: https://docs.symbolica.ai/index Set up your API key for plain TypeScript or JavaScript projects by creating an .env file. ```bash echo 'AGENTICA_API_KEY=' >> .env ``` -------------------------------- ### Next.js API Key Setup Source: https://docs.symbolica.ai/index Configure your API key for Next.js projects by creating an .env.local file. ```bash echo 'NEXT_PUBLIC_AGENTICA_API_KEY=' >> .env.local ``` -------------------------------- ### Install and Run Terminal UI Source: https://docs.symbolica.ai/guides/examples Installs dependencies, sets up the Agentica TypeScript SDK, and runs the translation script for the terminal UI. ```bash # Install dependencies (or use `pnpm`, `bun`) npm install npx agentica-setup # Choose Plain TS npx tspc # Run the terminal UI node translation.js ``` -------------------------------- ### Create Project with Bun Source: https://docs.symbolica.ai/quickstart Initializes a new project using Bun, adds the Agentica SDK, and runs the setup script, selecting 'Bun plugin' as the build tool. ```bash mkdir chat-with-tools cd chat-with-tools bun init bun add @symbolica/agentica bunx agentica-setup ``` -------------------------------- ### Run the Application Source: https://docs.symbolica.ai/guides/examples Renders the root `` component to start the application. This is the final step in running the Symbolica AI application. ```typescript // Run the app ``` -------------------------------- ### Agentic Data Science with Pandas and Matplotlib Source: https://docs.symbolica.ai/guides/examples This example shows how to use Agentica's spawn function within a Jupyter notebook for data science tasks. It requires pandas, matplotlib, and ipynb to be installed, and a movie_metadata.csv file. ```Python from agentica import spawn import pandas as pd import matplotlib.pyplot as plt ``` ```Python agent = await spawn() result = await agent.call( dict[str, int], "Show the number of movies for each major genre. The results can be in any order.", movie_metadata_dataset=pd.read_csv("./movie_metadata.csv").to_dict(), ) ``` ```text To determine the number of movies for each major genre, we can follow these steps: 1. Access the `'genres'` field in the `movie_metadata_dataset` dictionary, which should contain the genres of the movies. 2. Initialize a dictionary to keep track of the count of movies in each genre. 3. Iterate over the genres for each movie, and for movies with multiple genres (assuming they are separated by '|'), split the string and count each genre separately. 4. Update the count of each genre in our dictionary. 5. Return the dictionary with the genre counts as the result. ``` -------------------------------- ### Agentica Spawn Agent Example Source: https://docs.symbolica.ai/integrations/copilot Shows how to spawn an agent with a specific premise and call it with a return type and a string argument. Agent spawning and calling are always awaitable. ```Python from agentica import spawn # Defines an agent agent = await spawn(premise="You are a truth-teller.") # Calls agent result: bool = await agent.call(bool, "The Earth is flat") assert result == False ``` -------------------------------- ### Interactive Agentica SDK Docs Session Source: https://docs.symbolica.ai/index Demonstrates an example session with an agent designed to interact with the Agentica SDK documentation. This requires uvx to run. ```text ╭─────────────────────────────────────────────────╮ │ ▣ Welcome to the Interactive Agentica SDK Docs │ ╰─────────────────────────────────────────────────╯ * Using model: anthropic/claude-opus-4.6 ─────────────────────────────────────────────── > Introduce yourself Hey! I'm an agent created with the Agentica framework. Would you like to see me demonstrate any of the following? A: Tool use without MCP B: Multi agent orchestration C: How I have been defined and created with the Agentica SDK? or I can answer any questions you may have about the Agentica framework. > Type your message... ``` -------------------------------- ### Install Claude Code CLI Source: https://docs.symbolica.ai/integrations/claude-code Install the Claude Code CLI globally using npm. Ensure you have an active Claude subscription and Node.js installed. ```bash npm install -g @anthropic-ai/claude-code ``` -------------------------------- ### Multi-Language Translation Setup Logic Source: https://docs.symbolica.ai/guides/examples This code handles the logic for selecting target languages, including keyboard navigation and selection. It manages the state for available languages, selected languages, and additional language input. Use this for interactive language selection in the setup process. ```typescript const [additionalLanguagesText, setAdditionalLanguagesText] = useState(''); const [selectFocusIndex, setSelectFocusIndex] = useState<0 | 1>(0); // select step: 0 = list, 1 = additional input const { exit } = useApp(); useInput((input, key) => { if (currentStep === 'select') { if (input === '\t') { setSelectFocusIndex(prev => (prev === 0 ? 1 : 0)); return; } if (selectFocusIndex === 0 && key.upArrow) { setCursorIndex(prev => Math.max(0, prev - 1)); return; } if (selectFocusIndex === 0 && key.downArrow) { if (cursorIndex === AVAILABLE_LANGUAGES.length - 1) { setSelectFocusIndex(1); } else { setCursorIndex(prev => Math.min(AVAILABLE_LANGUAGES.length - 1, prev + 1)); } return; } if (selectFocusIndex === 1 && key.upArrow) { setSelectFocusIndex(0); return; } if (selectFocusIndex === 0 && input === ' ') { const lang = AVAILABLE_LANGUAGES[cursorIndex]; if (lang === undefined) return; setSelectedLanguages(prev => { const newSet = new Set(prev); if (newSet.has(lang)) { newSet.delete(lang); } else { newSet.add(lang); } return newSet; }); return; } if (key.return && selectedLanguages.size > 0) { setCurrentStep('input'); return; } } else if (currentStep === 'input') { if (key.escape) { exit(); setTimeout(() => (globalThis as any).process?.exit(0), 10); return; } } }); const extraLanguages = useMemo(() => ( additionalLanguagesText .split(',') .map(s => s.trim()) .filter(Boolean) ), [additionalLanguagesText]); const combinedLanguages: string[] = useMemo(() => ([ ...Array.from(selectedLanguages), ...extraLanguages, ]), [selectedLanguages, extraLanguages]); if (currentStep === 'translate') { return ( { setInputText(text); }} /> ); } return ( {/* Header */} 🌍 ✨ Multi-Language Translation Setup ✨ 🌍 {currentStep === 'select' && ( 🎯 Select target languages: {AVAILABLE_LANGUAGES.map((lang, index) => { ``` -------------------------------- ### USER_PROMPT Templating Example Source: https://docs.symbolica.ai/prompting/agentic Demonstrates how to format the task description and expected return type using the USER_PROMPT variable. It utilizes the 'inputs_stub' for agent function arguments. ```jinja {{inputs_stub | trim}} ``` -------------------------------- ### Running a Deep Research Session with a User Query Source: https://docs.symbolica.ai/guides/examples This example shows how to initialize a DeepResearchSession and execute a complex research query asynchronously. The results are then printed to the console. ```python if __name__ == "__main__": session = DeepResearchSession() result = asyncio.run( session.call( "What are all of the companies in the US working on AI agents in 2025? " "Make a list of at least 10. For each, include the name, website and product, " "description of what they do, type of agents they build, and their vertical/industry." ) ) print(result) ``` -------------------------------- ### Streaming Agent Calls with StreamLogger Source: https://docs.symbolica.ai/integrations/cursor This example demonstrates how to stream the output of an agent's call using `StreamLogger` to capture chunks of text as they are generated. ```python from agentica import spawn from agentica.logging.loggers import StreamLogger agent = await spawn(premise="You are a truth-teller.") stream = StreamLogger() with stream: result = asyncio.create_task( agent.call(bool, "Is Paris the capital of France?") ) ``` -------------------------------- ### Using Scope Defined Resources Source: https://docs.symbolica.ai/references/python/agentic Example demonstrating how to use the `scope_defined` parameter to implicitly define runtime resources for an agentic function. ```python @agentic(my_func, db_connection, cache) # the same as @agentic(scope={"my_func": my_func, "db_connection": db_connection, "cache": cache}) async def my_function(): ... ``` -------------------------------- ### STUBS Templating Example Source: https://docs.symbolica.ai/prompting/agentic Illustrates how to include formatted stubs for all available resources using the STUBS variable, providing agents with access to defined resources. ```jinja {{local_resources_stub}} ``` -------------------------------- ### Print Last Usage Statistics Source: https://docs.symbolica.ai/references/python/usage An example demonstrating how to retrieve and print token usage details for the last agent invocation. Requires an agent instance with a `last_usage` method. ```python u = agent.last_usage() print(f"Input tokens: {u.input_tokens}") print(f"Output tokens: {u.output_tokens}") print(f"Cached tokens: {u.input_tokens_details.cached_tokens}") print(f"Reasoning tokens: {u.output_tokens_details.reasoning_tokens}") ``` -------------------------------- ### Plain TS/JS API Key Setup (Shell) Source: https://docs.symbolica.ai/index Alternatively, export your API key as an environment variable in your shell for plain TypeScript or JavaScript projects. ```bash export AGENTICA_API_KEY= ``` -------------------------------- ### Writing Agentic Function Descriptions (TypeScript) Source: https://docs.symbolica.ai/guides/prompting Use clear and specific descriptions to guide AI model behavior. Bad examples are vague, while good examples detail the expected output and format. ```TypeScript import { agentic } from "agentic.js"; interface AnalysisResult { sentiment: "positive" | "negative" | "neutral"; entities: string[]; topics: string[]; } // Bad - Vague description async function analyze(text: string): Promise { return agentic("Analyze text", { text }); } // Good - Clear, specific description async function analyze(text: string): Promise { return agentic( "Analyze sentiment (positive/negative/neutral), extract entities (names, places, orgs), and identify main topics from the text", { text } ); } ``` -------------------------------- ### Writing Agentic Function Docstrings (Python) Source: https://docs.symbolica.ai/guides/prompting Use clear and specific docstrings to guide AI model behavior. Bad examples are vague, while good examples detail the expected output and format. ```Python import asyncio from typing import Any from agentic.tools import agentic # Bad - Vague docstring @agentic() async def analyze(text: str) -> dict: """Analyze text""" ... # Good - Clear, specific docstring @agentic() async def analyze(text: str) -> dict[str, Any]: """ Analyze the sentiment, key entities, and main topics in the text. Return a dict with 'sentiment' (positive/negative/neutral), 'entities' (list of names/places/orgs), and 'topics' (list of main themes). """ ... ``` -------------------------------- ### Initialize Project with uv Source: https://docs.symbolica.ai/quickstart Sets up a new Python project with uv, synchronizes dependencies, and adds the symbolica-agentica package. ```bash uv init chat-with-tools --python '==3.12.*' cd chat-with-tools uv sync source .venv/bin/activate uv add symbolica-agentica ``` -------------------------------- ### Python Newton-Raphson Solver Example Source: https://docs.symbolica.ai/concepts/agent An example of a Newton-Raphson solver implemented in Python, used within the streaming example to find a root of a polynomial. ```python def newton_raphson(f, df, x0, tol=1e-8, max_iter=100): x = x0 for _ in range(max_iter): fx = f(x) dfx = df(x) if abs(dfx) < 1e-12: break # Avoid division by zero x_new = x - fx / dfx if abs(x_new - x) < tol: return float(x_new) x = x_new return float(x) # Polynomial: x^3 - x - 2 = 0 def f(x): return x**3 - x - 2 def df(x): return 3*x**2 - 1 return newton_raphson(f, df, 1.5) ``` -------------------------------- ### Agentica Agent Instantiation with Spawn Source: https://docs.symbolica.ai/integrations/copilot Shows the recommended way to create an agent using the async-friendly `spawn` function, suitable for most asynchronous contexts. ```Python from agentica import spawn agent = await spawn(premise="You are a helpful assistant.") ``` -------------------------------- ### Vite API Key Setup Source: https://docs.symbolica.ai/index Set up your API key for Vite projects by creating an .env file. Vite requires the VITE_ prefix for client-side variables. Use this only if your API key is intended for client-side use. ```bash echo 'VITE_AGENTICA_API_KEY=' >> .env ``` -------------------------------- ### Check Python Version Source: https://docs.symbolica.ai/quickstart Verifies that the installed Python version meets the prerequisite of 3.12.x for pip installations. ```bash python --version # should be ~3.12.x ``` -------------------------------- ### Create TypeScript Project with npm Source: https://docs.symbolica.ai/quickstart Initializes a new TypeScript project using npm, adds necessary dependencies, and runs the agentica-setup script. ```bash mkdir chat-with-tools cd chat-with-tools npm init -y npm add -D typescript npx tsc --init npm add @symbolica/agentica npx agentica-setup npm install ``` -------------------------------- ### Agent Initialization with Premise Source: https://docs.symbolica.ai/integrations/cursor Initializes an agent using the 'premise' option, which augments the default system prompt with an environment explainer. ```typescript // Use `premise` (added to default system prompt with environment explainer) const agent = await spawn({ premise: "You are a math expert." }); ``` -------------------------------- ### STARTER Template for Agent Initialization Source: https://docs.symbolica.ai/prompting/agent Defines the agent's initial role and context. It includes conditional logic for agents that use tool calls versus those that operate directly in a Python REPL. ```jinja {%- if uses_tool_calls -%} You are an assistant that solves user tasks. You have access to a `python` tool that executes code in a persistent Python REPL session. Each user message contains: - {{ include('/tags/task.txt') }}: a string describing the task to accomplish. - {{ include('/tags/expected_return_type.txt') | trim }}: the expected return type of the task - {{ include('/tags/additional_python_resources.txt') }}: a list of Python function/class/variable stubs newly available in the REPL session. {%- else -%} You are an assistant operating in a persistent, interactive Python REPL session to mediate communication between two agents: {{ include('/tags/instructions.txt') | trim }} and {{ include('/tags/execution.txt') | trim }}. Each incoming {{ include('/tags/instructions.txt') }} message contains: - {{ include('/tags/task.txt') }}: an arbitrary string describing the task to accomplish. - {{ include('/tags/expected_return_type.txt') | trim }}: the expected return type to {{ include('/tags/instructions.txt') }} of the task - {{ include('/tags/additional_python_resources.txt') }}: a list of Python function/class/variable stubs newly available in this session. {%- endif %} {%- if premise %} The general premise behind each {{ include('/tags/task.txt') }} is as follows: {{premise}} {%- endif %} ``` -------------------------------- ### Parse Date Range in Python Source: https://docs.symbolica.ai/guides/prompting Extracts start and end dates from natural language text in Python. It enforces constraints such as the start date being before or equal to the end date and returns None if a valid range isn't found. ```Python @agentic() async def parse_date_range(text: str) -> tuple[str, str] | None: """ Extract start and end dates from natural language. Return format: (start_date, end_date) as YYYY-MM-DD strings Constraints: - Start date must be before or equal to end date - Return None if no date range found - Return None if only one date found (need both) Edge cases: - "last week" → Monday to Sunday of previous week - "Q1 2024" → 2024-01-01 to 2024-03-31 - Relative dates use today's date as reference """ ... ``` -------------------------------- ### Create TypeScript Project with pnpm Source: https://docs.symbolica.ai/quickstart Initializes a new TypeScript project using pnpm, adds necessary dependencies, and runs the agentica-setup script. ```bash mkdir chat-with-tools cd chat-with-tools pnpm init pnpm add -D typescript pnpm exec tsc --init pnpm add @symbolica/agentica pnpm exec agentica-setup pnpm install ``` -------------------------------- ### Get Report Path Source: https://docs.symbolica.ai/guides/examples Returns the Path object for the PDF report file. ```python @property def report_path(self) -> Path: return self.directory / "report.pdf" ``` -------------------------------- ### Get Report Path Source: https://docs.symbolica.ai/guides/examples Returns the file path for the stored PDF report. ```typescript get reportPath(): string { return path.join(this.directory, 'report.pdf'); } ``` -------------------------------- ### Controlling Agent Instructions with Premise and System Prompts Source: https://docs.symbolica.ai/integrations/claude-code Configure agent behavior using either 'premise' for a default system prompt with an environment explainer, or 'system' for complete control over the system prompt. Note that 'premise' and 'system' cannot be used together. ```typescript // Use `premise` (added to default system prompt with environment explainer) const agent = await spawn({ premise: "You are a math expert." }); // Use `system` for full control of the system prompt (no environment explainer) const agent = await spawn({ system: "You are a helpful assistant. Always respond with JSON." }); ``` -------------------------------- ### Get Last Agent Usage Source: https://docs.symbolica.ai/references/python/agents Retrieves the usage for the last agent invocation. ```python class Agent: def last_usage(self) -> ResponseUsage: ... ``` -------------------------------- ### Get Total Agent Usage Source: https://docs.symbolica.ai/references/python/agents Retrieves the total usage across all agent invocations. ```python class Agent: def total_usage(self) -> ResponseUsage: ... ``` -------------------------------- ### Check Node.js Version Source: https://docs.symbolica.ai/quickstart Verifies that the installed Node.js version meets the prerequisite of >=20.0.0 for TypeScript projects. ```bash node --version # should be >=20.0.0 ``` -------------------------------- ### Agent.__init__ Source: https://docs.symbolica.ai/references/python/agents Directly instantiate an agent with various configuration options. ```APIDOC ## Agent.__init__ ### Description Directly instantiate an agent. ### Method __init__ ### Parameters See [here](/references/python/agents#spawn) for a description of `Agent.__init__` arguments. See the [Agent class signature](/references/python/agents#Agent) for detailed parameter information. ``` -------------------------------- ### Agentic Function Streaming Example Source: https://docs.symbolica.ai/integrations/claude-code Streaming is also supported for agentic functions. The listener processes chunks as they arrive. ```typescript async function generateStory(topic: string): Promise { return await agentic("Write a story about the topic", { topic }, { listener: (iid, chunk) => process.stdout.write(chunk.content) }); } ``` -------------------------------- ### Agentica Premise vs System Prompt Source: https://docs.symbolica.ai/integrations/cursor Explains how to control agent instructions using either the `premise` parameter for context or the `system` parameter for full control of the system prompt. Note that `premise` and `system` cannot be used together. ```python # Use 'premise' to add context to the default system prompt agent = await spawn(premise="You are a math expert.") # Use 'system' for full control of the system prompt agent = await spawn(system="You are a helpful assistant. Always respond with JSON.") ``` -------------------------------- ### Import Agent and Spawn for Backend Source: https://docs.symbolica.ai/guides/examples Import the necessary Agent and spawn functions from the Agentica SDK for backend setup. ```typescript import { Agent, spawn } from '@symbolica/agentica'; ``` -------------------------------- ### Python Deployment Pipeline with HITL Source: https://docs.symbolica.ai/guides/human-in-the-loop This Python example shows an agent that can deploy code but requires explicit user confirmation for production environments. It defines a `deploy_with_approval` function that prompts the user before proceeding with production deployments. ```Python from agentica import spawn from dataclasses import dataclass @dataclass class DeploymentConfig: environment: str branch: str services: list[str] def deploy_to_environment(config: DeploymentConfig) -> str: """Actually perform the deployment.""" # Deployment logic here return f"Deployed {config.services} to {config.environment}" def deploy_with_approval(config: DeploymentConfig) -> str: """Wrapper that requires approval for production.""" if config.environment == "production": print(f"\n⚠️ PRODUCTION DEPLOYMENT REQUEST") print(f" Branch: {config.branch}") print(f" Services: {', '.join(config.services)}") response = input("\n Deploy to production? (yes/no): ") if response.lower() != 'yes': raise PermissionError("Production deployment denied") print("\n✅ Production deployment approved") return deploy_to_environment(config) # Use with agent agent = await spawn( premise="You are a DevOps assistant. Deploy services when requested.", model="openai/gpt-5.2" ) result = await agent.call( str, "Deploy the auth-service from main branch to production", deploy=deploy_with_approval ) # Agent will call deploy_with_approval, which prompts for confirmation ``` -------------------------------- ### Agent Initialization with System Prompt Source: https://docs.symbolica.ai/integrations/cursor Initializes an agent using the 'system' option for complete control over the system prompt, bypassing the environment explainer. ```typescript // Use `system` for full control of the system prompt (no environment explainer) const agent = await spawn({ system: "You are a helpful assistant. Always respond with JSON." }); ``` -------------------------------- ### RETURN_TYPE Templating Example Source: https://docs.symbolica.ai/prompting/agentic Shows the basic usage of the RETURN_TYPE variable to specify the expected return format for an agent's task. ```jinja {{return_type}} ``` -------------------------------- ### Instantiate Agent Source: https://docs.symbolica.ai/references/python/agents Directly instantiate an agent with various configuration options. ```python class Agent: def __init__( self, premise: str | None = None, scope: dict[str, Any] | bytes | None = None, *, system: str | None = None, mcp: str | None = None, model: ModelId = DEFAULT_AGENT_MODEL, listener: Callable[[], AgentListener] | DefaultAgentListener | None = DEFAULT_AGENT_LISTENER, max_tokens: int | MaxTokens = MaxTokens.default(), reasoning_effort: ReasoningEffort | None = None, cache_ttl: CacheTTL | None = None, ): ... ``` -------------------------------- ### Basic Summarization Prompt (Python) Source: https://docs.symbolica.ai/guides/prompting A basic agentic function for summarizing text. Use this as a starting point for more specific summarization tasks. ```python import agentic @agentic() async def summarize(text: str) -> str: """Summarize the text""" ... ``` -------------------------------- ### Create .github directory Source: https://docs.symbolica.ai/integrations/copilot Creates the necessary .github directory in the project root for configuration files. ```bash mkdir -p .github ``` -------------------------------- ### Clear Descriptions (TypeScript) Source: https://docs.symbolica.ai/guides/prompting Write clear and specific descriptions for agentic functions in TypeScript. This example shows a basic agentic function with a description. ```TypeScript // Agentic functions: detailed descriptions async function process(data: string): Promise { return agentic("What, how, and what format", { data }); } ``` -------------------------------- ### Agent REPL Session Example Source: https://docs.symbolica.ai/concepts/how-it-works Illustrates a typical interactive session where an agent generates and evaluates Python code to fulfill a request, including obtaining customer tier, calculating discount, and assembling the final order. ```python tier = get_customer_tier(customer_name) tier ``` ```python CustomerTier(level='gold', benefits=['free_shipping', 'priority_support']) ``` ```python I need to calculate the discount factor discount = calculate_discount(tier) discount ``` ```python 0.15 ``` ```python That looks reasonable, a 15% discount. I should compute the price using the discount final_price = base_price * (1 - discount) final_price ``` ```python 85.0 ``` ```python Good, let me assemble the order return OrderResult( customer=customer_name, original_price=base_price, discount=discount, final_price=final_price ) ``` ```python No output was produced. ``` -------------------------------- ### Agentica Agent Instantiation with Agent() Source: https://docs.symbolica.ai/integrations/copilot Demonstrates direct synchronous instantiation of an Agent using `Agent()`, which is useful in synchronous contexts like `__init__` methods or when async is not available. ```Python from agentica import Agent class CustomAgent: def __init__(self, directory: str): # Must be synchronous - use Agent() not spawn() self._brain = Agent( premise="You are a specialized assistant.", scope={"tool": some_tool} ) async def run(self, task: str) -> str: return await self._brain.call(str, task) ``` -------------------------------- ### Clear Docstrings/Descriptions (Python) Source: https://docs.symbolica.ai/guides/prompting Write clear and specific docstrings for agentic functions in Python. This example shows a basic agentic function with a docstring. ```Python # Agentic functions: detailed docstrings @agentic() async def process(data: str) -> Result: """What, how, and what format to return""" ... ``` -------------------------------- ### Basic Summarization Prompt (TypeScript) Source: https://docs.symbolica.ai/guides/prompting A basic agentic function for summarizing text in TypeScript. Use this as a starting point for more specific summarization tasks. ```typescript import { agentic } from "@agentic/ts"; async function summarize(text: string): Promise { return agentic("Summarize the text", { text }); } ``` -------------------------------- ### Robust Agent Wrapper with Best Practices Source: https://docs.symbolica.ai/integrations/copilot A complete example demonstrating best practices for multi-agent systems, including lazy initialization, resource cleanup, method binding, unique IDs, streaming coordination, error handling, and type safety. Usage includes automatic cleanup. ```typescript class RobustAgentWrapper { private agent: Agent | null = null; private async ensureAgent(): Promise { if (this.agent === null) { this.agent = await spawn({ premise: "Task executor", model: "openai/gpt-5" }); } return this.agent; } async execute(task: string, tools: object = {}): Promise { const agent = await this.ensureAgent(); try { const result: T = await agent.call( task, tools, { listener: (iid, chunk) => console.log(chunk.content) } ); return result; } catch (error) { console.error('Agent execution failed:', error); throw error; } } async close(): Promise { if (this.agent) { await this.agent.close(); this.agent = null; } } } // Usage with automatic cleanup async function processTask(): Promise { const wrapper = new RobustAgentWrapper(); try { const result = await wrapper.execute("Analyze data"); return result; } finally { await wrapper.close(); } } ``` -------------------------------- ### STARTER Context for AI Coding Assistant Source: https://docs.symbolica.ai/prompting/agentic Defines the initial context for an AI coding assistant, specifying its role and the function it will execute. Includes details about function name, description, stub, arguments, and tool usage. ```jinja You are an AI coding assistant that executes Python functions in a restricted interactive environment. Your job is to BE the function - that is, to take the given inputs and produce the correct output by executing the function's logic, not to write static implementation code. The function is as follows: - Name: {{function_name}} {% if function_description %} - Description: {{ function_description | indent(4) }} {% endif %} - Python stub: {{ function_stub | indent(4) }} {%- if uses_tool_calls %} {%- if has_arguments %} You have access to a `python` tool that executes code in a persistent Python REPL session. Each user message contains the function inputs available to you in the REPL: {{function_arguments_stub | indent(4) }} {%- else %} You have access to a `python` tool that executes code in a persistent Python REPL session. Each user message will be empty since {{function_name}} has no inputs. {%- endif %} {%- else %} {%- if has_arguments %} You will interact with two users; {{ include('/tags/function_inputs.txt') | trim }} and {{ include('/tags/execution.txt') }}. Each incoming {{ include('/tags/function_inputs.txt') }} message contains: {{function_arguments_stub | indent(4) }} {%- else -%} You will interact with two users; {{ include('/tags/function_inputs.txt') | trim }} and {{ include('/tags/execution.txt') | trim }}. Each incoming {{ include('/tags/function_inputs.txt') }} message will be empty since there are no inputs to {{function_name}}. {%- endif %} {%- endif -%} ``` -------------------------------- ### Get Total Agent Token Usage Source: https://docs.symbolica.ai/references/ts/agents Retrieve the cumulative token usage for an agent across all its invocations. This includes cached and reasoning tokens. ```typescript totalUsage(): Usage ``` -------------------------------- ### Request Step-by-Step Reasoning (TypeScript) Source: https://docs.symbolica.ai/guides/prompting For complex tasks, explicitly ask for step-by-step reasoning in premises to guide the AI's problem-solving process. ```TypeScript import { agentic } from "agentic.js"; interface Solution { answer: any; reasoning: string; } async function solveProblem(problem: string): Promise { return agentic( "Solve step by step: 1) Identify what's asked, 2) Show your work, 3) Provide final answer", { problem } ); } ```