让你的 Agent,开始工作。¶
用 Python 连接模型、调用工具、保存会话。通过 MCP、Skills 和执行前审批,把一个简单的 Agent Loop 组合成你的应用。
一个能调用工具的 Agent¶
先安装 SDK 并设置模型环境变量。下面是在已创建的 runtime 中注册和调用工具的核心代码:
注册工具,交给 Agent 调用
@runtime.tools.tool(name="add", description="计算两个整数的和。")
def add(a: int, b: int) -> int:
return a + b
result = await runtime.run(
"请调用 add 计算 21 加 34。",
config={"agent": {"tool_names": ["add"]}},
)
print(result.error.message if result.error else result.final_content)
查看完整可运行程序:查询课程信息
保存为 agent.py,运行 python agent.py。示例使用本地数据,终端会显示使用的工具名称和最终回答。
agent.py
import asyncio
import os
import bumblehive
COURSES = {
"Python 入门": "周一 10:00,教学楼 A101",
}
async def main() -> None:
config = bumblehive.RuntimeArguments(
model=os.environ["BUMBLEHIVE_MODEL"],
api_key=os.environ["BUMBLEHIVE_API_KEY"],
base_url=os.environ["BUMBLEHIVE_BASE_URL"],
agent_instructions=("回答课程问题前,必须先调用 get_course_info 工具。"),
tool_names=["get_course_info"],
)
async with bumblehive.from_config(config) as runtime:
@runtime.tools.tool(
name="get_course_info",
description="查询指定课程的上课时间和地点。",
)
def get_course_info(course: str) -> str:
return COURSES.get(course, f"没有找到课程:{course}")
result = await runtime.run("Python 入门课在什么时候、什么地点上课?")
if result.error is not None:
print(f"运行失败 [{result.error.code}]:{result.error.message}")
return
print(f"工具:{', '.join(result.tools_used) or '未调用工具'}")
print(f"回答:{result.final_content}")
if __name__ == "__main__":
asyncio.run(main())
按需构建你的 Agent¶
把能力组合成应用¶
| 你想构建 | 组合方式 |
|---|---|
| 文件与代码助手 | 文件搜索、修改、命令验证与人工审批 |
| 聊天界面 | 文本增量、工具状态、会话与停止操作 |
| 子 Agent 委派 | 用工具委派任务,隔离上下文和工具范围 |
需要查询具体参数时,直接访问 API 参考。文档面向 Python 3.11+,高层 Runtime 使用 OpenAI Chat Completions 兼容接口。