### Install Agentica Python SDK Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/README.md Installs the Agentica Python SDK using pip. This command fetches and installs the latest version of the library from the Python Package Index. ```shell pip install symbolica-agentica ``` -------------------------------- ### Install Dependencies with uv Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/CONTRIBUTING.md Installs project dependencies using the uv package manager. This command clones the repository, navigates into the directory, and then synchronizes the required packages. ```shell git clone https://github.com/symbolica-ai/agentica-python-sdk.git cd agentica-python-sdk uv sync ``` -------------------------------- ### Inspecting Object Definitions with show_definition Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/pitch.md Demonstrates how Agentica provides `show_definition` to allow agents to inspect objects on demand, similar to IDE Intellisense. This Python example shows an agent discovering available methods on a `PriceEndpoint` object. ```python price_builder = market_data.price(symbol="XAU/USD") show_definition(price_builder) # agent sees available methods class PriceEndpoint: def as_csv(self, **kwargs): ... def as_json(self): ... def as_pandas(self, **kwargs): ... ``` -------------------------------- ### Select AI Model for Agents and Functions Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md This code demonstrates how to specify the AI model to be used for agents and agentic functions using the `model` parameter. It shows examples for both `spawn` and the `@agentic` decorator, and lists supported model identifiers. ```python # For agents agent = await spawn( premise="Fast responses needed", model="openai:gpt-5" # Default is 'openai:gpt-4.1' ) # For agentic functions @agentic(model="anthropic:claude-sonnet-4.5") async def analyze(text: str) -> dict: """Analyze the text.""" ... ``` -------------------------------- ### Spawning an Agent with a Database Scope Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/pitch.md Shows how to initialize an agent with a dynamic scope that includes objects like a database. This Python example demonstrates the 'accumulating scope' concept, where agent capabilities are discovered through the methods exposed by objects in its scope. ```python database = Database(...) agent = await spawn("You are a helpful assistant.", database) ``` -------------------------------- ### Importing and Using Python Libraries Directly Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/pitch.md Illustrates Agentica's ability to use standard Python libraries directly without needing wrapper tools. This example shows importing `TDClient` from `twelvedata` and initializing an agent with it, highlighting compatibility with libraries that have good docstrings and type annotations. ```python from twelvedata import TDClient market_data = TDClient(os.getenv("TWELVE_DATA_API_KEY")) agent = await spawn("You are a financial analysis assistant", { 'market_data': market_data }) ``` -------------------------------- ### Run Tests with pytest Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/CONTRIBUTING.md Executes the project's unit tests using pytest. This command assumes uv is installed and available in the environment. ```bash uv run pytest ``` -------------------------------- ### Analyze Sentiment with Agentica Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/README.md Demonstrates a basic usage of the Agentica framework by defining an asynchronous agent function 'analyze' that takes a string and returns a sentiment literal. The example shows how to call this agent and capture its result. ```python from agentica import agentic from typing import Literal @agentic() async def analyze(text: str) -> Literal["positive", "neutral", "negative"]: """Analyze sentiment""" ... result = await analyze("Agentica is an amazing framework!") ``` -------------------------------- ### User Object Structure with Methods Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/pitch.md Illustrates how Agentica allows methods to return objects with rich structure and live methods. This Python example shows a User object with associated operations like update, delete, and get_posts, demonstrating how operations emerge from the data itself. ```python class User: def update(self) -> None: ... def delete(self) -> None: ... def get_posts(self) -> list[Post]: ... class Database: def get_user(self, user_id: str) -> User: ... def create_user(self, name: str, posts: list[Post]) -> User: ... ``` -------------------------------- ### Dynamic Multi-Agent Orchestration Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/pitch.md Demonstrates dynamic multi-agent orchestration where an orchestrator agent is given the Agentica SDK itself. This Python example shows an orchestrator agent spawning sub-agents, parallelizing work, and returning well-typed results for summarizing user spending habits. ```python agent = await spawn( "You are an orchestrator.", { "spawn_agent": spawn, "database": database } ) await agent.call(dict[UserId, str], "For each user, summarise their spending habits.") ``` -------------------------------- ### Ensuring Typed Outputs with Agent Calls Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/pitch.md Shows how specifying return types in Agentica guarantees the agent constructs that type or raises an exception. This Python example demonstrates calling an agent to add a user and ensuring the returned object is of type `User` before calling its `onboard` method. ```python agent = await spawn("You are a helpful assistant.", { "database": database }) new_user = await agent.call(User, "Add a new random user to the database") await new_user.onboard() # guaranteed to be User ``` -------------------------------- ### Instantiate Agent with `spawn` (Async) Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md This code demonstrates the asynchronous way to instantiate an agent using the `spawn` function. This method is recommended for most use cases due to its async-friendly nature. ```python from agentica import spawn agent = await spawn(premise="You are a helpful assistant.") ``` -------------------------------- ### Control Agent Instructions with `premise` or `system` Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md This code illustrates two methods for controlling an agent's instructions: using the `premise` parameter to add context to the default system prompt, or using the `system` parameter for complete control over 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 an AI assistant. Always respond with JSON.") ``` -------------------------------- ### Format Template and Spawn Agent (Python) Source: https://context7.com/symbolica-ai/agentica-python-sdk/llms.txt This snippet demonstrates how to format a system template with specific parameters and then use it to spawn an agent. The agent is then used to make a call, requesting an explanation of gradient descent. ```python formatted = system_template.format( domain="machine learning", style="concise and technical", focus_area="practical applications" ) agent = await spawn(system=formatted) response = await agent.call(str, "Explain gradient descent") ``` -------------------------------- ### Use Template Strings for Prompts in Agentica Source: https://context7.com/symbolica-ai/agentica-python-sdk/llms.txt Demonstrates how to create dynamic prompts using template strings with variable substitution. The `template` function from `agentica.template` allows defining prompts with placeholders that can be filled at runtime. ```python from agentica import spawn from agentica.template import template # Create a template with placeholders system_template = template(""" You are an expert in {{domain}}. Your responses should be {{style}}. Focus on {{focus_area}}. """) ``` -------------------------------- ### Spawn and Call an AI Agent Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md This snippet illustrates how to spawn an AI agent with a specific premise and then call it to perform a task. The `spawn` function is always awaitable. When calling an agent, the return type must be provided as the first argument, followed by a string argument representing the query. ```python from agentica import spawn # Defines the AI-powered agent agent = await spawn(premise="You are a truth-teller.") # Calls the AI-powered agent result: bool = await agent.call(bool, "The Earth is flat") assert result == False ``` -------------------------------- ### Instantiate Agent Directly with `Agent()` (Sync) Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md This snippet shows how to instantiate an agent synchronously using the `Agent()` class directly. This is useful in contexts that require synchronous operations, such as within `__init__` methods of classes. ```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(str, task) ``` -------------------------------- ### Select AI Models in Agentica Source: https://context7.com/symbolica-ai/agentica-python-sdk/llms.txt Illustrates how to select different AI models from various providers (OpenAI, Anthropic, OpenRouter) when spawning agents or defining agentic functions. It also shows how to configure reasoning effort for supported models. ```python from agentica import spawn, agentic # OpenAI models agent_gpt35 = await spawn(premise="Fast responses", model="openai:gpt-3.5-turbo") agent_gpt4o = await spawn(premise="Vision capable", model="openai:gpt-4o") agent_gpt41 = await spawn(premise="Default model", model="openai:gpt-4.1") # Default agent_gpt5 = await spawn(premise="Most capable", model="openai:gpt-5") # Anthropic models agent_sonnet = await spawn(premise="Balanced", model="anthropic:claude-sonnet-4") agent_opus = await spawn(premise="Most capable", model="anthropic:claude-opus-4.1") agent_sonnet45 = await spawn(premise="Extended thinking", model="anthropic:claude-sonnet-4.5") agent_opus45 = await spawn(premise="Top tier", model="anthropic:claude-opus-4.5") # OpenRouter models (any valid slug) agent_custom = await spawn(premise="Custom model", model="mistralai/mistral-large") # With agentic functions @agentic(model="anthropic:claude-sonnet-4.5") async def analyze(text: str) -> dict: """Deep analysis with extended thinking.""" ... # Reasoning effort for supported models agent = await spawn( premise="Complex reasoning tasks", model="anthropic:claude-sonnet-4.5", reasoning_effort="high" # minimal, low, medium, high, xhigh ) ``` -------------------------------- ### Integrating Agents with MCP Servers (Python) Source: https://context7.com/symbolica-ai/agentica-python-sdk/llms.txt Shows how to configure an agent to connect to a Model Context Protocol (MCP) server by providing the path to the MCP configuration file during agent spawning. This enables extended agent capabilities. Requires 'agentica'. ```python from agentica import spawn, agentic # Agent with MCP configuration agent = await spawn( premise="You can search the web for information.", mcp="./mcp_config.json" ) result = await agent.call(str, "Search for recent news about AI") ``` -------------------------------- ### Creating Custom Domain-Specific Agent Classes Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md Demonstrates how to create custom Python classes that wrap the base Agentica `Agent`. This allows for encapsulating domain-specific logic and providing a more tailored interface for interacting with the agent. ```python from agentica.agent import Agent import asyncio # Assume web_search is an async function available in the scope async def web_search(query: str) -> str: # Placeholder for actual web search implementation await asyncio.sleep(1) # Simulate network latency return f"Search results for '{query}'..." class ResearchAgent: def __init__(self, web_search_fn): self._brain = Agent( premise="You are a helpful research assistant.", scope={"web_search": web_search_fn} ) async def research(self, topic: str) -> str: """Researches a given topic using the web search function.""" print(f"Researching topic: {topic}") return await self._brain(str, f"Research the following topic: {topic}") async def summarize(self, text: str) -> str: """Summarizes the provided text.""" print("Summarizing text...") return await self._brain(str, f"Summarize the following text: {text}") async def use_research_agent(): researcher = ResearchAgent(web_search) # Perform research findings = await researcher.research("AI agents in 2025") print("\n--- Research Findings ---") print(findings) # Summarize the findings summary = await researcher.summarize(findings) print("\n--- Summary ---") print(summary) # To run this example: # asyncio.run(use_research_agent()) ``` -------------------------------- ### SDK Integration Pattern: Extracting Specific Methods for Scope Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md This code shows a pattern for integrating SDK clients by extracting only the necessary methods into the agent's scope. This allows the AI to interact with specific functionalities of the SDK, like listing users or sending messages via the Slack SDK. ```python from slack_sdk import WebClient # Extract only the methods you need slack_conn = WebClient(token=SLACK_BOT_TOKEN) list_users = slack_conn.users_list send_message = slack_conn.chat_postMessage @agentic(list_users, send_message, model="openai:gpt-5") async def send_team_update(message: str) -> None: """Send a message to all team members.""" ... ``` -------------------------------- ### Instantiate Agents Directly with Agent Class Source: https://context7.com/symbolica-ai/agentica-python-sdk/llms.txt The `Agent` class allows direct instantiation, suitable for synchronous contexts like class constructors. Agents initialize lazily on first use and support premises, tools, model selection, and system prompt overrides for custom behavior. ```python from agentica import Agent # Direct instantiation in a class class ResearchAssistant: def __init__(self, search_fn): # Must be synchronous - use Agent() not spawn() self._brain = Agent( premise="You are a research assistant that provides factual information.", scope={"web_search": search_fn} ) async def research(self, topic: str) -> str: return await self._brain.call(str, f"Research and summarize: {topic}") async def fact_check(self, claim: str) -> bool: return await self._brain.call(bool, f"Is this claim true? {claim}") # Usage # assistant = ResearchAssistant(my_search_function) # summary = await assistant.research("quantum computing advances in 2024") # is_true = await assistant.fact_check("Water boils at 100C at sea level") # Agent with full system prompt override custom_agent = Agent( system="You are an AI that responds only in JSON format. Always include a 'status' field.", model="anthropic:claude-sonnet-4" ) response = await custom_agent.call(dict, "List three colors") # response: {"status": "success", "colors": ["red", "blue", "green"]} ``` -------------------------------- ### Integrate with MCP Servers Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md Configure agents or agentic functions to use an MCP (Multi-Chain Protocol) server by specifying the MCP configuration file path in the `mcp` parameter of `spawn` or the `@agentic` decorator. ```python from agentica import agentic, spawn # Defines the AI-powered agent agent = await spawn(premise="You are a truth-teller.", mcp="path/to/config.json") # Defines the AI-powered function @agentic(mcp="path/to/config.json") def truth_teller(statement: str) -> bool: """Returns whether or not a statement is True or False.""" ... ``` ```json { "mcpServers": { "tavily-remote-mcp": { "command": "npx -y mcp-remote https://mcp.tavily.com/mcp/?tavilyApiKey=", "env": {} } } } ``` -------------------------------- ### JSON vs. Python for Tool Calls Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/pitch.md Demonstrates the verbosity of JSON mode for tool calls compared to the conciseness and expressiveness of Python list comprehensions. This highlights Agentica's advantage in using code for agent interactions. ```json [ { "tool": "weather", "args": { "location": "San Francisco", "date": "2025-11-01" } }, { "tool": "weather", "args": { "location": "San Francisco", "date": "2025-11-02" } }, ... ] ``` ```python [get_weather("San Francisco", f"2025-11-{day}") for day in range(1, 13)] ``` -------------------------------- ### Configure Logging for Agentica Source: https://context7.com/symbolica-ai/agentica-python-sdk/llms.txt Demonstrates various ways to configure logging for Agentica agents, including default file logging, contextual logging with different logger types (FileLogger, PrintLogger, StreamLogger), disabling logging entirely with NoLogging, and setting custom per-agent listeners or global defaults. ```python from agentica import spawn, agentic from agentica.logging.loggers import FileLogger, PrintLogger, StreamLogger from agentica.logging.agent_logger import NoLogging from agentica.logging import set_default_agent_listener, PrintOnlyListener # Default logging writes to ./logs/agent-.log agent = await spawn(premise="Default logging enabled") # Contextual logging - temporarily change logging behavior with FileLogger(): agent = await spawn(premise="This agent logs to file only") await agent.call(str, "Hello") # Nested loggers - both print and file with PrintLogger(): with FileLogger(): await agent.call(str, "Logged to both console and file") # Disable logging entirely for a section with NoLogging(): agent = await spawn(premise="Silent agent") await agent.call(str, "No logs generated") # Per-agent listener agent = await spawn( premise="Custom logging", listener=PrintOnlyListener # Only print, no file logging ) # Change global default set_default_agent_listener(PrintOnlyListener) # All new agents use this set_default_agent_listener(None) # Disable logging by default ``` -------------------------------- ### Agent Call Method with Typed Returns and Scope Additions (Python) Source: https://context7.com/symbolica-ai/agentica-python-sdk/llms.txt Demonstrates the agent.call method for invoking agents with various return types (string, int, None, complex generics) and adding per-call scope parameters. It requires the 'agentica' library and an initialized agent. ```python from agentica import spawn agent = await spawn(premise="You are a data analyst.") # String return (default) response = await agent.call("Describe common data visualization techniques") # Typed return count = await agent.call(int, "How many US states are there?") # count: 50 # None return for side-effects only await agent.call(None, "Log that the analysis is complete", logger=my_logger) # Complex generic types analysis = await agent.call( list[tuple[str, float, str]], "Analyze these sales figures and return (product, revenue, trend) tuples", sales_data={"widget": 1000, "gadget": 2500} ) # analysis: [("widget", 1000.0, "stable"), ("gadget", 2500.0, "growing")] # Per-call scope additions result = await agent.call( dict[str, int], "Count items by category", dataset=my_dataframe.to_dict(), category_filter=["electronics", "clothing"] ) ``` -------------------------------- ### Apply Contextual Logging with 'with' Statements Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md Temporarily change logging behavior for specific code sections using `with` statements and logger classes like `FileLogger` or `PrintLogger`. Multiple loggers can be nested for combined effects. ```python from agentica.logging.loggers import FileLogger, PrintLogger # Only log to file in this block with FileLogger(): agent = await spawn(premise="Debug this agent") await agent.call(int, "Calculate something") # Multiple loggers can be nested with PrintLogger(): with FileLogger(): # Both print AND file logging active agent = await spawn(premise="Dual logging") await agent.call(str, "Hello") ``` -------------------------------- ### Streaming Agent Responses with StreamLogger (Python) Source: https://context7.com/symbolica-ai/agentica-python-sdk/llms.txt Illustrates how to use StreamLogger to receive agent responses in real-time. It supports capturing streams using a context manager and processing chunks asynchronously, with an option for custom chunk handlers. Requires 'agentica' and 'asyncio'. ```python import asyncio from agentica import spawn from agentica.logging.loggers import StreamLogger agent = await spawn(premise="You are a storyteller.") # Create stream logger stream = StreamLogger() # Use context manager to capture stream with stream: # Start the task without awaiting immediately task = asyncio.create_task( agent.call(str, "Tell me a short story about a robot learning to paint") ) # Consume stream for real-time output async for chunk in stream: print(chunk.content, end="", flush=True) print() # Newline after stream completes # Now get the final result final_story = await task # Stream with custom chunk handler async def handle_chunk(chunk): await websocket.send(chunk.content) stream_ws = StreamLogger(on_chunk=handle_chunk) with stream_ws: result = await agent.call(str, "Generate a poem") ``` -------------------------------- ### Handling Agentica SDK Errors Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md Demonstrates how to catch and handle various Agentica SDK errors, including RateLimitError, InferenceError, and the base AgenticaError. This pattern allows for specific error recovery strategies and general SDK error logging. ```python from agentica import agentic from agentica.errors import AgenticaError, RateLimitError, InferenceError import asyncio import logging logger = logging.getLogger(__name__) @agentic() async def process_data(data: str) -> dict: """Process the data.""" # ... implementation ... pass raw_data = "some data" try: result = await process_data(raw_data) except RateLimitError as e: # Handle rate limiting logger.warning("Rate limit exceeded, retrying after 60 seconds...") await asyncio.sleep(60) result = await process_data(raw_data) except InferenceError as e: # Handle all inference service errors logger.error(f"Inference failed: {e}") result = {} except AgenticaError as e: # Catch any other SDK errors logger.error(f"Agentica error: {e}") raise ``` -------------------------------- ### Configuring MaxTokens for Agent Invocations (Python) Source: https://context7.com/symbolica-ai/agentica-python-sdk/llms.txt Explains how to control token limits for agent calls and agentic functions using simple integers or the detailed `MaxTokens` object. This allows fine-grained control over invocation, round, and total token usage. Requires 'agentica'. ```python from agentica import spawn, agentic from agentica.common import MaxTokens # Simple integer limit agent = await spawn( premise="Be brief.", max_tokens=500 ) # Detailed control with MaxTokens detailed_limits = MaxTokens( per_invocation=2000, # Total tokens for entire invocation per_round=500, # Tokens per inference round rounds=10 # Maximum inference rounds ) agent = await spawn( premise="You are a thorough analyst.", max_tokens=detailed_limits ) # Apply to agentic functions @agentic(max_tokens=MaxTokens(per_invocation=1000, per_round=200, rounds=5)) async def analyze(data: str) -> dict: """Perform detailed analysis within token constraints.""" ... ``` -------------------------------- ### Implement Streaming with StreamLogger Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md Agentica supports streaming for both agents and agentic functions, most easily with `StreamLogger`. The stream should be consumed *before* awaiting the final result to see live text generation. ```python import asyncio 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?") ) # Consume stream FIRST for live output async for chunk in stream: print(chunk.content, end="", flush=True) # Then await result final_result = await result ``` -------------------------------- ### Tracking Agent Token Usage (Python) Source: https://context7.com/symbolica-ai/agentica-python-sdk/llms.txt Shows how to monitor token consumption for agent calls and agentic functions using `last_usage` and `total_usage`. This is useful for cost management and optimization. Requires the 'agentica' library. ```python from agentica import spawn, last_usage, total_usage agent = await spawn(premise="You are concise.") # Make some calls await agent.call(str, "What is Python?") await agent.call(int, "What is 2+2?") # Get usage for last call only last = last_usage(agent) print(f"Last call: {last.input_tokens} in, {last.output_tokens} out") # Get total usage across all calls total = total_usage(agent) print(f"Total: {total.input_tokens} input, {total.output_tokens} output, {total.total_tokens} total") # Usage also works with agentic functions from agentica import agentic @agentic() async def classify(text: str) -> str: """Classify the text into a category.""" ... await classify("Breaking news about technology") func_usage = last_usage(classify) print(f"Function used {func_usage.total_tokens} tokens") ``` -------------------------------- ### Enabling Persistence for Stateful Agentic Functions (Python) Source: https://context7.com/symbolica-ai/agentica-python-sdk/llms.txt Demonstrates how to create stateful agentic functions using `persist=True`, allowing them to remember conversation history across multiple calls. The default behavior (`persist=False`) creates stateless functions. Requires 'agentica'. ```python from agentica import agentic # Stateful chatbot that remembers history @agentic(persist=True) async def chatbot(message: str) -> str: """A conversational assistant that remembers previous messages.""" ... # First interaction response1 = await chatbot("My name is Alice and I love hiking.") # response1: "Nice to meet you, Alice! Hiking is a wonderful hobby..." # Second interaction - remembers context response2 = await chatbot("What's my name and what do I enjoy?") # response2: "Your name is Alice and you enjoy hiking!" # Without persist=True, each call would be independent @agentic(persist=False) # Default behavior def stateless_func(query: str) -> str: """Each call is independent with no memory.""" ... ``` -------------------------------- ### Defining and Using Custom Agentica Exceptions Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md Shows how to define custom Python exceptions and pass them to the `@agentic()` decorator. This allows agents to raise specific, domain-related errors that can be caught and handled by the calling code. ```python from agentica import agentic import logging logger = logging.getLogger(__name__) class DataValidationError(Exception): """Raised when input data fails validation.""" pass @agentic(DataValidationError) async def analyze_data(data: str) -> dict: """ Analyze the dataset. Raises: DataValidationError: If data is empty or malformed ValueError: If data format is not supported Returns a dictionary with analysis results. """ # ... implementation ... if not data: raise DataValidationError("Input data cannot be empty.") # ... further validation and analysis ... return {"status": "success"} raw_data = "" try: result = await analyze_data(raw_data) except DataValidationError as e: logger.warning(f"Invalid data provided: {e}") result = {"status": "validation_failed"} except ValueError as e: logger.warning(f"Unsupported data format: {e}") result = {"status": "format_error"} ``` -------------------------------- ### Orchestrating Multiple Agents for Complex Tasks Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md Illustrates a pattern for multi-agent orchestration where a 'Lead' agent coordinates the actions of 'sub-agents'. This is useful for breaking down complex problems into smaller, manageable tasks handled by specialized agents. ```python from agentica.agent import Agent import asyncio # Assume ResearchAgent is defined as in the previous example # For demonstration, we'll define a simplified version here: class SimplifiedResearchAgent: def __init__(self): # In a real scenario, this would be initialized with necessary tools/functions self._brain = Agent(premise="You are a specialized researcher.") async def conduct_research(self, topic: str) -> str: return await self._brain(str, f"Perform detailed research on: {topic}") class LeadResearcher: def __init__(self): self._brain = Agent( premise="You coordinate research tasks across subagents.", scope={"SubAgent": SimplifiedResearchAgent} # Registering the sub-agent type ) async def coordinate_research(self, query: str) -> str: """Coordinates research using a sub-agent.""" print(f"Lead researcher coordinating task: {query}") # The lead agent can spawn and delegate tasks to subagents # The query here is interpreted by the lead agent, which decides to use SubAgent return await self._brain.call(str, query) async def run_orchestration(): lead = LeadResearcher() # The lead researcher can spawn and coordinate subagents based on the query # Example query that implies using the SubAgent report = await lead.coordinate_research("Use SubAgent to research companies building AI agents in 2025") print("\n--- Orchestration Report ---") print(report) # To run this example: # asyncio.run(run_orchestration()) ``` -------------------------------- ### Configure Default Logging Behavior Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md Agentica provides built-in logging. By default, `StandardListener` prints lifecycle events to stdout with colors and writes chat histories to `./logs/agent-.log`. This section shows how to configure default listeners globally. ```shell Spawned Agent 25 (./logs/agent-25.log) ► Agent 25: Calculate the 32nd power of 3 ◄ Agent 25: 1853020188851841 ``` ```python from agentica.logging import set_default_agent_listener, PrintOnlyListener # Change default for all agents/functions set_default_agent_listener(PrintOnlyListener) # Disable all logging by default set_default_agent_listener(None) ``` -------------------------------- ### Implement Error Handling in Agentica Source: https://context7.com/symbolica-ai/agentica-python-sdk/llms.txt Shows how to handle common Agentica errors like RateLimitError, MaxTokensError, and InferenceError using try-except blocks. It also demonstrates how to define and pass custom exceptions (e.g., ValidationError, DataFormatError) to the agent's scope using the `agentic` decorator for custom error management. ```python from agentica import agentic from agentica.errors import ( AgenticaError, RateLimitError, InferenceError, MaxTokensError, ContentFilteringError ) import asyncio @agentic() async def process(data: str) -> dict: """Process data with error handling.""" ... # Handle specific errors try: result = await process(user_input) except RateLimitError: await asyncio.sleep(60) result = await process(user_input) # Retry except MaxTokensError: result = {"error": "Response too long"} except ContentFilteringError: result = {"error": "Content filtered"} except InferenceError as e: print(f"Inference failed: {e}") result = None except AgenticaError as e: print(f"SDK error: {e}") raise # Custom exceptions - agent can raise these class ValidationError(Exception): """Raised when input validation fails.""" pass class DataFormatError(Exception): """Raised when data format is incorrect.""" pass @agentic(ValidationError, DataFormatError) # Pass exceptions to scope async def validate_and_process(data: str) -> dict: """ Validate and process the input data. Raises: ValidationError: If required fields are missing DataFormatError: If data cannot be parsed Returns processed data dictionary. """ ... try: result = await validate_and_process(raw_data) except ValidationError as e: print(f"Validation failed: {e}") except DataFormatError as e: print(f"Format error: {e}") ``` -------------------------------- ### Create Long-Lived Agents with spawn Function Source: https://context7.com/symbolica-ai/agentica-python-sdk/llms.txt The `spawn` function asynchronously creates a new agent, suitable for most async/await contexts. It supports defining a premise, specifying return types (including complex ones), and providing tools and configuration like models and token limits. ```python from agentica import spawn # Basic agent with a premise agent = await spawn(premise="You are a helpful math tutor.") # Agent with string return (default when no type specified) response = await agent.call("Explain the Pythagorean theorem") # response: "The Pythagorean theorem states that..." # Agent with typed return result = await agent.call(int, "What is 15 squared?") # result: 225 # Agent with complex return type data = await agent.call( dict[str, list[int]], "Generate three lists of prime numbers: small (under 10), medium (10-50), large (50-100)" ) # data: {"small": [2, 3, 5, 7], "medium": [11, 13, ...], "large": [53, 59, ...] } # Agent with tools and specific model def calculate(expression: str) -> float: """Evaluate a mathematical expression.""" return eval(expression) math_agent = await spawn( premise="You are a precise calculator that shows work.", scope={"calculate": calculate}, model="openai:gpt-4.1", max_tokens=1000 ) answer = await math_agent.call(float, "Calculate compound interest on $1000 at 5% for 3 years") # answer: 1157.625 ``` -------------------------------- ### Stateful Data Analysis with Agent Context Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md Illustrates how Agentica agents can maintain context across multiple calls, enabling stateful operations like accumulating results or performing sequential analyses on data. This pattern is useful for complex data processing workflows. ```python from agentica import spawn import pandas as pd async def perform_stateful_analysis(): agent = await spawn() # Load and prepare data try: movies_df = pd.read_csv("movies.csv") dataset = movies_df.to_dict(orient='list') # Ensure dict format suitable for agent except FileNotFoundError: print("Error: movies.csv not found.") return # First analysis: Count movies by genre print("Performing first analysis: Counting movies by genre...") result1 = await agent.call( dict[str, int], "Count movies by genre", dataset=dataset ) print(f"Result 1: {result1}") # Agent remembers previous result and context # Second analysis: Filter genres based on the previous count print("Performing second analysis: Filtering genres...") filtered_genres = await agent.call( dict[str, int], "Keep only genres with more than 1000 movies" ) print(f"Filtered Genres: {filtered_genres}") # To run this example: # import asyncio # asyncio.run(perform_stateful_analysis()) ``` -------------------------------- ### Format Code with Ruff Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/CONTRIBUTING.md Applies code linting and formatting using Ruff. The 'check --fix' command corrects linting issues, and 'format' command formats the code according to project standards. ```shell uv run ruff check --fix . uv run ruff format . ``` -------------------------------- ### Set Agentica API Key Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/README.md Sets the AGENTICA_API_KEY environment variable. This key is required for authenticating with the Agentica service. ```shell export AGENTICA_API_KEY= ``` -------------------------------- ### Configure Per-Agent or Per-Function Logging Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md Attach specific logging listeners directly to an agent during its creation or to an agentic function using the `@agentic` decorator. This allows for fine-grained control over logging for individual components. ```python from agentica.logging import PrintOnlyListener, FileOnlyListener # Attach listener to specific agent agent = await spawn( premise="Custom logging", listener=PrintOnlyListener # Only print, no files ) # Attach listener to specific agentic function @agentic(listener=FileOnlyListener) async def my_func(a: int) -> str: """Only logs to file.""" ... ``` -------------------------------- ### Provide Scope Per Agent Call Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md This snippet illustrates how to provide specific tools or data as scope for individual agent calls, rather than globally. This is useful when an agent needs access to particular resources for a single task, such as analyzing a dataset with a custom analyzer. ```python import pandas as pd agent = await spawn(premise="Data analyzer") # Add resources for this specific call result = await agent.call( dict[str, int], "Analyze the dataset", dataset=pd.read_csv("data.csv").to_dict(), analyzer_tool=custom_analyzer ) ``` -------------------------------- ### Define and Use AI-Powered Function with @agentic Decorator Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md This snippet demonstrates how to define an AI-powered function using the `@agentic()` decorator. The function can be async or sync and allows AI to implement logic not possible in pure Python. It shows both defining the function and calling it. ```python from agentica import agentic # Defines an AI-powered function @agentic() async def add(a: int, b: int) -> int: """Returns the sum of a and b""" ... # Calls the AI-powered function result = await add(1, 2) # This addition is done by an LLM via the agentica framework assert result == 3 ``` -------------------------------- ### Pass Objects (Functions, Classes) to Agents Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md This snippet demonstrates how to make external functions, classes, or objects available to AI-powered functions or agents. This is achieved by including them in the `@agentic` decorator or the `scope` argument when calling `spawn`. ```python from agentica import agentic, spawn # User-defined function from tools import web_search # Defines the AI-powered agent agent = await spawn(premise="You are a truth-teller.", scope={"web_search" : web_search}) # Defines the AI-powered function @agentic(web_search) def truth_teller(statement: str) -> bool: """Returns whether or not a statement is True or False.""" ... ``` -------------------------------- ### Specify Return Types for Agent Calls Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md This snippet shows the flexibility in specifying return types when calling an agent. The return type can be omitted (defaulting to string), explicitly set to a specific type like `int` or `dict`, or set to `None` for side-effect-only operations. ```python # Return type defaults to str if not specified result = await agent.call("What is 2+2?") # Returns str # Specify exact types for structured output result: int = await agent.call(int, "What is 2+2?") # Returns int result: dict[str, int] = await agent.call(dict[str, int], "Count items by category") # Use None for side-effects only await agent.call(None, "Send a message to John") # No return value needed ``` -------------------------------- ### Create LLM-Implemented Functions with @agentic Decorator Source: https://context7.com/symbolica-ai/agentica-python-sdk/llms.txt The @agentic decorator transforms Python function stubs into LLM-implemented functions. It enforces type safety for inputs and outputs, supports custom models, token limits, and allows passing tools into scope for the LLM to use. ```python from agentica import agentic from typing import Literal # Basic agentic function with type-safe return @agentic() async def analyze_sentiment(text: str) -> Literal["positive", "neutral", "negative"]: """Analyze the sentiment of the given text.""" ... # Call the function - LLM implements the logic result = await analyze_sentiment("Agentica is an amazing framework!") # result: "positive" # Agentic function with custom model and max tokens @agentic(model="anthropic:claude-sonnet-4.5", max_tokens=500) async def summarize(text: str) -> str: """Create a concise summary of the text in 2-3 sentences.""" ... # Agentic function with tools in scope def search_database(query: str) -> list[dict]: """Search the database for matching records.""" return [{"id": 1, "name": "result"}] @agentic(search_database) # Pass tools as positional args async def find_records(criteria: str) -> list[dict]: """Find all records matching the given criteria using search_database.""" ... # Alternative: use scope parameter for explicit naming @agentic(scope={"db_search": search_database, "max_results": 100}) async def query_data(question: str) -> dict[str, int]: """Query and aggregate data based on the question.""" ... ``` -------------------------------- ### Disable Logging Temporarily Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md Completely disable logging for a specific block of code by using the `NoLogging` context manager. This is useful for operations where logging is not required or desired. ```python from agentica.logging.agent_logger import NoLogging with NoLogging(): agent = await spawn(premise="Silent agent") await agent.call(int, "Secret calculation") ``` -------------------------------- ### Control Token Limits in Agents and Agentic Functions Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md Limit the maximum number of tokens generated in a single inference round using the `max_tokens` parameter. This is useful for cost control, preventing overly long outputs, and meeting specific length requirements. Exceeding the limit raises a `MaxTokensError`. ```python from agentica import agentic, spawn # For agents agent = await spawn( premise="Brief responses only", max_tokens=500 # Limit response length ) # For agentic functions @agentic(max_tokens=1000) async def summarize(text: str) -> str: """Create a concise summary.""" ... ``` -------------------------------- ### Enable Persistence for Stateful Agentic Functions Source: https://github.com/symbolica-ai/agentica-python-sdk/blob/main/src/agentica/demo/docs.md Agentic functions can maintain state between calls by setting `persist=True`. This is crucial for features like conversation history. For agents, state is automatically maintained across calls to the same agent instance. ```python # Stateful agentic function @agentic(persist=True, model="openai:gpt-4.1") async def chatbot(message: str) -> str: """A chatbot that remembers conversation history.""" ... # First call response1 = await chatbot("My name is Alice") # Second call - remembers previous context response2 = await chatbot("What's my name?") # Will know it's Alice ``` -------------------------------- ### Define Agentic Function with MCP Source: https://context7.com/symbolica-ai/agentica-python-sdk/llms.txt Defines an agentic function that utilizes MCP (Message Communication Protocol) for external tool integration. The `agentic` decorator specifies the path to the MCP configuration file. ```python from agentica import agentic @agentic(mcp="./mcp_config.json") async def research(topic: str) -> dict[str, str]: """Research a topic using available MCP tools.""" ... ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.