SuperAPI AI 工具集

ai-python-basics

智能体与模型

查看项目

更新于 10-16 05:02

技能介绍

用途:介绍 AI SDK for Python 的基础用法,包括配置模型、构造消息、流式输出、声明工具以及构建基础智能体。

环境与安装:需要 Python 3.12 或更高版本,使用 uv add ai 安装,通过 import ai 引入。若使用网关路由的模型 ID,需设置 AI_GATEWAY_API_KEY。

核心概念:Model 用于选择提供方与模型;Messages 是带类型的 Python 对象;ai.stream 执行一次模型调用并返回一条助手消息;ai.Agent 在循环中包装 ai.stream,负责执行 Python 工具并管理历史。

模型选择:默认建议使用网关模型 ID,例如 model = ai.get_model("anthropic/claude-sonnet-4")。如需直连提供方,需安装额外依赖:uv add "ai[openai]" 或 uv add "ai[anthropic]"。

消息构造:使用 ai.system_message 与 ai.user_message 等构造带类型的消息列表。

基础智能体:用 @ai.tool 装饰异步函数声明工具,创建 ai.Agent(tools=[...]),在 async with agent.run(model, messages) as run 中异步迭代事件,通过 ai.events.TextDelta 获取流式文本,运行结束后用 run.output 取答案、run.messages 取历史。

单次调用:若不需要执行 Python 工具,可用 ai.stream(model, messages),同样异步迭代事件,结束后取 stream.output 并将 stream.message 追加到消息列表。

进阶方向:资料提到可参考 ai-python-custom-loop、ai-python-subagents、ai-python-streaming-tools、ai-python-serverless-execution、ai-python-durable-execution、ai-python-ui-adapter 和 ai-python-custom-provider 等技能了解更高级的模式。

限制:资料未提供收费、价格、平台支持范围及具体效果等信息。