| name | agentica-sdk |
| description | Build Python agents with Agentica SDK - @agentic decorator, spawn(), persistence, MCP integration |
| allowed-tools | ["Bash","Read","Write","Edit"] |
Agentica SDK Reference (v0.3.1)
Build AI agents in Python using the Agentica framework. Agents can implement functions, maintain state, use tools, and coordinate with each other.
When to Use
Use this skill when:
- Building new Python agents
- Adding agentic capabilities to existing code
- Integrating MCP tools with agents
- Implementing multi-agent orchestration
- Debugging agent behavior
Quick Start
Agentic Function (simplest)
from agentica import agentic
@agentic()
async def add(a: int, b: int) -> int:
"""Returns the sum of a and b"""
...
result = await add(1, 2)
Spawned Agent (more control)
from agentica import spawn
agent = await spawn(premise="You are a truth-teller.")
result: bool = await agent.call(bool, "The Earth is flat")
Core Patterns
Return Types
result = await agent.call("What is 2+2?")
result: int = await agent.call(int, "What is 2+2?")
result: dict[str, int] = await agent.call(dict[str, int], "Count items")
await agent.call(None, "Send message to John")
Premise vs System Prompt
agent = await spawn(premise="You are a math expert.")
agent = await spawn(system="You are a JSON-only responder.")
Passing Tools (Scope)
from agentica import agentic, spawn
@agentic(scope={'web_search': web_search_fn})
async def researcher(query: str) -> str:
"""Research a topic."""
...
agent = await spawn(
premise="Data analyzer",
scope={"analyze": custom_analyzer}
)
result = await agent.call(
dict[str, int],
"Analyze the dataset",
dataset=data,
analyzer=custom_fn
)
SDK Integration Pattern
from slack_sdk import WebClient
slack = WebClient(token=SLACK_TOKEN)
@agentic(scope={
'list_users': slack.users_list,
'send_message': slack.chat_postMessage
})
async def team_notifier(message: str) -> None:
"""Send team notifications."""
...
Agent Instantiation
spawn() - Async (most cases)
agent = await spawn(premise="Helpful assistant")
Agent() - Sync (for __init__)
from agentica.agent import Agent
class CustomAgent:
def __init__(self):
self._brain = Agent(
premise="Specialized assistant",
scope={"tool": some_tool}
)
async def run(self, task: str) -> str:
return await self._brain(str, task)
Model Selection
agent = await spawn(
premise="Fast responses",
model="openai:gpt-5"
)
@agentic(model="anthropic:claude-sonnet-4.5")
async def analyze(text: str) -> dict:
"""Analyze text."""
...
Available models:
openai:gpt-3.5-turbo, openai:gpt-4o, openai:gpt-4.1, openai:gpt-5
anthropic:claude-sonnet-4, anthropic:claude-opus-4.1
anthropic:claude-sonnet-4.5, anthropic:claude-opus-4.5
- Any OpenRouter slug (e.g.,
google/gemini-2.5-flash)
Persistence (Stateful Agents)
@agentic(persist=True)
async def chatbot(message: str) -> str:
"""Remembers conversation history."""
...
await chatbot("My name is Alice")
await chatbot("What's my name?")
For spawn() agents, state is automatic across calls to the same instance.
Token Limits
from agentica import spawn, MaxTokens
agent = await spawn(
premise="Brief responses",
max_tokens=500
)
agent = await spawn(
premise="Controlled output",
max_tokens=MaxTokens(
per_invocation=5000,
per_round=1000,
rounds=5
)
)
Token Usage Tracking
from agentica import spawn, last_usage, total_usage
agent = await spawn(premise="You are helpful.")
await agent.call(str, "Hello!")
usage = agent.last_usage()
print(f"Last: {usage.input_tokens} in, {usage.output_tokens} out")
usage = agent.total_usage()
print(f"Total: {usage.total_tokens} processed")
@agentic()
async def my_fn(x: str) -> str: ...
await my_fn("test")
print(last_usage(my_fn))
print(total_usage(my_fn))
Streaming
from agentica import spawn
from agentica.logging.loggers import StreamLogger
import asyncio
agent = await spawn(premise="You are helpful.")
stream = StreamLogger()
with stream:
result = asyncio.create_task(
agent.call(bool, "Is Paris the capital of France?")
)
async for chunk in stream:
print(chunk.content, end="", flush=True)
final = await result
MCP Integration
from agentica import spawn, agentic
agent = await spawn(
premise="Tool-using agent",
mcp="path/to/mcp_config.json"
)
@agentic(mcp="path/to/mcp_config.json")
async def tool_user(query: str) -> str:
"""Uses MCP tools."""
...
mcp_config.json format:
{
"mcpServers": {
"tavily-remote-mcp": {
"command": "npx -y mcp-remote https://mcp.tavily.com/mcp/?tavilyApiKey=<key>",
"env": {}
}
}
}
Logging
Default Behavior
- Prints to stdout with colors
- Writes to
./logs/agent-<id>.log
Contextual Logging
from agentica.logging.loggers import FileLogger, PrintLogger
from agentica.logging.agent_logger import NoLogging
with FileLogger():
agent = await spawn(premise="Debug agent")
await agent.call(int, "Calculate")
with NoLogging():
agent = await spawn(premise="Silent agent")
Per-Agent Logging
from agentica.logging.agent_listener import (
PrintOnlyListener,
FileOnlyListener,
StandardListener,
NoopListener,
)
agent = await spawn(
premise="Custom logging",
listener=PrintOnlyListener
)
agent = await spawn(
premise="Silent agent",
listener=NoopListener
)
Global Config
from agentica.logging.agent_listener import (
set_default_agent_listener,
get_default_agent_listener,
PrintOnlyListener,
)
set_default_agent_listener(PrintOnlyListener)
set_default_agent_listener(None)
Error Handling
from agentica.errors import (
AgenticaError,
RateLimitError,
InferenceError,
MaxTokensError,
MaxRoundsError,
ContentFilteringError,
APIConnectionError,
APITimeoutError,
InsufficientCreditsError,
OverloadedError,
ServerError,
)
try:
result = await agent.call(str, "Do something")
except RateLimitError:
await asyncio.sleep(60)
result = await agent.call(str, "Do something")
except MaxTokensError:
pass
except ContentFilteringError:
pass
except InferenceError as e:
logger.error(f"Inference failed: {e}")
except AgenticaError as e:
logger.error(f"SDK error: {e}")
Custom Exceptions
class DataValidationError(Exception):
"""Invalid input data."""
pass
@agentic(DataValidationError)
async def analyze(data: str) -> dict:
"""
Analyze data.
Raises:
DataValidationError: If data is malformed
"""
...
try:
result = await analyze(raw_data)
except DataValidationError as e:
logger.warning(f"Invalid: {e}")
Multi-Agent Patterns
Custom Agent Class
from agentica.agent import Agent
class ResearchAgent:
def __init__(self, web_search_fn):
self._brain = Agent(
premise="Research assistant.",
scope={"web_search": web_search_fn}
)
async def research(self, topic: str) -> str:
return await self._brain(str, f"Research: {topic}")
async def summarize(self, text: str) -> str:
return await self._brain(str, f"Summarize: {text}")
Agent Orchestration
class LeadResearcher:
def __init__(self):
self._brain = Agent(
premise="Coordinate research across subagents.",
scope={"SubAgent": ResearchAgent}
)
async def __call__(self, query: str) -> str:
return await self._brain(str, query)
lead = LeadResearcher()
report = await lead("Research AI agent frameworks 2025")
Tracing & Debugging
OpenTelemetry Tracing
from agentica import initialize_tracing
tracer = initialize_tracing(
service_name="my-agent-app",
environment="development",
tempo_endpoint="http://localhost:4317",
organization_id="my-org",
log_level="INFO",
instrument_httpx=False,
)
SDK Debug Logging
from agentica import enable_sdk_logging
disable_fn = enable_sdk_logging(log_tags="1")
disable_fn()
Top-Level Exports
from agentica import (
Agent,
agentic,
spawn,
ModelStrings,
AgenticFunction,
last_usage,
total_usage,
initialize_tracing,
enable_sdk_logging,
__version__,
)
Checklist
Before using Agentica: