chore: import upstream snapshot with attribution
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
## Semantic Kernel OpenAI Responses Agent
|
||||
|
||||
The responses API is OpenAI's latest core API and an agentic API primitive. See more details [here](https://platform.openai.com/docs/guides/responses-vs-chat-completions).
|
||||
|
||||
### OpenAI Responses Agent
|
||||
|
||||
In Semantic Kernel, we don't currently support the Computer User Agent Tool. This is coming soon.
|
||||
|
||||
#### Environment Variables / Config
|
||||
|
||||
`OPENAI_RESPONSES_MODEL_ID=""`
|
||||
|
||||
### Azure Responses Agent
|
||||
|
||||
The Semantic Kernel Azure Responses Agent leverages Azure OpenAI's new stateful API.
|
||||
It brings together the best capabilities from the chat completions and assistants API in one unified experience.
|
||||
|
||||
For `AzureResponsesAgent` limitations, please see the latest [Azure OpenAI Responses API Docs](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/responses?tabs=python-secure).
|
||||
|
||||
#### API Support
|
||||
|
||||
`2025-03-01-preview` or later, therefore please use `AZURE_OPENAI_API_VERSION="2025-03-01-preview"`.
|
||||
|
||||
Please visit the following [link](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/responses?tabs=python-secure) to view region availability, model support, and further details.
|
||||
|
||||
#### Environment Variables / Config
|
||||
|
||||
`AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME=""`
|
||||
|
||||
The other Azure OpenAI config values used for AzureAssistantAgent or AzureChatCompletion, like `AZURE_OPENAI_API_VERSION` or `AZURE_OPENAI_ENDPOINT` are still valid for the `AzureResponsesAgent`.
|
||||
@@ -0,0 +1,67 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
import asyncio
|
||||
|
||||
from azure.identity import AzureCliCredential
|
||||
|
||||
from semantic_kernel.agents import AzureResponsesAgent
|
||||
from semantic_kernel.connectors.ai.open_ai import AzureOpenAISettings
|
||||
|
||||
"""
|
||||
The following sample demonstrates how to create an OpenAI Responses Agent using either
|
||||
Azure OpenAI or OpenAI. The sample shows how to have the agent answer
|
||||
questions about the world.
|
||||
|
||||
Note, in this sample, a thread is not used. This creates a stateless agent. It will
|
||||
not be able to recall previous messages, which is expected behavior.
|
||||
|
||||
The interaction with the agent is via the `get_response` method, which sends a
|
||||
user input to the agent and receives a response from the agent. The conversation
|
||||
history is maintained by the agent service, i.e. the responses are automatically
|
||||
associated with the thread. Therefore, client code does not need to maintain the
|
||||
conversation history.
|
||||
"""
|
||||
|
||||
USER_INPUTS = [
|
||||
"Hi, my name is John Doe.",
|
||||
"Why is the sky blue?",
|
||||
"What is the speed of light?",
|
||||
"What is my name?",
|
||||
]
|
||||
|
||||
|
||||
async def main():
|
||||
# 1. Create the client using Azure OpenAI resources and configuration
|
||||
client = AzureResponsesAgent.create_client(credential=AzureCliCredential())
|
||||
|
||||
# 2. Create a Semantic Kernel agent for the OpenAI Responses API
|
||||
agent = AzureResponsesAgent(
|
||||
ai_model_id=AzureOpenAISettings().responses_deployment_name,
|
||||
client=client,
|
||||
instructions="Answer questions about the world in one sentence.",
|
||||
name="Expert",
|
||||
)
|
||||
|
||||
for user_input in USER_INPUTS:
|
||||
print(f"# User: '{user_input}'")
|
||||
# 3. Invoke the agent for the current message and print the response
|
||||
response = await agent.get_response(messages=user_input)
|
||||
# We are not using a thread for context, so there will be no memory
|
||||
print(f"# {response.name}: {response.content}")
|
||||
|
||||
"""
|
||||
You should see output similar to the following:
|
||||
|
||||
# User: 'Hi, my name is John Doe.'
|
||||
# Expert: Hello, John Doe! How can I assist you today?
|
||||
# User: 'Why is the sky blue?'
|
||||
# Expert: The sky appears blue because of Rayleigh scattering, where shorter blue light wavelengths are scattered
|
||||
more than other colors by the gases in Earth's atmosphere.
|
||||
# User: 'What is the speed of light?'
|
||||
# Expert: The speed of light in a vacuum is approximately 299,792 kilometers per second (km/s).
|
||||
# User: 'What is my name?'
|
||||
# Expert: I'm sorry, I can't determine your name from our conversation.
|
||||
"""
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
import asyncio
|
||||
|
||||
from azure.identity import AzureCliCredential
|
||||
|
||||
from semantic_kernel.agents import AzureResponsesAgent
|
||||
from semantic_kernel.connectors.ai.open_ai import AzureOpenAISettings
|
||||
|
||||
"""
|
||||
The following sample demonstrates how to create an OpenAI Responses Agent.
|
||||
The sample shows how to have the agent answer questions about the world.
|
||||
|
||||
The interaction with the agent is via the `get_response` method, which sends a
|
||||
user input to the agent and receives a response from the agent. The conversation
|
||||
history is maintained by the agent service, i.e. the responses are automatically
|
||||
associated with the thread. Therefore, client code does not need to maintain the
|
||||
conversation history.
|
||||
"""
|
||||
|
||||
USER_INPUTS = [
|
||||
"My name is John Doe.",
|
||||
"Tell me a joke",
|
||||
"Explain why this is funny.",
|
||||
"What have we been talking about?",
|
||||
]
|
||||
|
||||
|
||||
async def main():
|
||||
# 1. Create the client using Azure OpenAI resources and configuration
|
||||
client = AzureResponsesAgent.create_client(credential=AzureCliCredential())
|
||||
|
||||
# 2. Create a Semantic Kernel agent for the OpenAI Responses API
|
||||
agent = AzureResponsesAgent(
|
||||
ai_model_id=AzureOpenAISettings().responses_deployment_name,
|
||||
client=client,
|
||||
instructions="Answer questions about from the user.",
|
||||
name="Joker",
|
||||
)
|
||||
|
||||
# 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
|
||||
|
||||
for user_input in USER_INPUTS:
|
||||
print(f"# User: '{user_input}'")
|
||||
# 4. 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}")
|
||||
# 5. Update the thread so the previous response id is used
|
||||
thread = response.thread
|
||||
|
||||
"""
|
||||
You should see output similar to the following:
|
||||
|
||||
# User: 'My name is John Doe.'
|
||||
# Joker: Hello, John! How can I assist you today?
|
||||
# User: 'Tell me a joke'
|
||||
# Joker: Sure! Why don't scientists trust atoms?
|
||||
|
||||
Because they make up everything!
|
||||
# User: 'Explain why this is funny.'
|
||||
# Joker: The joke is funny because it plays on the double meaning of "make up." In one sense, atoms are the
|
||||
building blocks of all matter, so they literally "make up" everything. In another sense, "make up" can mean
|
||||
to fabricate or lie, humorously suggesting that atoms are untrustworthy because they "invent" or "fabricate"
|
||||
everything. This clever wordplay is what makes the joke amusing.
|
||||
# User: 'What have we been talking about?'
|
||||
# Joker: We've been discussing a joke about atoms and its humor, focusing on wordplay and double meanings.
|
||||
"""
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
import asyncio
|
||||
from typing import Annotated
|
||||
|
||||
from azure.identity import AzureCliCredential
|
||||
|
||||
from semantic_kernel.agents import AzureResponsesAgent
|
||||
from semantic_kernel.connectors.ai.open_ai import AzureOpenAISettings
|
||||
from semantic_kernel.functions import kernel_function
|
||||
|
||||
"""
|
||||
The following sample demonstrates how to create an OpenAI Responses Agent.
|
||||
The sample shows how to have the agent answer questions about the sample menu.
|
||||
|
||||
The interaction with the agent is via the `get_response` method, which sends a
|
||||
user input to the agent and receives a response from the agent. The conversation
|
||||
history is maintained by the agent service, i.e. the responses are automatically
|
||||
associated with the thread. Therefore, client code does not need to maintain the
|
||||
conversation history.
|
||||
"""
|
||||
|
||||
|
||||
# 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"
|
||||
|
||||
|
||||
# Simulate a conversation with the agent
|
||||
USER_INPUTS = [
|
||||
"Hello",
|
||||
"What is the special soup?",
|
||||
"What is the special drink?",
|
||||
"How much is it?",
|
||||
"Thank you",
|
||||
]
|
||||
|
||||
|
||||
async def main():
|
||||
# 1. Create the client using Azure OpenAI resources and configuration
|
||||
client = AzureResponsesAgent.create_client(credential=AzureCliCredential())
|
||||
|
||||
# 2. Create a Semantic Kernel agent for the OpenAI Responses API
|
||||
agent = AzureResponsesAgent(
|
||||
ai_model_id=AzureOpenAISettings().responses_deployment_name,
|
||||
client=client,
|
||||
instructions="Answer questions about the menu.",
|
||||
name="Host",
|
||||
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
|
||||
|
||||
for user_input in USER_INPUTS:
|
||||
print(f"# User: '{user_input}'")
|
||||
# 4. 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}")
|
||||
thread = response.thread
|
||||
"""
|
||||
You should see output similar to the following:
|
||||
|
||||
# User: 'Hello'
|
||||
# Host: Hi there! How can I assist you today?
|
||||
# User: 'What is the special soup?'
|
||||
# Host: The special soup is Clam Chowder.
|
||||
# User: 'What is the special drink?'
|
||||
# Host: The special drink is Chai Tea.
|
||||
# User: 'How much is it?'
|
||||
# Host: The Chai Tea costs $9.99.
|
||||
# User: 'Thank you'
|
||||
# Host: You're welcome! If you have any more questions, feel free to ask.
|
||||
"""
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
import asyncio
|
||||
|
||||
from semantic_kernel.agents import OpenAIResponsesAgent
|
||||
from semantic_kernel.connectors.ai.open_ai import OpenAISettings
|
||||
|
||||
"""
|
||||
The following sample demonstrates how to create an OpenAI Responses Agent.
|
||||
The sample shows how to have the agent answer questions using the web search
|
||||
preview tool with streaming responses.
|
||||
|
||||
The interaction with the agent is via the `get_response` method, which sends a
|
||||
user input to the agent and receives a response from the agent. The conversation
|
||||
history is maintained by the agent service, i.e. the responses are automatically
|
||||
associated with the thread. Therefore, client code does not need to maintain the
|
||||
conversation history.
|
||||
"""
|
||||
|
||||
|
||||
# Simulate a conversation with the agent
|
||||
USER_INPUTS = [
|
||||
"Find me news articles about the latest technology trends.",
|
||||
]
|
||||
|
||||
|
||||
async def main():
|
||||
# 1. Create the client using OpenAI resources and configuration
|
||||
# Note: the Azure OpenAI Responses API does not yet support the web search tool.
|
||||
client = OpenAIResponsesAgent.create_client()
|
||||
|
||||
web_search_tool = OpenAIResponsesAgent.configure_web_search_tool()
|
||||
|
||||
# 2. Create a Semantic Kernel agent for the OpenAI Responses API
|
||||
agent = OpenAIResponsesAgent(
|
||||
ai_model_id=OpenAISettings().responses_model_id,
|
||||
client=client,
|
||||
instructions="Answer questions from the user about performing web searches for news.",
|
||||
name="NewsSearcher",
|
||||
tools=[web_search_tool],
|
||||
)
|
||||
|
||||
# 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
|
||||
|
||||
for user_input in USER_INPUTS:
|
||||
print(f"# User: '{user_input}'")
|
||||
response = await agent.get_response(messages=user_input, thread=thread)
|
||||
print(f"# {response.name}: {response.content}")
|
||||
thread = response.thread
|
||||
|
||||
"""
|
||||
You should see output similar to the following:
|
||||
|
||||
# User: 'Find me news articles about the latest technology trends.'
|
||||
# NewsSearcher: Recent developments in technology have highlighted several key trends shaping various industries:
|
||||
|
||||
**Artificial Intelligence (AI) Integration**: AI continues to revolutionize sectors by automating tasks,
|
||||
enhancing real-time analytics, and improving content delivery. At the 2025 NAB Show, AI's influence is
|
||||
evident across creator platforms, sports technology, streaming solutions, and cloud architectures.
|
||||
([tvtechnology.com](https://www.tvtechnology.com/news/nab-show-2025-exhibitor-insight-black-box?utm_source=openai))
|
||||
...
|
||||
"""
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from azure.identity import AzureCliCredential
|
||||
|
||||
from semantic_kernel.agents import AzureResponsesAgent
|
||||
from semantic_kernel.connectors.ai.open_ai import AzureOpenAISettings
|
||||
|
||||
"""
|
||||
The following sample demonstrates how to create an OpenAI Responses Agent.
|
||||
The sample shows how to have the agent answer questions about the provided
|
||||
document.
|
||||
|
||||
The interaction with the agent is via the `get_response` method, which sends a
|
||||
user input to the agent and receives a response from the agent. The conversation
|
||||
history is maintained by the agent service, i.e. the responses are automatically
|
||||
associated with the thread. Therefore, client code does not need to maintain the
|
||||
conversation history.
|
||||
"""
|
||||
|
||||
|
||||
# Simulate a conversation with the agent
|
||||
USER_INPUTS = [
|
||||
"By birthday, who is the youngest employee?",
|
||||
"Who works in sales?",
|
||||
"I have a customer request, who can help me?",
|
||||
]
|
||||
|
||||
|
||||
async def main():
|
||||
# 1. Create the client using Azure OpenAI resources and configuration
|
||||
client = AzureResponsesAgent.create_client(credential=AzureCliCredential())
|
||||
|
||||
pdf_file_path = os.path.join(
|
||||
os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "resources", "employees.pdf"
|
||||
)
|
||||
|
||||
with open(pdf_file_path, "rb") as file:
|
||||
file = await client.files.create(file=file, purpose="assistants")
|
||||
|
||||
vector_store = await client.vector_stores.create(
|
||||
name="step4_responses_agent_file_search",
|
||||
file_ids=[file.id],
|
||||
)
|
||||
|
||||
file_search_tool = AzureResponsesAgent.configure_file_search_tool(vector_store.id)
|
||||
|
||||
# 2. Create a Semantic Kernel agent for the OpenAI Responses API
|
||||
agent = AzureResponsesAgent(
|
||||
ai_model_id=AzureOpenAISettings().responses_deployment_name,
|
||||
client=client,
|
||||
instructions="Find answers to the user's questions in the provided file.",
|
||||
name="FileSearch",
|
||||
tools=[file_search_tool],
|
||||
)
|
||||
|
||||
# 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
|
||||
|
||||
try:
|
||||
for user_input in USER_INPUTS:
|
||||
print(f"# User: '{user_input}'")
|
||||
# 4. Invoke the agent for the current message and print the response
|
||||
async for response in agent.invoke(messages=user_input, thread=thread):
|
||||
print(f"# Agent: {response.content}")
|
||||
thread = response.thread
|
||||
finally:
|
||||
# 5. Clean up the resources
|
||||
await client.vector_stores.delete(vector_store.id)
|
||||
await client.files.delete(file.id)
|
||||
|
||||
"""
|
||||
# User: 'By birthday, who is the youngest employee?'
|
||||
# Agent: The youngest employee by birthday is Teodor Britton, born on January 9, 1997.
|
||||
# User: 'Who works in sales?'
|
||||
# Agent: The employees who work in sales are:
|
||||
|
||||
- Mariam Jaslyn, Sales Representative
|
||||
- Hicran Bea, Sales Manager
|
||||
- Angelino Embla, Sales Representative.
|
||||
# User: 'I have a customer request, who can help me?'
|
||||
# Agent: For a customer request, you could reach out to the following people in the sales department:
|
||||
|
||||
- Mariam Jaslyn, Sales Representative
|
||||
- Hicran Bea, Sales Manager
|
||||
- Angelino Embla, Sales Representative.
|
||||
"""
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from semantic_kernel.agents import OpenAIResponsesAgent
|
||||
from semantic_kernel.connectors.ai.open_ai import OpenAISettings
|
||||
from semantic_kernel.contents import ChatMessageContent
|
||||
from semantic_kernel.contents.image_content import ImageContent
|
||||
from semantic_kernel.contents.text_content import TextContent
|
||||
from semantic_kernel.contents.utils.author_role import AuthorRole
|
||||
|
||||
"""
|
||||
The following sample demonstrates how to create an OpenAI Responses Agent.
|
||||
The sample shows how to have the agent answer questions about the provided images.
|
||||
|
||||
The interaction with the agent is via the `get_response` method, which sends a
|
||||
user input to the agent and receives a response from the agent. The conversation
|
||||
history is maintained by the chat history. Therefore, client code does need to
|
||||
maintain the conversation history if conversation context is desired.
|
||||
"""
|
||||
|
||||
|
||||
async def main():
|
||||
# 1. Create the client using OpenAI resources and configuration
|
||||
client = OpenAIResponsesAgent.create_client()
|
||||
|
||||
# 2. Define a file path for an image that will be used in the conversation
|
||||
file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "resources", "cat.jpg")
|
||||
|
||||
# 3. Create a Semantic Kernel agent for the OpenAI Responses API
|
||||
agent = OpenAIResponsesAgent(
|
||||
ai_model_id=OpenAISettings().responses_model_id,
|
||||
client=client,
|
||||
instructions="Answer questions about the provided images.",
|
||||
name="VisionAgent",
|
||||
)
|
||||
|
||||
# 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
|
||||
|
||||
# 4. Define a list of user messages that include text and image content for the vision task
|
||||
user_messages = [
|
||||
ChatMessageContent(
|
||||
role=AuthorRole.USER,
|
||||
items=[
|
||||
TextContent(text="Describe this image."),
|
||||
ImageContent(
|
||||
uri="https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/New_york_times_square-terabass.jpg/1200px-New_york_times_square-terabass.jpg"
|
||||
),
|
||||
],
|
||||
),
|
||||
ChatMessageContent(
|
||||
role=AuthorRole.USER,
|
||||
items=[
|
||||
TextContent(text="What is the main color in this image?"),
|
||||
ImageContent(uri="https://upload.wikimedia.org/wikipedia/commons/5/56/White_shark.jpg"),
|
||||
],
|
||||
),
|
||||
ChatMessageContent(
|
||||
role=AuthorRole.USER,
|
||||
items=[
|
||||
TextContent(text="Is there an animal in this image?"),
|
||||
ImageContent.from_image_file(file_path),
|
||||
],
|
||||
),
|
||||
]
|
||||
|
||||
for user_input in user_messages:
|
||||
print(f"# User: {str(user_input)}") # type: ignore
|
||||
# 5. Invoke the agent with the current chat history and print the response
|
||||
response = await agent.get_response(messages=user_input, thread=thread)
|
||||
print(f"# Agent: {response.content}\n")
|
||||
thread = response.thread
|
||||
"""
|
||||
You should see output similar to the following:
|
||||
|
||||
# User: Describe this image.
|
||||
# Agent: The image depicts a bustling scene of Times Square in New York City...
|
||||
|
||||
# User: What is the main color in this image?
|
||||
# Agent: The main color in the image is blue.
|
||||
|
||||
# User: Is there an animal in this image?
|
||||
# Agent: Yes, there is a cat in the image.
|
||||
"""
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from semantic_kernel.agents import OpenAIResponsesAgent
|
||||
from semantic_kernel.connectors.ai.open_ai import OpenAISettings
|
||||
|
||||
"""
|
||||
The following sample demonstrates how to create an OpenAI Responses Agent.
|
||||
The sample shows how to have the agent provide response using structured outputs.
|
||||
|
||||
The interaction with the agent is via the `get_response` method, which sends a
|
||||
user input to the agent and receives a response from the agent. The conversation
|
||||
history is maintained by the chat history. Therefore, client code does need to
|
||||
maintain the conversation history if conversation context is desired.
|
||||
"""
|
||||
|
||||
user_inputs = ["how can I solve 8x + 7y = -23, and 4x=12?"]
|
||||
|
||||
|
||||
# Define the BaseModel we will use for structured outputs
|
||||
class Step(BaseModel):
|
||||
explanation: str
|
||||
output: str
|
||||
|
||||
|
||||
class Reasoning(BaseModel):
|
||||
steps: list[Step]
|
||||
final_answer: str
|
||||
|
||||
|
||||
async def main():
|
||||
# 1. Create the client using OpenAI resources and configuration
|
||||
# Note: the Azure OpenAI Responses API does not yet support structured outputs.
|
||||
client = OpenAIResponsesAgent.create_client()
|
||||
|
||||
# 2. Create a Semantic Kernel agent for the OpenAI Responses API
|
||||
agent = OpenAIResponsesAgent(
|
||||
ai_model_id=OpenAISettings().responses_model_id,
|
||||
client=client,
|
||||
instructions="Answer the user's questions.",
|
||||
name="StructuredOutputsAgent",
|
||||
text=OpenAIResponsesAgent.configure_response_format(Reasoning),
|
||||
)
|
||||
|
||||
# 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
|
||||
|
||||
for user_input in user_inputs:
|
||||
print(f"# User: {str(user_input)}") # type: ignore
|
||||
# 5. Invoke the agent with the current chat history and print the response
|
||||
response = await agent.get_response(messages=user_input, thread=thread)
|
||||
reasoned_result = Reasoning.model_validate_json(response.message.content)
|
||||
print(f"# {response.name}:\n\n{json.dumps(reasoned_result.model_dump(), indent=4, ensure_ascii=False)}")
|
||||
thread = response.thread
|
||||
|
||||
# 6. Clean up the thread
|
||||
await thread.delete() if thread else None
|
||||
|
||||
"""
|
||||
# User: how can I solve 8x + 7y = -23, and 4x=12?
|
||||
# StructuredOutputsAgent:
|
||||
|
||||
{
|
||||
"steps": [
|
||||
{
|
||||
"explanation": "First, solve the equation 4x = 12 to find the value of x.",
|
||||
"output": "4x = 12\nx = 12 / 4\nx = 3"
|
||||
},
|
||||
{
|
||||
"explanation": "Substitute x = 3 into the first equation 8x + 7y = -23.",
|
||||
"output": "8(3) + 7y = -23"
|
||||
},
|
||||
{
|
||||
"explanation": "Perform the multiplication and simplify the equation.",
|
||||
"output": "24 + 7y = -23"
|
||||
},
|
||||
{
|
||||
"explanation": "Subtract 24 from both sides to isolate the term with y.",
|
||||
"output": "7y = -23 - 24\n7y = -47"
|
||||
},
|
||||
{
|
||||
"explanation": "Divide by 7 to solve for y.",
|
||||
"output": "y = -47 / 7\ny = -6.71 (rounded to two decimal places)"
|
||||
}
|
||||
],
|
||||
"final_answer": "x = 3 and y = -6.71 (rounded to two decimal places)"
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
import asyncio
|
||||
from typing import Annotated
|
||||
|
||||
from semantic_kernel.agents import AgentRegistry, OpenAIResponsesAgent
|
||||
from semantic_kernel.functions import kernel_function
|
||||
|
||||
"""
|
||||
The following sample demonstrates how to create an OpenAI Assistant agent that answers
|
||||
questions about a sample menu using a Semantic Kernel Plugin. The agent is created
|
||||
using a yaml declarative spec.
|
||||
"""
|
||||
|
||||
# Simulate a conversation with the agent
|
||||
USER_INPUTS = [
|
||||
"Hello",
|
||||
"What is the special soup?",
|
||||
"How much does that cost?",
|
||||
"Thank you",
|
||||
]
|
||||
|
||||
# Define the YAML string for the sample
|
||||
SPEC = """
|
||||
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
|
||||
"""
|
||||
|
||||
|
||||
# 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"
|
||||
|
||||
|
||||
async def main():
|
||||
# 1. Create the client using Azure OpenAI resources and configuration
|
||||
client = OpenAIResponsesAgent.create_client()
|
||||
|
||||
# 2. Create the assistant on the Azure OpenAI service
|
||||
agent: OpenAIResponsesAgent = await AgentRegistry.create_from_yaml(
|
||||
SPEC,
|
||||
plugins=[MenuPlugin()],
|
||||
client=client,
|
||||
)
|
||||
|
||||
# 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
|
||||
|
||||
try:
|
||||
for user_input in USER_INPUTS:
|
||||
print(f"# User: {user_input}")
|
||||
# 4. Invoke the agent for the specified thread for response
|
||||
async for response in agent.invoke(
|
||||
messages=user_input,
|
||||
thread=thread,
|
||||
):
|
||||
print(f"# {response.name}: {response}")
|
||||
thread = response.thread
|
||||
finally:
|
||||
# 5. Clean up the resources
|
||||
await thread.delete() if thread else None
|
||||
|
||||
"""
|
||||
Sample Output:
|
||||
|
||||
# User: Hello
|
||||
# Agent: Hello! How can I assist you today?
|
||||
# User: What is the special soup?
|
||||
# ...
|
||||
"""
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user