API生成
- 作者仓库星标 3,783
- 作者更新于 实时读取
- 作者仓库 Continuous-Claude-v3
- 领域
- AI 智能
- 兼容 Agent
-
- Claude Code
- Cursor
- Cline
- Codex
- Windsurf
- Gemini CLI
- +20
- 信任分
- 88 / 100 · 社区维护
- 作者 / 版本 / 许可
- @parcadei · 未声明 license
- Token 消耗评级
- 较高消耗
- 接入复杂程度
- 需手动接入
- 是否需要外部 API Key
- 需要 · Vendor-specific
- 兼容的系统
- macOS · Linux · Windows
- 底层运行要求
- Python
- 文件与系统权限
-
- 只读
- Shell 执行
- 允许写入 / 修改
- 网络行为
- 允许外网请求
- 安装命令数
- 26 条
档案由构建时根据 SKILL.md 与安装命令自动衍生,可能与作者实际意图存在差异。
需要注意: 未限定 allowed-tools,默认拥有全部工具权限。
---
name: agentica-sdk
description: Build Python agents with Agentica SDK - @agentic decorator, spawn(), persistence, MCP integratio…
category: AI 智能
runtime: Python
---
# agentica-sdk 输出预览
## PART A: 任务判断
- 适用问题:提示词、Agent 工作流、模型评估或自动化推理。
- 输入要求:目标材料、限制条件、期望输出和验收方式。
- 证据边界:围绕“When to Use / Quick Start / Agentic Function (simplest)”读取原文规则,不把推断写成作者承诺。
## PART B: 执行结果
- **01** 任务判断:确认你的需求是否属于提示词、Agent 工作流、模型评估或自动化推理,并标出输入、限制和预期结果。
- **02** 执行计划:优先按“When to Use / Quick Start / Agentic Function (simplest)”拆成步骤,说明每一步会读取什么、修改什么、产出什么。
- **03** 交付结果:给出可复制的命令、文件改动、检查清单或内容草稿,并说明如何继续迭代。
- **04** 风险边界:结合 读取文件、执行终端命令、写入/修改文件、会按任务需要访问外部网络、需要准备 Vendor-specific API Key 给出执行前确认项。
## Running Rules
- 读取文件、执行终端命令、写入/修改文件;会按任务需要访问外部网络;需要准备 Vendor-specific API Key。
- 先小样例验证,再放大到真实任务。
- 交付时同时给结果、检查口径和下一步迭代建议。 原文没有稳定的斜杠命令要求。安装验证后通常全局生效,直接在对话里点名这个 Skill 并描述任务即可。
告诉 Agent 目标文件或材料、期望结果、不可改范围、是否允许联网或执行命令。本 Skill 的权限画像是:读取文件、执行终端命令、写入/修改文件。
先用一个小任务确认它会围绕“When to Use / Quick Start / Agentic Function (simplest)”工作;涉及文件或命令时,先看 diff、日志、预览或测试结果。
检查最终产物是否包含明确结果、必要证据和下一步动作;如果输出泛泛而谈,就补充输入、边界和验收标准后重跑。
---
name: agentica-sdk
description: Build Python agents with Agentica SDK - @agentic decorator, spawn(), persistence, MCP integratio…
category: AI 智能
source: parcadei/Continuous-Claude-v3
---
# agentica-sdk
## 什么时候使用
- 把 AI / Agent方向的常用动作沉淀成 Agent 可调用的技能 适合处理AI Agent、提示词、模型评估与自动化推理,核心价值是把输入、判断、执行、验证和交付边界固定下来,避免 Agent 泛泛回答。 把任务拆成可执行、可检查…
- 面向提示词、Agent 工作流、模型评估或自动化推理,优先处理能明确输入、步骤和验收标准的工作。
## 需要提供什么
- 目标材料、目录范围、期望结果和不可改动内容。
- 是否允许联网、执行命令、读写文件或调用外部服务。
## 执行规则
- 围绕「When to Use / Quick Start / Agentic Function (simplest)」组织步骤,不把推断写成作者事实。
- 读取文件、执行终端命令、写入/修改文件;会按任务需要访问外部网络;需要准备 Vendor-specific API Key。
- 先跑小样例,确认结果可检查后再扩大任务范围。
## 输出要求
- 给出最终产物、关键证据、验证方式和下一步动作。
- 信息不足时标记 unknown,不编造命令、平台或依赖。 作者原文负责流程事实;仓库文件负责来源和命令;流狐只补充适用场景、限制和质量判断。
skill "agentica-sdk" {
输入层 -> 用户目标 + 目标文件 + 禁止范围 + 验收标准
上下文层 -> When to Use / Quick Start / Agentic Function (simplest)
规则层 -> SKILL.md 触发条件 / 执行顺序 / 输出格式
运行层 -> Python | 读取文件、执行终端命令、写入/修改文件 | 会按任务需要访问外部网络
安全层 -> 需要准备 Vendor-specific API Key + 小任务验证 + diff / 日志复核
输出层 -> 可复制结果 + 检查清单 + 下一步迭代
} 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) # Agent computes: 3
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")
# Returns: False
Core Patterns
Return Types
# String (default)
result = await agent.call("What is 2+2?")
# Typed output
result: int = await agent.call(int, "What is 2+2?")
result: dict[str, int] = await agent.call(dict[str, int], "Count items")
# Side-effects only
await agent.call(None, "Send message to John")
Premise vs System Prompt
# Premise: adds to default system prompt
agent = await spawn(premise="You are a math expert.")
# System: full control (replaces default)
agent = await spawn(system="You are a JSON-only responder.")
Passing Tools (Scope)
from agentica import agentic, spawn
# In decorator
@agentic(scope={'web_search': web_search_fn})
async def researcher(query: str) -> str:
"""Research a topic."""
...
# In spawn
agent = await spawn(
premise="Data analyzer",
scope={"analyze": custom_analyzer}
)
# Per-call scope
result = await agent.call(
dict[str, int],
"Analyze the dataset",
dataset=data, # Available as 'dataset'
analyzer=custom_fn # Available as 'analyzer'
)
SDK Integration Pattern
from slack_sdk import WebClient
slack = WebClient(token=SLACK_TOKEN)
# Extract specific methods
@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):
# Synchronous - use Agent() not spawn()
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
# In spawn
agent = await spawn(
premise="Fast responses",
model="openai:gpt-5" # Default: openai:gpt-4.1
)
# In decorator
@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-5anthropic:claude-sonnet-4,anthropic:claude-opus-4.1anthropic: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?") # Knows: Alice
For spawn() agents, state is automatic across calls to the same instance.
Token Limits
from agentica import spawn, MaxTokens
# Simple limit
agent = await spawn(
premise="Brief responses",
max_tokens=500
)
# Fine-grained control
agent = await spawn(
premise="Controlled output",
max_tokens=MaxTokens(
per_invocation=5000, # Total across all rounds
per_round=1000, # Per inference round
rounds=5 # Max inference rounds
)
)
Token Usage Tracking
from agentica import spawn, last_usage, total_usage
agent = await spawn(premise="You are helpful.")
await agent.call(str, "Hello!")
# Agent method
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")
# For @agentic functions
@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?")
)
# Consume stream FIRST for live output
async for chunk in stream:
print(chunk.content, end="", flush=True)
# chunk.role is 'user', 'agent', or 'system'
# Then await result
final = await result
MCP Integration
from agentica import spawn, agentic
# Via config file
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
# File only
with FileLogger():
agent = await spawn(premise="Debug agent")
await agent.call(int, "Calculate")
# Silent
with NoLogging():
agent = await spawn(premise="Silent agent")
Per-Agent Logging
# Listeners are in agent_listener submodule (NOT exported from agentica.logging)
from agentica.logging.agent_listener import (
PrintOnlyListener, # Console output only
FileOnlyListener, # File logging only
StandardListener, # Both console + file (default)
NoopListener, # Silent - no logging
)
agent = await spawn(
premise="Custom logging",
listener=PrintOnlyListener
)
# Silent agent
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) # Disable all
Error Handling
from agentica.errors import (
AgenticaError, # Base for all SDK errors
RateLimitError, # Rate limiting
InferenceError, # HTTP errors from inference
MaxTokensError, # Token limit exceeded
MaxRoundsError, # Max inference rounds exceeded
ContentFilteringError, # Content filtered
APIConnectionError, # Network issues
APITimeoutError, # Request timeout
InsufficientCreditsError,# Out of credits
OverloadedError, # Server overloaded
ServerError, # Generic server error
)
try:
result = await agent.call(str, "Do something")
except RateLimitError:
await asyncio.sleep(60)
result = await agent.call(str, "Do something")
except MaxTokensError:
# Reduce scope or increase limits
pass
except ContentFilteringError:
# Content was filtered
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) # Pass exception type
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
# Initialize tracing (returns TracerProvider)
tracer = initialize_tracing(
service_name="my-agent-app",
environment="development", # Optional
tempo_endpoint="http://localhost:4317", # Optional: Grafana Tempo
organization_id="my-org", # Optional
log_level="INFO", # DEBUG, INFO, WARNING, ERROR
instrument_httpx=False, # Optional: trace HTTP calls
)
SDK Debug Logging
from agentica import enable_sdk_logging
# Enable internal SDK logs (for debugging the SDK itself)
disable_fn = enable_sdk_logging(log_tags="1")
# ... run agents ...
disable_fn() # Disable when done
Top-Level Exports
# Main imports from agentica
from agentica import (
# Core
Agent, # Synchronous agent class
agentic, # @agentic decorator
spawn, # Async agent creation
# Configuration
ModelStrings, # Model string type hints
AgenticFunction, # Agentic function type
# Token tracking
last_usage, # Get last call's token usage
total_usage, # Get cumulative token usage
# Tracing/Logging
initialize_tracing, # OpenTelemetry setup
enable_sdk_logging, # SDK debug logs
# Version
__version__, # "0.3.1"
)
Checklist
Before using Agentica:
- Functions with
@agentic()MUST beasync -
spawn()returns awaitable - useawait spawn(...) -
agent.call()is awaitable - useawait agent.call(...) - First arg to
call()is return type, second is prompt string - Use
persist=Truefor conversation memory in@agentic - Use
Agent()(notspawn()) in synchronous__init__ - Document exceptions in docstrings for agent to raise them
- Import listeners from
agentica.logging.agent_listener(NOTagentica.logging)
先判断是否适合
作者设计意图
作者的方法与取舍
边界和复核