十年匠心定制 · 商业建站与技术教学双线并行 咨询热线:400-886-1026 service@lmnt.cn
ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

aisuite 分层架构实战指南:统一 Chat Completions 客户端、Agent API 与 OpenWorker 智能体框架

aisuite 分层架构实战指南:统一 Chat Completions 客户端、Agent API 与 OpenWorker 智能体框架 aisuite 分层架构实战指南统一 Chat Completions 客户端、Agent API 与 OpenWorker 智能体框架【免费下载链接】aisuiteSimple, unified interface to multiple Generative AI providers项目地址: https://gitcode.com/GitHub_Trending/ai/aisuiteaisuite 是一个简单、统一的多生成式 AI 提供商接口开源项目提供三层递进的能力一个对接 20 提供商、OpenAI 兼容的聊天补全客户端一个轻量的AgentRunner智能体库以及一个开源的桌面端智能体框架 OpenWorker。本文以项目入口文档 README-alternative.md 为主线结合 aisuite/ 包源码与 docs/ 快速上手文档系统讲解三层各自的能力、彼此如何堆叠以及如何用几行代码完成从调用模型到构建完整智能体的实战落地。一、三层架构总览每一层都可独立使用aisuite 的核心设计理念是分层堆叠、逐层独立上层构建在下层之上但任何一层都可以脱离其他层单独使用。入口文档用如下示意图说明三层关系OpenWorker an agent harness for tasks automations (app) │ built on Agent API Agent Runner: tools, state, tracing (lib) │ built on Chat Completions one client, many providers (lib)Chat Completions 层库一个客户端对接多个提供商用字符串切换模型无需维护多套 SDKAgent API 层库在客户端之上提供Agent智能体定义Runner执行器附带工具、持久化状态与追踪能力而不引入重框架OpenWorker 层应用桌面端智能体框架在文件夹中运行任务、使用连接器与工具、产出工件、运行定时自动化。从 aisuite/init.py 的导出列表可以看到Agent、Runner、Client、各种StateStore、ArtifactStore、工具策略ToolPolicy系列等符号全部从包顶层导出这正对应文档每一层都可独立使用的承诺——只需import aisuite as ai即可触达所有能力。二、Chat Completions一个客户端20 提供商1. 安装与 API Key基础安装只包含核心包不带任何提供商 SDK需要哪个提供商就装对应的 extrapip install aisuite # 基础包无提供商 SDK pip install aisuite[anthropic] # 携带某个提供商的 SDK pip install aisuite[all] # 携带全部提供商 SDK按 docs/chat-completions-quickstart.md 的说明API Key 只需为你要调用的提供商设置通常以环境变量形式提供export OPENAI_API_KEYyour-openai-api-key export ANTHROPIC_API_KEYyour-anthropic-api-key也可以编程方式传入Client构造函数client ai.Client({openai: {api_key: ...}})2. 第一次补全调用入口文档给出了最核心的示例——切换模型只需改一个字符串import aisuite as ai client ai.Client() response client.chat.completions.create( modelanthropic:claude-sonnet-4-5, messages[{role: user, content: Why is the sky blue?}], ) print(response.choices[0].message.content)模型名统一使用provider:model-name格式aisuite 负责路由到正确的提供商并在 SDK 之间翻译参数与响应。temperature、max_tokens、tools等核心参数是跨提供商通用的见 docs/chat-completions-quickstart.md。3. 底层路由机制ProviderFactory从源码看这种改字符串换模型的能力由 aisuite/provider.py 中的ProviderFactory实现它扫描aisuite.providers目录下所有*_provider.py文件动态生成受支持提供商集合get_supported_providers()再按命名约定f{provider_key}_provider懒加载模块、实例化对应的XxxProvider类。因此支持哪些提供商直接由 aisuite/providers/ 目录中实际存在的文件决定当前可见 openai、anthropic、gemini、google、mistral、groq、ollama、deepgram、cohere、deepseek、watsonx、xai、together、cerebras、fireworks、huggingface、lmstudio、nebius、openrouter、sambanova、tongyi、azure、aws、crusoe、edenai、featherless、inception、requesty 等本地模型同样支持例如通过 Ollama 运行无需 API Keyresponse client.chat.completions.create( modelollama:llama3.3, messages[{role: user, content: Hello!}], )4. Client 配置与参数校验aisuite/client.py 中的Client构造函数支持两个关键参数参数默认值说明provider_configsNone提供商配置字典键为提供商名如openai、aws-bedrock值为该提供商的配置字典如{api_key: ...}、{aws_access_key: ..., aws_region: ...}extra_param_modewarn未知 ASR音频转写参数的处理策略strict抛ValueError生产环境、warn仅记录警告默认开发环境、permissive全部放行测试Client采用懒初始化策略configure()方法只更新配置、_resolve_provider()在首次调用时才创建提供商实例并且同一个Client暴露了chat与audio两条接口Chat/Completions与Audio/Transcriptions。5. 超出补全流式、异步与音频转写流式streamTrue时返回 OpenAI 形状的分块迭代器chat.completion.chunk见 aisuite/framework/chat_completion_chunk.pyProvider基类在 aisuite/provider.py 中默认抛出LLMError说明不支持流式避免静默挂起异步client.chat.completions.acreate(...)提供异步变体基类的默认异步实现通过asyncio.to_thread把同步调用丢到工作线程因此每个提供商天然可 await而 OpenAI、Anthropic 等原生异步 SDK 会覆盖该方法实现真正非阻塞 I/O音频转写client.audio.transcriptions.create(modelopenai:whisper-1, fileaudio.mp3, languageen)提供跨提供商统一的转写接口常见参数language、prompt、temperature自动映射到各家 SDK 约定提供商特有参数如 Deepgram 的punctuate、diarize直接透传。参数映射与校验由 aisuite/framework/parameter_mapper.py、aisuite/framework/asr_params.py 实现设计动机见 aisuite/design-notes/asr-parameter-design-motivation.md。三、Agent APIAgent Runner 轻量智能体框架当任务需要多轮工具调用、状态持久化与可观测性时入口文档推荐使用AgentRunnerAgent 是可复用的定义Runner 拥有执行权。1. 最小示例入口文档的核心示例把普通 Python 函数直接当作工具import aisuite as ai def get_weather(city: str) - str: Get the current weather for a city. return fIts sunny in {city}. agent ai.Agent( nameassistant, modelopenai:gpt-5.5, instructionsAnswer briefly. Use tools when they help., tools[get_weather], ) result ai.Runner.run_sync(agent, Whats the weather in San Francisco?) print(result.final_output)安装方式pip install aisuite[agents]。2. Agent 与 Runner 的源码视角从 aisuite/agents/types.py 看Agent是一个kw_only数据类字段包括name、model、instructions、tools、model_settings、tags、metadata——纯声明式定义本身不执行任何东西。执行交给 aisuite/agents/runner.py 中的RunnerRunner.run(agent, input, ...)是异步入口签名支持max_turns默认 5、run_name、parent_run_id、group_id、tags、metadata、tool_policy、trace_sinks、state_store/thread_id、artifact_store等生产级参数Runner.run_sync(agent, input)是同步包装内部通过asyncio.run驱动若已在事件循环中运行则回退到nest_asyncio方便脚本与 Notebook 使用返回值RunResult携带final_output、status、messages、raw_responses、steps、trace_id等并可直接to_state()转回RunState以便继续对话。RunState.status的类型为completed | requires_input | max_turns_exceeded | failedRunStep.type覆盖agent / model_response / tool_call / tool_result / handoff / custom为运行过程提供了结构化的记录单元。3. 两种工具调用模式结合 docs/agents-quickstart.md 与 aisuite/client.py 的实现工具调用有两条路径自动多轮max_turns传入普通 Python 函数aisuite 根据函数签名与 docstring 自动生成 OpenAI 格式的 schema执行调用并把结果回填给模型循环直到模型不再请求工具或达到max_turns上限。response.choices[0].intermediate_messages保留完整工具交互历史可追加到消息列表继续会话。底层实现在Completions._tool_runner()同步与_atool_runner()异步中两者共用事件发射、响应处理逻辑手动工具处理省略max_turns直接传 OpenAI 格式的 JSON 工具规格aisuite 返回模型发起的工具调用请求由你自行执行、校验、过滤——适合已有工具管线或需要自定义错误处理的场景。4. 生产级组件策略、状态、工件、追踪入口文档与快速上手共同列出的四类生产组件在 aisuite/agents/ 中均有对应实现能力可用实现源码位置工具策略Tool policiesRequireApprovalPolicy、AllowToolsPolicy/DenyAllToolPolicy或任意接收ToolPolicyContext的可调用对象aisuite/agents/policies.py状态存储State storesInMemoryStateStore、FileStateStore、PostgresStateStore配合thread_id跨进程恢复、续跑aisuite/agents/state_store.py、aisuite/agents/postgres_state_store.py工件存储ArtifactsFileArtifactStore、InMemoryArtifactStoreaisuite/agents/artifact_store.py追踪Tracing每个RunResult携带步骤、原始响应与trace_id可插拔 trace sinkaisuite/tracing/工具策略通过ToolPolicyContext含agent_name、tool_name、arguments、trace_id、messages等与ToolMetadata含risk_level: low/medium/high、requires_approval等实现细粒度门控RunResult.print_trace()与write_trace_jsonl()让调试与落盘追踪都只需一行代码。相关测试参见 tests/agents/test_tool_policy.py、tests/agents/test_trace_output.py。5. 工具包Toolkits与 MCPToolkits是预置的沙箱工具族ai.toolkits.files(root.)、ai.toolkits.git(root.)、ai.toolkits.shell(...)见 aisuite/toolkits/files.py、aisuite/toolkits/git.py、aisuite/toolkits/shell.py。快速上手示例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(agent, What changed in the last commit? Summarize in 3 bullets.) print(result.final_output)MCPModel Context Protocol任何 MCP 服务器的工具都可以直接交给模型pip install aisuite[mcp]。既可以在tools里内联 MCP 配置字典{type: mcp, name: ..., command: npx, args: [...]}也可以用aisuite.mcp.MCPClient显式创建并复用支持allowed_tools过滤与工具前缀use_tool_prefix。相关实现见 aisuite/mcp/client.py、aisuite/mcp/config.pyCompletions.create()在client.py中通过ExitStack自动管理 MCP 客户端生命周期。注意streamTrue与max_turns不可同时使用源码在_prepare_stream_kwargs()中会主动抛错流式场景请手动执行工具。四、OpenWorker桌面端开源智能体框架入口文档将 OpenWorker 定位为运行日常任务与自动化的开放智能体框架一个桌面应用智能体在你的文件夹中工作使用连接器与工具、产出工件、运行定时自动化。自带 API Key文件与密钥都留在本机。1. 功能亮点多文件夹文件访问按文件夹授予只读 / 读写权限连接器与工具浏览器自动化、各类集成、MCP 服务器工件ArtifactsMarkdown、图片、PDF、CSV、电子表格与 Office 文件自动化Automations定时运行并延续为对话自带模型OpenAI、Anthropic、Gemini以及通过 Ollama 运行的本地模型。2. 快速上手要点结合 docs/openworker-quickstart.md安装macOS 13Apple Silicon与 Windows 10/11x64提供桌面安装包Windows 首次运行时 SmartScreen 可能提示选择More info → Run anyway即可连接模型选择提供商并粘贴 API KeyOpenAI / Anthropic / Gemini或选Ollama完全本地运行可同时连接多个提供商并在会话间切换模型。密钥只存在本机、只发给所选提供商没有 OpenWorker 后端服务器布置任务授予文件夹访问权限只读或读写用自然语言下达指令。文档给出了几类典型任务整理文件夹——按类型和项目分组文件并根据内容重命名截图读取五份供应商方案并生成对比表格价格、条款、截止日期、风险项整理收据并生成按类别汇总的月度费用报告。智能体产物默认存到 scratch 文件夹也可指定目录内置查看器可预览文档、表格、图片与 PDF危险操作shell 命令、写越权文件夹会先请求批准自动化自然语言即可安排周期性任务例如每个工作日早上 7 点搜索我所在行业新闻并写一页简报放到我的 briefings 文件夹自动化在应用运行期间执行可在设置中开启Launch at loginMCP 扩展在Manage → Integrations中添加 MCP 服务器使用与 Claude Desktop、Cursor 相同的mcpServersJSON 格式支持 stdio 与 HTTP并可对每个工具单独配置审批。3. 隐私与开发者参考OpenWorker 无后端模型调用从你的电脑直接发往所配置的提供商API Key、对话与文件都留在本机。其源码位于仓库 platform/ 目录下含coworker/智能体、connectors/连接器、mcp/、memory/、skills/、server/等模块本身就是基于 aisuite 构建完整智能体框架的可运行参考实现入口文档明确说明OpenWorkers source under platform/ is a working reference for building a full agent harness with aisuite。五、如何选择层级从模型调用到完整框架入口文档给出的选择建议非常直白——从最适合你的那一层开始只想调用模型直接用 Chat Completions 层一个客户端、改字符串换模型想给模型工具与多轮能力用 Agent API 层声明Agent、交给Runner想要开箱即用的桌面智能体直接使用 OpenWorker 应用。因为每一层都建立在下一层之上你可以在任意一层升级或降级而不会推倒重来。六、仓库布局与实际源码结构入口文档给出了项目级布局结合当前仓库实际目录对照如下入口文档描述当前仓库实际对应说明aisuite-py/aisuite 包aisuite/Python 包Chat Completions Agent API ASR 等aisuite-js/JS/TS 移植版aisuite-js/TypeScript 实现含 OpenAI/Anthropic/Mistral/Groq/Deepgram 提供商与测试openworker/桌面应用 服务platform/OpenWorker/coworker 源码、GUITauri、服务器与测试code-cli/命令行编码智能体cli/py/aisuite-code-cli/aisuite-code命令行编码智能体examples/examples/各产品可运行示例Notebook 与 Python 脚本docs/docs/快速上手文档chat / agents / openworker注意入口文档中的libs/、apps/目录名与当前仓库实际目录结构略有出入本文以仓库实际结构为准。七、文档导航与进一步学习Chat Completionsdocs/chat-completions-quickstart.md安装、密钥、首次补全、本地模型Agent APIdocs/agents-quickstart.mdmax_turns工具调用、手动工具、AgentRunner、MCPOpenWorkerdocs/openworker-quickstart.md安装、连接模型、任务、自动化、MCP 扩展各提供商指南guides/含 openai、anthropic、gemini、google、aws、azure、ollama 等逐家说明可运行示例examples/如 examples/tool_calling_abstraction.ipynb、examples/mcp_tools_example.ipynb、examples/asr_example.ipynb测试验证tests/ 覆盖客户端、提供商转换、流式、Agent 运行器、工具策略与追踪等如 tests/client/test_client.py、tests/agents/test_runner.py贡献与许可CONTRIBUTING.md、LICENSEMIT结语aisuite 的价值不在于引入新的模型运行时而在于用统一接口 分层架构消除多提供商集成的摩擦Chat Completions 层解决写一次代码、到处换模型Agent API 层解决给模型工具、状态与追踪OpenWorker 层解决开箱即用的桌面智能体。无论是快速原型、生产级智能体服务还是自研 agent harness都可以从 README-alternative.md 描述的这三层中找到合适的起点。【免费下载链接】aisuiteSimple, unified interface to multiple Generative AI providers项目地址: https://gitcode.com/GitHub_Trending/ai/aisuite创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表