新闻详情

新闻详情

首页 / 资讯中心 / 详情

aisuite Agents 快速上手:用统一接口在多个 LLM 上构建多轮工具调用 Agent

发布时间:2026/9/14 4:07:37来源:尧图网络
aisuite Agents 快速上手:用统一接口在多个 LLM 上构建多轮工具调用 Agent
aisuite Agents 快速上手用统一接口在多个 LLM 上构建多轮工具调用 Agent【免费下载链接】aisuiteSimple, unified interface to multiple Generative AI providers项目地址: https://gitcode.com/GitHub_Trending/ai/aisuite本篇指南以 aisuite 的 Agents 能力为核心讲解如何让模型调用真实 Python 函数、自动生成工具 Schema、执行多轮工具循环并组合 Toolkits、MCP 服务器、工具策略Tool Policies、状态存储State Stores与 Artifacts搭建一套可用于生产环境的 Agent 编排管线。读完你将掌握max_turns自动工具循环、手动工具处理、AgentRunner声明式开发以及 MCP 工具的接入与安全管理。本文假设你已按 Chat Completions 快速入门 完成 aisuite 安装并配置好至少一个提供商的 API Key。模型名采用provider:model-name格式如openai:gpt-4o、anthropic:claude-sonnet-4-6。一、自动工具调用把普通 Python 函数直接交给模型aisuite 最核心的 Agent 能力是你只需传入普通 Python 函数aisuite 会根据函数签名和 docstring 自动生成工具 Schema负责执行模型发起的调用并把执行结果反馈给模型如此循环直到模型给出最终回答或达到max_turns上限。1.1 最小可运行示例import aisuite as ai def will_it_rain(location: str, time_of_day: str): Check if it will rain in a location at a given time today. Args: location (str): Name of the city time_of_day (str): Time of the day in HH:MM format. return YES client ai.Client() response client.chat.completions.create( modelopenai:gpt-4o, messages[{ role: user, content: I live in San Francisco. Can you check for weather and plan an outdoor picnic for me at 2pm? }], tools[will_it_rain], max_turns2 ) print(response.choices[0].message.content)运行流程大致如下aisuite 从will_it_rain的函数签名解析出参数location: str、time_of_day: str从 docstring 提取参数说明生成 OpenAI 格式的function工具规范模型看到工具后返回一次tool_calls请求而不是直接回答aisuite 在内部执行该函数把返回值包装成tool角色的消息回传给模型模型基于工具结果继续推理输出最终答案若轮次达到max_turns则停止。1.2 关键约定Schema 从签名与 docstring 自动生成函数返回值的类型不限但参数建议用类型注解str、int、float、bool等并在 docstring 中为每个参数写出Args:说明——这些信息会直接映射到生成工具 Schema 的properties与required字段中直接影响模型调用工具的准确率。1.3 用intermediate_messages续接对话一次带工具调用的响应中response.choices[0].intermediate_messages保存了完整的工具交互历史模型发起的每次工具调用请求 每次工具执行结果类型定义见 aisuite/framework/choice.py。想继续同一段对话时把它追加进messages传给下一次create即可模型就能感知之前的工具调用上下文all_messages messages list(response.choices[0].intermediate_messages) response2 client.chat.completions.create( modelopenai:gpt-4o, messagesall_messages, tools[will_it_rain], max_turns2, )二、手动工具处理完全掌控工具循环如果不传max_turnsaisuite不会替你执行任何工具而是把模型的工具调用请求原样返回由你自行执行、校验或过滤。此时tools需要传 OpenAI 格式的 JSON 工具规范tools [{ type: function, function: { name: will_it_rain, description: Check if it will rain in a location at a given time today, parameters: { type: object, properties: { location: {type: string, description: Name of the city}, time_of_day: {type: string, description: Time of the day in HH:MM format.} }, required: [location, time_of_day] } } }] response client.chat.completions.create( modelopenai:gpt-4o, messagesmessages, toolstools )拿到响应后从response.choices[0].message.tool_calls读取模型的调用请求自行决定执行策略自定义错误处理如工具抛异常时返回特定提示、选择性执行如只执行白名单内的工具、或接入既有工具管线。两种风格的对比与选择方式适用场景特点max_turns自动循环快速原型、工具可信、追求开发效率aisuite 自动生成 Schema、自动执行并回填结果手动处理需要权限校验、审计、自定义失败逻辑完全掌控循环工具 Schema 需要手写两种方式的完整可运行示例见 examples/tool_calling_abstraction.ipynb。三、Agents API声明式 Agent Runner 编排对于更长时、更结构化的任务推荐使用声明式Agent与Runner的组合一次声明 Agent反复运行并挂载工具策略、状态存储、Artifacts 与 Tracing 等生产级能力。3.1 最小示例import aisuite as ai from aisuite import Agent, Runner agent Agent( namerepo-helper, modelanthropic:claude-sonnet-4-6, instructionsYou are a careful repo assistant. Use your tools to answer from the code., tools[*ai.toolkits.files(root.), *ai.toolkits.git(root.)], ) result Runner.run_sync(agent, What changed in the last commit? Summarize in 3 bullets.) print(result.final_output)Agent是一个声明式数据类定义见 aisuite/agents/types.py核心字段字段类型说明namestrAgent 名称用于日志、Tracing 与上下文标记modelstr模型标识格式provider:model-nameinstructionsstr | None系统指令Runner 会自动将其作为首条system消息注入toolslist[Callable]工具函数列表含 Toolkit 生成的工具model_settingsdict透传给模型的额外参数如temperaturetags/metadatalist[str]/dict用于运行分组与观测的元信息3.2 Runner同步与异步两种入口aisuite/agents/runner.py 中的Runner提供静态方法Runner.run(agent, input, ...)异步运行对应client.chat.completions.acreateRunner.run_sync(agent, input, ...)同步包装。当从已有事件循环内如 Jupyter Notebook调用时会自动借助nest_asyncio兜底未安装相关依赖时会给出明确提示。input可以是普通字符串、消息列表也可以是RunState用于续跑已持久化的会话。常见参数参数默认值说明max_turns5工具循环最大轮数与Client的max_turns语义一致tool_policyNone工具执行策略见下文第四节state_store/thread_idNone持久化状态存储二者必须同时提供artifact_storeNoneArtifact 存储用于保存/恢复大对象run_name/parent_run_id/group_id/tags/metadataNone运行分组与观测元信息trace_sinks/tracing_disabledNone/False自定义 Tracing 输出3.3 读懂RunResultRunner.run_sync返回 RunResult关键成员final_outputAgent 的最终输出优先取最后一条有效内容消息status运行状态取值completed/requires_input/max_turns_exceeded/failedsteps完整步骤列表agent、model_response、tool_call、tool_result等每一步含trace_id、时间戳与数据messages运行后的完整消息历史new_items本轮新增消息raw_responses底层每次模型响应含intermediate_responsestrace_id整次运行的唯一追踪 ID。RunResult还内置了可观测方法print_trace()在终端打印结构化步骤摘要write_trace_jsonl(path)将运行追踪追加写入 JSONL 文件。继续对话时可调用Runner.continue_run/Runner.continue_sync传RunResult或Agent作为目标无需手动拼接历史消息。四、生产级治理组件4.1 Toolkits开箱即用的沙箱工具族ai.toolkits提供三组预构建工具见 aisuite/toolkits/init.pyfiles —— 文件系统工具aisuite/toolkits/files.pyai.toolkits.files( root., # 根目录所有相对路径都基于它解析 allow_writeFalse, # 为 True 时额外暴露写工具 max_read_bytes200_000, # 单文件最大读取字节数 max_search_bytes1_000_000, # 单次搜索累计扫描上限 ignore[.git, .venv, node_modules], # 覆盖默认忽略列表 )只读工具list_files、read_file、read_file_lines、search_files风险等级low写工具allow_writeTrue时暴露write_file、apply_unified_diff、apply_patch、replace_in_file这些工具均标记risk_levelmedium且requires_approvalTrue便于与审批策略联动支持多根目录roots[{path: ..., writable: True}, ...]越界访问会被PermissionError拒绝。git —— 只读 Git 工具aisuite/toolkits/git.pyai.toolkits.git(root., max_output_chars20000)提供git_statusgit status --short --branch与git_diff支持path与staged参数只读、沙箱化。shell —— Shell 执行工具aisuite/toolkits/shell.py面向需要执行命令的场景风险等级最高务必配合工具策略使用。工具本身通过tool()装饰器aisuite/agents/policies.py挂载ToolMetadata其中category、risk_level、capabilities、requires_approval字段会作为策略决策与 Tracing 的依据。4.2 工具策略Tool Policies策略接收一个 ToolPolicyContext内含agent_name、tool_name、arguments、tags、metadata、messages等返回bool或ToolPolicyDecision(allowed, reason)。内置策略AllowAllToolPolicy放行所有工具DenyAllToolPolicy(reasonNone)拒绝所有工具AllowToolsPolicy(allowed_tools, reasonNone)仅放行白名单内的工具名RequireApprovalPolicy(callback)回调返回True放行、False拒绝也可直接返回ToolPolicyDecision——适合接入人工审批界面或外部审批系统。也支持任意满足evaluate(context) - bool | ToolPolicyDecision的可调用对象ToolPolicy为 Protocol 类型见 aisuite/agents/types.py。策略通过Runner.run_sync(agent, input, tool_policy...)注入被拒绝的工具调用会记录为tool.denied追踪事件。4.3 状态存储State Stores跨进程持久化与续跑存储协议aisuite/agents/state_store.py要求实现save_state/load_state/delete_state并提供带乐观锁的revision机制冲突时抛StateConflictError。内置实现InMemoryStateStore()进程内字典适合单进程测试FileStateStore(root.aisuite/state)按thread_id落盘为 JSON 文件写入采用临时文件 os.replace的原子替换方式PostgresStateStore生产环境推荐支持并发与持久化见 aisuite/agents/postgres_state_store.py含CompactionRecord压缩记录。使用方式首次运行传入state_store与thread_id再次运行时直接以相同thread_id调用Runner.continue_run(agent, input, state_store..., thread_id...)即可从上次状态续跑。注意state_store与thread_id必须成对出现且新线程名冲突会抛ThreadAlreadyExistsError缺失线程会抛StateNotFoundError。4.4 ArtifactsAgent 产物的存取aisuite/agents/artifact_store.py 定义了ArtifactStore协议put/get/delete与两种实现InMemoryArtifactStore()内存存储FileArtifactStore(root.aisuite/artifacts)每个 Artifact 一个目录含data文件与metadata.json记录ref、created_at并自动计算sha256摘要。Artifact提供text()方法便捷读取文本内容。Artifact 与状态存储配合使用时Runner会自动对消息中的大对象做脱水/回水dehydrate / hydrate避免把二进制内容直接塞进会话状态。4.5 Tracing每次运行都可观测每个RunResult都携带trace_id、完整steps与原始响应。除了print_trace()/write_trace_jsonl()之外Runner会向配置的 Trace Sinks 发射run.started、model.send、model.response、tool.allowed、tool.denied、tool.completed、tool.failed、run.completed等事件相关机制见 aisuite/tracing/sinks.py 与 aisuite/tracing/viewer.py可对接本地观测面板或自建采集链路。五、MCP 工具接入 Model Context Protocol 服务器任何 Model Context Protocol 服务器的工具都可以接入 aisuite需安装 MCP 支持pip install aisuite[mcp]。5.1 内联配置简单场景直接在tools里声明一个type: mcp的工具response client.chat.completions.create( modelopenai:gpt-4o, messages[{role: user, content: List the files in the current directory}], tools[{ type: mcp, name: filesystem, command: npx, args: [-y, modelcontextprotocol/server-filesystem, /path/to/directory] }], max_turns3 )5.2 显式 MCPClient可复用、带安全过滤对于需要复用连接、过滤工具或做名称前缀隔离的场景使用 aisuite/mcp/client.py 中的MCPClientfrom aisuite.mcp import MCPClient mcp MCPClient( commandnpx, args[-y, modelcontextprotocol/server-filesystem, /path/to/directory] ) response client.chat.completions.create( modelopenai:gpt-4o, messages[{role: user, content: List the files}], toolsmcp.get_callable_tools(), max_turns3 ) mcp.close()MCPClient核心方法list_tools()查看服务器暴露的全部工具 Schemaget_callable_tools(allowed_toolsNone, use_tool_prefixFalse)将工具包装成 aisuite 可调用的 Python 函数。allowed_tools只暴露白名单内的工具安全过滤use_tool_prefixTrue时为工具名加{client_name}__前缀避免多服务器工具名冲突get_tool(tool_name)按名获取单个工具close()关闭服务器连接。MCPClient同时支持 stdio 与 HTTP 两种传输stdio 传command/args/envHTTP 传server_url/headers/timeout默认 30 秒二者互斥。更多用法见 examples/mcp_tools_example.ipynb。六、组合示例把上述能力串成一个生产级 Agent以下示例演示 Agent Toolkits 审批策略 文件状态存储 Artifact 存储 手动续跑的完整组合import aisuite as ai from aisuite import Agent, Runner from aisuite.agents import ( AllowToolsPolicy, FileStateStore, FileArtifactStore, ) agent Agent( namedoc-writer, modelopenai:gpt-4o, instructions( You edit files in the repo. Only use allowed tools. Report what you changed. ), tools[*ai.toolkits.files(root., allow_writeTrue)], ) state_store FileStateStore(root.aisuite/state) artifact_store FileArtifactStore(root.aisuite/artifacts) policy AllowToolsPolicy( allowed_tools[list_files, read_file, search_files, write_file], reasononly read write_file are permitted, ) result Runner.run_sync( agent, Add a NOTES.md describing the repo layout, then summarize., tool_policypolicy, state_storestate_store, thread_iddoc-writer-1, artifact_storeartifact_store, ) print(result.status, result.trace_id) result.print_trace() # 同一线程续跑模型能感知上一次的全部工具历史 result2 Runner.continue_sync( agent, Now append todays date to NOTES.md., state_storestate_store, thread_iddoc-writer-1, artifact_storeartifact_store, ) print(result2.final_output)七、进一步学习若尚未安装 aisuite 或未配置 API Key先阅读 Chat Completions 快速入门可运行的 Notebook 示例集中在 examples/工具调用抽象见 examples/tool_calling_abstraction.ipynbMCP 用法见 examples/mcp_tools_example.ipynbAgent 核心实现源码Agent/RunResult 类型定义、Runner 运行器、工具策略、状态存储、Artifact 存储、MCP 客户端配套测试可参考 tests/agents/ 与 tests/mcp/覆盖 Agent 集成流程、状态续跑、工具策略与 MCP 端到端调用想要现成的桌面 AI 协作工具而非自己搭建可参考 OpenWorker 快速入门其完整源码位于 platform/是使用 aisuite 搭建完整 Agent 编排系统的可运行参考实现。【免费下载链接】aisuiteSimple, unified interface to multiple Generative AI providers项目地址: https://gitcode.com/GitHub_Trending/ai/aisuite创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
网站建设高端定制企业官网
RELATED

相关资讯

更多精彩内容,欢迎继续阅读

较早相关资讯

最新相关资讯

Example Obsidian Links 2026/9/14 5:01:40

Example Obsidian Links

Example Obsidian Links 【免费下载链接】harper Offline, privacy-first grammar checker. Fast, open-source, Rust-powered 项目地址: https://gitcode.com/GitHub_Trending/har/harper Below, you will find a number of example links that Obsidian is able to pr…

阅读更多 →
amis 边框样式工具类 border-style 全解析:从 5 个类名到源码级实现与实战用法 2026/9/14 5:01:40

amis 边框样式工具类 border-style 全解析:从 5 个类名到源码级实现与实战用法

amis 边框样式工具类 border-style 全解析:从 5 个类名到源码级实现与实战用法 【免费下载链接】amis 前端低代码框架,通过 JSON 配置就能生成各种页面。 项目地址: https://gitcode.com/GitHub_Trending/am/amis 本文围绕 amis 低代码框架中 hel…

阅读更多 →
医疗垂直场景RAG调优实战:分段、混合检索、重排与溯源 2026/9/14 5:01:40

医疗垂直场景RAG调优实战:分段、混合检索、重排与溯源

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

阅读更多 →
listmonk 如何为百万级订阅者列表调大 Batch size 提升活动发送吞吐 2026/9/14 5:01:40

listmonk 如何为百万级订阅者列表调大 Batch size 提升活动发送吞吐

listmonk 如何为百万级订阅者列表调大 Batch size 提升活动发送吞吐 【免费下载链接】listmonk High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app. 项目地址: https://gitcode.com/GitHub_Trending/li/listm…

阅读更多 →
Plandex Context Management 完全指南:上下文加载、自动管理与智能窗口机制 2026/9/14 5:01:40

Plandex Context Management 完全指南:上下文加载、自动管理与智能窗口机制

Plandex Context Management 完全指南:上下文加载、自动管理与智能窗口机制 【免费下载链接】plandex Open source AI coding agent. Designed for large projects and real world tasks. 项目地址: https://gitcode.com/GitHub_Trending/pl/plandex Plandex…

阅读更多 →
鸿蒙远程控制五大核心适配细节解析 2026/9/14 4:58:40

鸿蒙远程控制五大核心适配细节解析

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

阅读更多 →

今日资讯

本周资讯

本月资讯

看完文章仍有疑问?

联系尧图顾问,获取一对一建站咨询

立即免费咨询 📞 400-888-8888
📞