资讯动态

Semantic Kernel Python 中的 OpenAI / Azure Assistant Agents 完整实战指南

发布时间:2026/9/13 6:28:15 来源:尧图企业网站定制
Semantic Kernel Python 中的 OpenAI / Azure Assistant Agents 完整实战指南【免费下载链接】semantic-kernelIntegrate cutting-edge LLM technology quickly and easily into your apps项目地址: https://gitcode.com/GitHub_Trending/se/semantic-kernel导读本篇文章以 python/samples/concepts/agents/openai_assistant/README.md 为核心脉络系统讲解在 Semantic KernelPython中使用 OpenAI Assistant Agents 与 Azure Assistant Agents 的完整开发流程从客户端创建、Assistant 定义、Thread 会话管理到 Code Interpreter、File Search、函数调用Function Calling、流式输出、结构化输出与声明式 YAML 配置。读完本文你将能够基于仓库中的概念示例独立搭建一个带工具、可流式对话、可声明化部署的 Assistant Agent 应用。OpenAI Assistants API 概述Assistants API 是 OpenAI 提供的面向生产级 AI 助手的解决方案它把「助手」本身抽象为一种可编程资源极大简化了将大语言模型集成进应用的工作量。其核心能力来自三方面专用 AI 助手Purpose-Built AI AssistantsAssistant 是基于 OpenAI 模型构建的专门化 AI能够与用户交互、访问文件、维护持久化会话Thread并调用附加工具从而支撑高度定制化的交互体验。简化的会话管理ThreadThread 是助手与用户之间的一段专用会话消息历史由服务端自动维护系统会根据上下文长度自动存储并按需截断消息开发者无需自己管理对话缓存。内置工具Integrated ToolsAPI 原生提供Code Interpreter让助手执行代码解决复杂任务与File Search基于先进的分块与嵌入技术检索上传文件内容。增强的函数调用Function Calling改进的第三方工具集成支持让助手在原生能力之外无缝扩展自定义函数。在 Semantic Kernel 仓库中Assistants 能力被封装为OpenAIAssistantAgent与AzureAssistantAgent两个核心类二者位于 python/semantic_kernel/agents/open_ai/ 目录下并通过统一的 Agent 抽象对外提供服务。快速上手创建 OpenAI Assistant AgentREADME 给出了一条最简创建链路包含客户端、Assistant 定义、Agent 封装与 Thread 调用四个步骤from semantic_kernel.agents import OpenAIAssistantAgent # 1. 使用 OpenAI 资源与配置创建客户端 client OpenAIAssistantAgent.create_client() # 2. 创建 Assistant 定义 definition await client.beta.assistants.create( modelAzureOpenAISettings().chat_deployment_name, instructionsinstructions, namename, ) # 3. 封装为 Semantic Kernel 的 OpenAI Assistant Agent agent OpenAIAssistantAgent( clientclient, definitiondefinition, ) # 4. 定义 ThreadNone 表示由首次调用自动创建 thread None # 5. 调用 Agent 并逐条消费返回内容 async for content in agent.invoke(messagesuser input, threadthread): print(f# {content.role}: {content.content}) # 从响应中取回 thread以便延续当前上下文 thread response.thread这段代码揭示了 Semantic Kernel 封装 OpenAI Assistants 的关键设计一切远端状态Assistant 定义、Thread、文件都由 OpenAI 服务端托管本地只负责通过client进行创建与调用。注意 README 示例中model一行末尾缺少逗号实际运行时请补全见上方修正版否则会引发 Python 语法错误。源码层面的调用链印证在源码中客户端工厂方法定义于 openai_assistant_agent.py 的create_client()AzureAssistantAgent的对应实现位于 azure_assistant_agent.py。二者均返回可直接访问client.beta.assistants.*的 OpenAI SDK 客户端对象这意味着你既能用 SDK 原生接口管理 Assistant也能完全以 Semantic Kernel 的Agent抽象进行调用。Thread 的延续与清理延续上下文invoke()返回的每个响应对象都携带thread属性。传入threadNone时首次调用会自动创建新 Thread并在响应中返回之后每次将上次响应中的thread传回即可保持同一会话的上下文连续。清理资源仓库内所有样例在finally块中都会执行await thread.delete()与await client.beta.assistants.delete(assistant_idagent.id)防止测试/演示场景中在服务端遗留孤儿资源。生产环境建议按生命周期管理 Thread 与 Assistant。使用 Azure Assistant Agents预览版Azure Assistant Agents 目前处于预览阶段要求使用带-preview后缀的 API 版本最低2024-05-01-preview。随着新特性引入API 版本会持续更新。指定正确 API 版本有两种方式方式一环境变量例如写入.env文件AZURE_OPENAI_API_VERSION2025-01-01-preview方式二在创建客户端时显式传入api_version。创建 Azure 版 Agent 的流程与 OpenAI 版几乎完全一致仅客户端工厂不同from semantic_kernel.agents import AzureAssistantAgent # 使用 Azure OpenAI 资源与配置创建客户端 client AzureAssistantAgent.create_client() # 创建 Assistant 定义 definition await client.beta.assistants.create( modelAzureOpenAISettings().chat_deployment_name, instructionsinstructions, namename, ) # 封装为 Semantic Kernel 的 Azure OpenAI Assistant Agent agent AzureAssistantAgent( clientclient, definitiondefinition, ) thread None async for content in agent.invoke(messagesuser input, threadthread): print(f# {content.role}: {content.content}) thread response.threadAzure 客户端的凭据注入仓库中的 Azure 示例通常还会通过credential参数注入 Azure 身份凭据例如 openai_assistant_chart_maker.py 中的AzureAssistantAgent.create_client(credentialAzureCliCredential())使用 Azure CLI 登录态完成鉴权模型名则统一从AzureOpenAISettings().chat_deployment_name读取该配置类位于 python/semantic_kernel/connectors/ai/open_ai/。使用前请确认你的环境已正确配置 Azure OpenAI 的部署名、Endpoint 与密钥/凭据。进阶能力一集成内置工具Code Interpreter代码解释器Code Interpreter 允许助手生成并执行代码。仓库提供了两种使用方式。编程式创建使用AzureAssistantAgent.configure_code_interpreter_tool()便捷方法获取工具定义与资源对象再传入tools和tool_resources参数code_interpreter_tool, code_interpreter_resource AzureAssistantAgent.configure_code_interpreter_tool() definition await client.beta.assistants.create( modelAzureOpenAISettings().chat_deployment_name, instructionsCreate charts as requested without explanation., nameChartMaker, toolscode_interpreter_tool, tool_resourcescode_interpreter_resource, )完整示例见 openai_assistant_chart_maker.py助手会基于用户给出的数据表格绘制柱状图并通过FileReferenceContent返回生成的图片文件示例配套的 openai_assistant_sample_utils.py 中的download_response_images()会遍历response.items中的FileReferenceContent调用agent.client.files.content(file_id)将图片下载到当前目录。声明式创建也可以完全用 YAML 描述 Agent见 openai_assistant_declarative_code_interpreter.pytype: openai_assistant name: CodeInterpreterAgent description: Agent with code interpreter tool. instructions: Use the code interpreter tool to answer questions that require code to be generated and executed. model: id: ${OpenAI:ChatModelId} connection: api_key: ${OpenAI:ApiKey} tools: - type: code_interpreter options: file_ids: - ${OpenAI:FileId1}该示例先通过client.files.create(filefile, purposeassistants)将本地sales.csv上传为 FileObject再通过AgentRegistry.create_from_yaml(yaml_strspec, clientclient, extras{OpenAI:FileId1: file.id})把文件 ID 注入 YAML 占位符。调用时借助响应元数据response.metadata.get(code, False)判断当前流式分片是否为代码块从而在控制台以 Markdown 代码块形式高亮输出。File Search文件检索File Search 使用先进的分块与嵌入技术检索上传文件。仓库同时提供configure_file_search_tool()便捷方法定义于 openai_assistant_agent.py以及声明式 YAML 版本openai_assistant_declarative_file_search.py。其核心价值在于开发者只需上传原始文档助手即可在对话中自动检索相关内容作答无需自行实现 RAG 管线。进阶能力二函数调用与插件Semantic Kernel 的核心优势之一是能将任意 Kernel 插件Plugin直接挂载到 Assistant Agent 上实现函数调用。以 openai_assistant_streaming.py 中的MenuPlugin为例from semantic_kernel.functions import kernel_function class MenuPlugin: kernel_function(descriptionProvides a list of specials from the menu.) def get_specials(self) - Annotated[str, Returns the specials from the menu.]: return Special Soup: Clam Chowder Special Salad: Cobb Salad Special Drink: Chai Tea kernel_function(descriptionProvides the price of the requested menu item.) def get_item_price( self, menu_item: Annotated[str, The name of the menu item.] ) - Annotated[str, Returns the price of the menu item.]: return $9.99 agent AzureAssistantAgent( clientclient, definitiondefinition, plugins[MenuPlugin()], )只需在构造 Agent 时传入plugins[...]助手便会在对话中自动决定何时调用这些函数。仓库中提供多个相关样例流式版本 openai_assistant_streaming.py、非流式版本 openai_assistant_message_callback.py、以及将插件与函数调用过滤链结合的 openai_assistant_auto_func_invocation_filter.py。观察中间步骤on_intermediate_message 回调非流式invoke()默认只返回最终助手消息但通过on_intermediate_message参数可以实时接收函数调用与结果等中间消息openai_assistant_message_callback.pyasync def handle_intermediate_steps(message: ChatMessageContent) - None: for item in message.items or []: if isinstance(item, FunctionResultContent): print(fFunction Result: {item.result} for function: {item.name}) elif isinstance(item, FunctionCallContent): print(fFunction Call: {item.name} with arguments: {item.arguments}) async for response in agent.invoke( messagesuser_input, threadthread, on_intermediate_messagehandle_intermediate_steps, ): thread response.thread从该样例的注释输出可以看到当用户询问「What is the special soup?」时回调依次打印Function Call: MenuPlugin-get_specials与对应结果随后才是最终答案这为可观测性与调试提供了关键抓手。拦截与改写AUTO_FUNCTION_INVOCATION 过滤器更进一步可以将Kernel实例注入 Agent从而使用 Semantic Kernel 的过滤器机制在函数调用前后进行拦截、改写甚至终止。在 openai_assistant_auto_func_invocation_filter.py 中kernel.filter(FilterTypes.AUTO_FUNCTION_INVOCATION) async def auto_function_invocation_filter(context: AutoFunctionInvocationContext, next): await next(context) result context.function_result if menu in context.function.plugin_name.lower(): context.function_result FunctionResult( functionresult.function, valueWe are sold out, sorry!, ) context.terminate True agent AzureAssistantAgent( clientclient, definitiondefinition, plugins[MenuPlugin()], kernelkernel, )过滤器在函数执行后将其结果改写为「已售罄」并立即终止调用链最终助手会基于改写后的结果作答样例输出为「Im sorry, but all the specials on the menu are currently sold out...」。若只需透传原始结果可在过滤器内直接设置context.terminate True而不改写function_result。这展示了 Semantic Kernel 过滤器体系与 Assistants API 的深度集成能力。进阶能力三流式输出与结构化输出流式对话Streaming使用invoke_stream()替代invoke()即可获得 Token 级流式输出。结合上一节插件示例的调用方式async for response in agent.invoke_stream(messagesuser_input, threadthread): thread response.thread print(response.content, end, flushTrue)openai_assistant_streaming.py 展示了配合first_chunk标志在首个分片时打印角色前缀的完整写法openai_assistant_declarative_code_interpreter.py 则展示了如何通过response.metadata区分代码块与普通文本分片。仓库还提供了图表生成的流式版本 openai_assistant_chart_maker_streaming.py 与消息回调的流式版本 openai_assistant_message_callback_streaming.py可以对照学习。结构化输出Structured Outputs通过AzureAssistantAgent.configure_response_format()便捷方法定义于 openai_assistant_agent.py可以将任意 Pydantic 模型转换为服务端的response_format强制助手按预定义 Schema 返回from pydantic import BaseModel class ResponseModel(BaseModel): response: str items: list[str] definition await client.beta.assistants.create( modelAzureOpenAISettings().chat_deployment_name, nameAssistant, instructionsYou are a helpful assistant answering questions about the world in one sentence., response_formatAzureAssistantAgent.configure_response_format(ResponseModel), )调用时响应内容即符合ResponseModel的 JSON可直接用ResponseModel.model_validate_json(str(response.content))反序列化校验见 openai_assistant_structured_outputs.py。README 注释中还说明了另一种方式不借助便捷方法直接手写 JSON Schema 传给response_format此时务必保证 Schema 格式正确type: json_schema含name、strict: True等字段。进阶能力四声明式 Agent 与复用已有 Agent基于 YAML 声明式创建Semantic Kernel 支持通过AgentRegistry.create_from_yaml()以声明式方式创建 Agent配置以type: openai_assistant/type: azure_assistant标识占位符支持${OpenAI:...}长格式或extras短格式注入。除代码解释器外仓库还提供了函数调用openai_assistant_declarative_function_calling_from_file.py与模板化openai_assistant_declarative_templating.py的声明式样例对应 Azure 版本则以azure_openai_assistant_declarative_*前缀命名。这种模式将 Agent 定义与代码解耦便于版本管理与多环境部署。复用已有 Assistant ID如果 Assistant 已在 OpenAI 服务端创建可以通过 ID 直接恢复实例无需重新定义openai_assistant_retrieval.py 展示了先client.beta.assistants.create(...)创建、记录definition.id再client.beta.assistants.retrieve(assistant_id)取回定义并重建 Agent 的过程。而 openai_assistant_declarative_with_existing_agent_id.py 展示了在 YAML 中通过id: ${OpenAI:AgentId}引用已有 Agentid: ${OpenAI:AgentId} type: openai_assistant instructions: You are helpful agent who always responds in French.创建时传入extras{AgentId: my-agent-id}即可。该样例中助手被指示始终用法语回答示例输出展示了完整的法语回答内容关于瑞利散射解释天空为何是蓝色的验证了声明式配置对指令的有效继承。样例全景与延伸阅读openai_assistant目录python/samples/concepts/agents/openai_assistant/共包含 24 个示例文件覆盖了本主题的绝大多数实战场景能力类别示例文件基础创建与对话openai_assistant_chart_maker.py、openai_assistant_retrieval.py流式输出openai_assistant_streaming.py、openai_assistant_chart_maker_streaming.pyCode Interpreteropenai_assistant_declarative_code_interpreter.py、azure_openai_assistant_declarative_code_interpreter.pyFile Searchopenai_assistant_declarative_file_search.py、azure_openai_assistant_declarative_file_search.py文件处理与下载openai_assistant_file_manipulation.py、openai_assistant_sample_utils.py函数调用与回调openai_assistant_message_callback.py含流式版过滤器openai_assistant_auto_func_invocation_filter.py含流式版结构化输出openai_assistant_structured_outputs.py模板化openai_assistant_declarative_templating.py含流式版复用已有 Agentopenai_assistant_declarative_with_existing_agent_id.py、azure_openai_assistant_declarative_with_existing_agent_id.py视觉Visionopenai_assistant_vision_streaming.py所有示例均可直接以python运行内部通过asyncio.run(main())驱动但都需要先配置好对应模型服务的环境变量与凭据。单元测试方面python/tests/unit/agents/openai_assistant/目录下的 test_openai_assistant_agent.py、test_azure_assistant_agent.py 与 test_open_ai_assistant_channel.py 覆盖了 Agent 构建、Thread 操作与调用通道的单元级验证是理解内部行为的另一条路径。若想进一步掌握 Agent 抽象的整体设计可阅读仓库决策文档 0032-agents.md 与 Agent 核心源码 python/semantic_kernel/agents/。总结OpenAI / Azure Assistant Agents 将「对话状态管理、内置工具、函数调用」等繁重工作全部下沉到服务端而 Semantic Kernel 的OpenAIAssistantAgent/AzureAssistantAgent则以统一的 Agent 抽象补齐了插件、过滤器、流式与声明式配置等工程能力。实际落地时只需记住四条主线create_client 建连 → beta.assistants.create 定义 → Agent 封装可挂插件/Kernel→ invoke/invoke_stream 携带 thread 持续对话再按需叠加工具配置、回调与过滤器即可快速构建具备生产级交互能力的 AI 助手应用。【免费下载链接】semantic-kernelIntegrate cutting-edge LLM technology quickly and easily into your apps项目地址: https://gitcode.com/GitHub_Trending/se/semantic-kernel创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价