当智能体能够执行超出纯文本生成的任务时,它们才真正有用。工具让它们可以调用函数、查询数据库、发起应用程序编程接口 API 请求——以及完成任何你能用代码实现的行为。
先定义一个带有类型提示和文档字符串的函数,然后将它传给 runner.run()。Dedalus SDK 会自动提取 schema,并在模型决定使用该函数时负责执行。
import asyncio
from dedalus_labs import AsyncDedalus, DedalusRunner
from dotenv import load_dotenv
load_dotenv()
def as_bullets(items: list[str]) -> str:
"""Format items as a bulleted list."""
return "\n".join(f"• {item}" for item in items)
async def main():
client = AsyncDedalus()
runner = DedalusRunner(client)
result = await runner.run(
input=(
"Take the following events and call as_bullets with a list of items (one per event).\n\n"
"Events:\n"
"- Warriors vs Lakers — San Francisco — 2026-01-18\n"
"- Warriors vs Suns — San Francisco — 2026-01-22\n"
"- Warriors vs Celtics — San Francisco — 2026-01-29\n\n"
"Return only the list."
),
model="openai/gpt-5.2",
tools=[as_bullets],
)
print(result.final_output)
if __name__ == "__main__":
asyncio.run(main())
模型会查看各个 tool 的 schema,决定要调用哪一个,然后由 Runner 来执行。多步推理会自动进行——Runner 会持续调用模型,直到任务完成为止。
好的工具通常具备以下特征:
- 所有参数和返回值都有类型提示(type hints)
- 有文档字符串(docstring),清楚说明工具的作用(模型会读取这些内容)
- 名称清晰,能直接体现用途
# 好:有类型提示、有文档、名称清晰
def get_weather(city: str, units: str = "celsius") -> dict:
"""获取某个城市的当前天气。返回温度和天气状况。"""
return {"temp": 22, "conditions": "sunny"}
# 差:无类型提示、无文档、名称不清晰
def do_thing(x):
return some_api_call(x)
工具可以是异步的。Runner 会自动等待它们完成:
async def fetch_user(user_id: int) -> dict:
"""从数据库中获取用户信息。"""
async with db.connection() as conn:
return await conn.fetchone("SELECT * FROM users WHERE id = $1", user_id)
将一个专用智能体封装为 tool。协调器将特定任务委派给专家,同时不放弃对话控制权。
这与交接不同:
- 交接(handoffs):新的智能体接管带有完整历史的对话
- 作为工具的智能体(Agent as tool):专家接收特定输入并返回输出,由协调器继续对话
import asyncio
from dedalus_labs import AsyncDedalus, DedalusRunner
async def main():
client = AsyncDedalus()
runner = DedalusRunner(client)
# 专家:将另一个 runner 的调用封装为工具
async def research_specialist(query: str) -> str:
"""对某个主题进行深入研究。用于需要全面分析的问题。"""
result = await runner.run(
input=query,
model="openai/gpt-5.2", # 更强的研究模型
instructions="You are a research analyst. Be thorough and cite sources.",
mcp_servers=["windsor/brave-search-mcp"] # 通过 Brave Search MCP 进行网页搜索
)
return result.final_output
async def code_specialist(spec: str) -> str:
"""根据规格生成可用于生产环境的代码。"""
result = await runner.run(
input=spec,
model="anthropic/claude-opus-4-5", # 擅长代码
instructions="Write clean, tested, production-ready code."
)
return result.final_output
# 协调器:低成本模型,将任务委派给专家
result = await runner.run(
input="Research quantum computing breakthroughs in 2025, then write a Python simulator for a basic quantum gate",
model="openai/gpt-4o-mini",
tools=[research_specialist, code_specialist]
)
print(result.final_output)
if __name__ == "__main__":
asyncio.run(main())
何时使用这种模式:
| 场景 | 为什么使用 Agent-as-Tool |
|---|
| 视觉 / OCR 任务 | 纯文本协调器将图像任务委派给视觉模型 |
| 代码生成 | 快速模型负责分流,强模型负责写代码 |
| 领域专家 | 通用路由器 → 专门化的指令 / 模型 |
| 成本优化 | 使用便宜的协调器,只在需要时调用昂贵专家 |
工具调用质量因模型而异。要实现可靠的多步工具调用:
openai/gpt-5.2 和 openai/gpt-4.1 能很好地处理复杂工具链。较旧或较小的模型在多步推理方面可能会有困难。