外观
协议
OpenAI 兼容 Chat Completions vs Anthropic Messages API;通过
Agent工厂基类 +protocol字段统一选择。
两种协议对比
| 维度 | OpenAI(BaseAgent) | Anthropic(AnthropicAgent) |
|---|---|---|
| Endpoint | /v1/chat/completions | /v1/messages |
| System prompt | messages[0] | 顶层 system 字段 |
| 工具 schema | {type: function, function: {name, description, parameters}} | {name, description, input_schema} |
| 工具调用 | tool_calls[].function.{name, arguments} | content: [{type: tool_use, id, name, input}] |
| 工具结果 | role: tool, tool_call_id, content | role: user, content: [{type: tool_result, tool_use_id, content}] |
| 流式事件 | chunk.choices[].delta.content | message_start / content_block_* / message_delta / message_stop |
| 鉴权头 | Authorization: Bearer <key> | x-api-key: <key> + anthropic-version |
Agent 工厂基类(v0.2.2+)
不直接选 BaseAgent / AnthropicAgent,而是选 Agent + protocol 字段:
python
import dumplingsAI
@dumplingsAI.template_agent("chat", uuid="chat-uuid", description="chat agent")
class ChatAgent(dumplingsAI.Agent):
protocol = "openai" # 或 "anthropic"
prompt = "..."
model_name = "..."
api_key = "..."
api_provider = "..." # 对应协议的 base URL_ProtocolMeta metaclass 在类创建时根据 protocol 字段把 Agent 占位基类替换成 BaseAgent / AnthropicAgent,运行时零开销。直接继承 BaseAgent / AnthropicAgent 也兼容(旧写法)。
双协议公开 API 对称性(v0.3.1)
BaseAgent / AnthropicAgent 公开方法集合完全一致:
| 方法 | BaseAgent | AnthropicAgent |
|---|---|---|
__init__(new_load=True) | ✓ | ✓ |
conversation_with_tool(messages, tool, images) | ✓ | ✓ |
aconversation_with_tool(messages, tool, images) | ✓ | ✓ |
out(content: dict) -> None | ✓ | ✓ |
pack(message, tool_model, tool_name, tool_parameter, finish_task, other, tool_result) | ✓ | ✓ |
register_tool_hook(hook_func) | ✓ | ✓ |
ask_for_help(agent_id, message) | ✓ | ✓ |
list_agents() | ✓ | ✓ |
attempt_completion(report_content) | ✓ | ✓ |
reload() | ✓ | ✓ |
register_template(name, description) | ✓ | ✓ |
activate_template(name) | ✓ | ✓ |
deactivate_template(name) | ✓ | ✓ |
list_templates(name) | ✓ | ✓ |
get_all_available_tools() | ✓ | ✓ |
自定义 Anthropic 端点
AnthropicAgent.api_provider 没有默认值(v0.2.2+ 起强制显式设置),避免"忘记设置 endpoint 误走到官方 API"的隐性 bug。可指向任意兼容 Anthropic Messages API 的服务:
python
class MyAgent(dumplingsAI.AnthropicAgent):
api_provider = "https://api.anthropic.com" # 官方
# api_provider = "https://your-proxy.example.com" # 第三方代理
# api_provider = "https://your-proxy.com/v1/messages" # 完整 endpoint
# api_provider = "bedrock-runtime.us-east-1.amazonaws.com" # AWS Bedrock_endpoint() 智能拼接:
- 末尾是
/v1/messages→ 原样使用 - 末尾是
/v1→ 拼上/messages - 其他 → 拼上
/v1/messages
如果网关要求额外 header(Authorization: Bearer xxx / 租户 ID),在子类 __init__ 里覆盖 self.headers:
python
def __init__(self, new_load=True):
super().__init__(new_load=new_load)
self.headers["X-Tenant-Id"] = "tenant-001"
# self.headers["Authorization"] = f"Bearer {self.api_key}"
# self.headers.pop("x-api-key", None)完整示例见 examples/anthropic_agent/agent_example.py。