探索语义内核
重要
此功能处于实验阶段。 此阶段的功能正在开发中,在升级到预览阶段或候选发布阶段之前可能会更改。
即将推出
OpenAIResponsesAgent
。
功能当前在 Java 中不可用。
什么是响应代理?
OpenAI 响应 API 是 OpenAI 生成模型响应的最高级接口。 它支持文本和图像输入以及文本输出。 可以使用先前响应的输出作为输入创建与模型的有状态交互。 还可以使用用于文件搜索、Web 搜索、计算机使用等的内置工具扩展模型的功能。
准备您的开发环境
若要继续开发 OpenAIResponsesAgent
,请使用相应的包配置开发环境。
即将推出
OpenAIResponsesAgent
。
安装 semantic-kernel
包:
pip install semantic-kernel
重要
在语义内核 Python 包 1.27.0 及更高版本中支持OpenAIResponsesAgent
。
功能当前在 Java 中不可用。
创建一个 OpenAIResponsesAgent
创建OpenAIResponsesAgent
需要先创建一个客户端,以便能够与远程服务进行通信。
即将推出
OpenAIResponsesAgent
。
若要配置 OpenAI 或 Azure OpenAI 响应 API 使用的模型,引入了新的环境变量:
OPENAI_RESPONSES_MODEL_ID=""
AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME=""
根据所使用的提供程序设置适当的变量。
小窍门
允许的最低 Azure OpenAI API 版本为 2025-03-01-preview
。 请访问以下 链接 以查看区域可用性、模型支持和更多详细信息。
若要创建一个 AzureResponsesAgent
以便与 Azure OpenAI 模型一起使用,请:
from semantic_kernel.agents import AzureResponsesAgent
from semantic_kernel.connectors.ai.open_ai import AzureOpenAISettings, OpenAISettings
# Set up the client and model using Azure OpenAI Resources
client = AzureResponsesAgent.create_client()
# Create the AzureResponsesAgent instance using the client and the model
agent = AzureResponsesAgent(
ai_model_id=AzureOpenAISettings().responses_deployment_name,
client=client,
instructions="your instructions",
name="name",
)
或者,若要创建一个与 OpenAI 模型一起使用的 OpenAIResponsesAgent
,请:
from semantic_kernel.agents import OpenAIResponsesAgent
# Set up the client and model using OpenAI Resources
client = OpenAIResponsesAgent.create_client()
# Create the OpenAIResponsesAgent instance using the client and the model
agent = OpenAIResponsesAgent(
ai_model_id=OpenAISettings().responses_model_id,
client=client,
instructions="your instructions",
name="name",
)
功能当前在 Java 中不可用。
使用 OpenAIResponsesAgent
即将推出
OpenAIResponsesAgent
。
OpenAI 响应 API 支持可选的远程存储对话。 默认情况下,使用ResponsesAgentThread
时,响应会被远程存储。 这样就可以使用响应 API previous_response_id
在调用之间维护上下文。
每个会话被视为一个线程,由唯一的字符串 ID 标识。 与你的 OpenAIResponsesAgent
的所有交互都与此线程标识符相关。
响应 API 线程的基础机制由实现 ResponsesAgentThread
接口的 AgentThread
类抽象化。
OpenAIResponsesAgent
目前仅支持类型为 ResponsesAgentThread
的线程。
无需指定 OpenAIResponsesAgent
即可调用 AgentThread
,以启动新线程,新的 AgentThread
将作为响应的一部分返回。
from semantic_kernel.agents import AzureResponsesAgent
# Set up the client and model using Azure OpenAI Resources
client = AzureResponsesAgent.create_client()
# Create the AzureResponsesAgent instance using the client and the model
agent = AzureResponsesAgent(
ai_model_id=AzureOpenAISettings().responses_deployment_name,
client=client,
instructions="your instructions",
name="name",
)
USER_INPUTS = [
"My name is John Doe.",
"Tell me a joke",
"Explain why this is funny.",
"What have we been talking about?",
]
thread = None
# Generate the agent response(s)
for user_input in USER_INPUTS:
print(f"# User: '{user_input}'")
# Invoke the agent for the current message and print the response
response = await agent.get_response(messages=user_input, thread=thread)
print(f"# {response.name}: {response.content}")
# Update the thread so the previous response id is used
thread = response.thread
# Delete the thread when it is no longer needed
await thread.delete() if thread else None
功能当前在 Java 中不可用。
使用 OpenAIResponsesAgent
处理中间消息
语义内核 OpenAIResponsesAgent
旨在调用满足用户查询或问题的代理。 在调用期间,代理可以执行工具来派生最终答案。 若要访问在此过程中生成的中间消息,调用方可以提供一个回调函数来处理FunctionCallContent
或FunctionResultContent
的实例。
即将推出
OpenAIResponsesAgent
。
在on_intermediate_message
或agent.invoke(...)
中配置agent.invoke_stream(...)
回调函数允许调用方在制定代理最终响应的过程中接收生成的中间消息。
import asyncio
from typing import Annotated
from semantic_kernel.agents import AzureResponsesAgent
from semantic_kernel.contents import AuthorRole, FunctionCallContent, FunctionResultContent
from semantic_kernel.contents.chat_message_content import ChatMessageContent
from semantic_kernel.functions import kernel_function
# Define a sample plugin for the sample
class MenuPlugin:
"""A sample Menu Plugin used for the concept sample."""
@kernel_function(description="Provides 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(description="Provides 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"
# This callback function will be called for each intermediate message,
# which will allow one to handle FunctionCallContent and FunctionResultContent.
# If the callback is not provided, the agent will return the final response
# with no intermediate tool call steps.
async def handle_intermediate_steps(message: ChatMessageContent) -> None:
for item in message.items or []:
if isinstance(item, FunctionResultContent):
print(f"Function Result:> {item.result} for function: {item.name}")
elif isinstance(item, FunctionCallContent):
print(f"Function Call:> {item.name} with arguments: {item.arguments}")
else:
print(f"{item}")
async def main():
# 1. Create the client using Azure OpenAI resources and configuration
client = AzureResponsesAgent.create_client()
# 2. Create a Semantic Kernel agent for the OpenAI Responses API
agent = AzureResponsesAgent(
ai_model_id=AzureOpenAISettings().responses_deployment_name,
client=client,
name="Host",
instructions="Answer questions about the menu.",
plugins=[MenuPlugin()],
)
# 3. Create a thread for the agent
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread = None
user_inputs = ["Hello", "What is the special soup?", "What is the special drink?", "How much is that?", "Thank you"]
try:
for user_input in user_inputs:
print(f"# {AuthorRole.USER}: '{user_input}'")
async for response in agent.invoke(
messages=user_input,
thread=thread,
on_intermediate_message=handle_intermediate_steps,
):
thread = response.thread
print(f"# {response.name}: {response.content}")
finally:
await thread.delete() if thread else None
if __name__ == "__main__":
asyncio.run(main())
下面演示了代理调用过程的示例输出:
AuthorRole.USER: 'Hello'
Host: Hi there! How can I assist you with the menu today?
AuthorRole.USER: 'What is the special soup?'
Function Call:> MenuPlugin-get_specials with arguments: {}
Function Result:>
Special Soup: Clam Chowder
Special Salad: Cobb Salad
Special Drink: Chai Tea
for function: MenuPlugin-get_specials
Host: The special soup is Clam Chowder. Would you like to know more about any other specials?
AuthorRole.USER: 'What is the special drink?'
Host: The special drink is Chai Tea. Would you like any more information?
AuthorRole.USER: 'How much is that?'
Function Call:> MenuPlugin-get_item_price with arguments: {"menu_item":"Chai Tea"}
Function Result:> $9.99 for function: MenuPlugin-get_item_price
Host: The Chai Tea is $9.99. Is there anything else you would like to know?
AuthorRole.USER: 'Thank you'
Host: You're welcome! If you have any more questions, feel free to ask. Enjoy your day!
功能当前在 Java 中不可用。
声明性规范
即将推出有关使用声明式规格的文档。
重要
此功能处于实验阶段。 此阶段的功能正在开发中,在升级到预览阶段或候选发布阶段之前可能会更改。
OpenAIResponsesAgent
支持从 YAML 声明性规范中进行实例化。 声明性方法允许在单个可审核文档中定义代理的属性、说明、模型配置、工具和其他选项。 这使得代理组合可移植且易于跨环境进行管理。
注释
声明性 YAML 中列出的任何工具、函数或插件都必须在构造时可供代理使用。 对于基于内核的插件,这意味着必须在内核中注册它们。 对于代码解释器或文件搜索等内置工具,必须提供正确的配置和凭据。 代理加载程序不会从头开始创建函数。 如果缺少所需的组件,代理创建将失败。
如何使用声明性规范
本部分概述了关键原则,并提供概念示例的链接,这些示例显示了每种工具类型的完整代码,而不是枚举每个可能的 YAML 配置。 请参阅以下概念示例,了解具有声明性规范的 OpenAIResponsesAgent
端到端实现:
AzureResponsesAgent
样品:
OpenAIResponsesAgent
样品:
示例:从 YAML 创建 AzureAIAgent
最小 YAML 声明性规范可能如下所示:
type: openai_responses
name: Host
instructions: Respond politely to the user's questions.
model:
id: ${OpenAI:ChatModelId}
tools:
- id: MenuPlugin.get_specials
type: function
- id: MenuPlugin.get_item_price
type: function
有关如何连接代理的详细信息,请参阅上面的完整代码示例。
要点
- 声明性规范允许在 YAML 中定义代理结构、工具和行为。
- 必须在运行时注册或访问所有引用的工具和插件。
- 必应、文件搜索和代码解释器等内置工具需要适当的配置和凭据(通常通过环境变量或显式参数)。
- 有关全面的示例,请参阅提供的示例链接,这些链接演示了实际方案,包括插件注册、Azure 标识配置和高级工具使用。
此功能不可用。