chore: import upstream snapshot with attribution
dotnet-build-and-test / dotnet-test-functions (push) Has been cancelled
dotnet-build-and-test / paths-filter (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Debug, windows-latest, net9.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, ubuntu-latest, net10.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, ubuntu-latest, net8.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, windows-latest, net472) (push) Has been cancelled
dotnet-build-and-test / dotnet-test (Release, integration, true, ubuntu-latest, net10.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-test (Release, integration, true, windows-latest, net472) (push) Has been cancelled
dotnet-build-and-test / dotnet-foundry-hosted-it (push) Has been cancelled
dotnet-build-and-test / dotnet-build-and-test-check (push) Has been cancelled
dotnet-build-and-test / Integration Test Report (push) Has been cancelled
CodeQL / Analyze (csharp) (push) Has been cancelled
CodeQL / Analyze (python) (push) Has been cancelled
dotnet-build-and-test / dotnet-test-functions (push) Has been cancelled
dotnet-build-and-test / paths-filter (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Debug, windows-latest, net9.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, ubuntu-latest, net10.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, ubuntu-latest, net8.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, windows-latest, net472) (push) Has been cancelled
dotnet-build-and-test / dotnet-test (Release, integration, true, ubuntu-latest, net10.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-test (Release, integration, true, windows-latest, net472) (push) Has been cancelled
dotnet-build-and-test / dotnet-foundry-hosted-it (push) Has been cancelled
dotnet-build-and-test / dotnet-build-and-test-check (push) Has been cancelled
dotnet-build-and-test / Integration Test Report (push) Has been cancelled
CodeQL / Analyze (csharp) (push) Has been cancelled
CodeQL / Analyze (python) (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
# OpenAI Provider Samples
|
||||
|
||||
This folder contains OpenAI provider samples for the generic clients in
|
||||
`agent_framework.openai`.
|
||||
|
||||
## Chat Completions API samples (`OpenAIChatCompletionClient`)
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| [`chat_completion_client_basic.py`](chat_completion_client_basic.py) | Basic non-streaming and streaming chat completion sample with an explicit `gpt-5.4-nano` model and API key. |
|
||||
| [`chat_completion_client_with_explicit_settings.py`](chat_completion_client_with_explicit_settings.py) | Chat completion sample with explicit model and API key settings. |
|
||||
| [`chat_completion_client_with_function_tools.py`](chat_completion_client_with_function_tools.py) | Function tools with agent-level and run-level patterns. |
|
||||
| [`chat_completion_client_with_local_mcp.py`](chat_completion_client_with_local_mcp.py) | Local MCP integration with the chat completions client. |
|
||||
| [`chat_completion_client_with_runtime_json_schema.py`](chat_completion_client_with_runtime_json_schema.py) | Runtime JSON schema output with the chat completions client. |
|
||||
| [`chat_completion_client_with_session.py`](chat_completion_client_with_session.py) | Session management with the chat completions client. |
|
||||
| [`chat_completion_client_with_web_search.py`](chat_completion_client_with_web_search.py) | Web search with the chat completions client. |
|
||||
|
||||
## Responses API samples (`OpenAIChatClient`)
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| [`client_basic.py`](client_basic.py) | Basic non-streaming and streaming responses sample with an explicit `gpt-5.4-nano` model and API key. |
|
||||
| [`client_image_analysis.py`](client_image_analysis.py) | Analyze images with the responses client. |
|
||||
| [`client_image_generation.py`](client_image_generation.py) | Generate images from text prompts. |
|
||||
| [`client_reasoning.py`](client_reasoning.py) | Reasoning-focused sample for models such as `gpt-5`. |
|
||||
| [`client_streaming_image_generation.py`](client_streaming_image_generation.py) | Streaming image generation sample. |
|
||||
| [`client_verbosity.py`](client_verbosity.py) | GPT-5 `verbosity` option (`low`/`medium`/`high`) with default and per-call overrides. |
|
||||
| [`client_with_agent_as_tool.py`](client_with_agent_as_tool.py) | Agent-as-tool orchestration pattern. |
|
||||
| [`client_with_code_interpreter.py`](client_with_code_interpreter.py) | Code interpreter sample. |
|
||||
| [`client_with_code_interpreter_files.py`](client_with_code_interpreter_files.py) | Code interpreter sample with uploaded files. |
|
||||
| [`client_with_explicit_settings.py`](client_with_explicit_settings.py) | Responses client with explicit model and API key settings. |
|
||||
| [`client_with_file_search.py`](client_with_file_search.py) | Hosted file search sample. |
|
||||
| [`client_with_function_tools.py`](client_with_function_tools.py) | Function tools with agent-level and run-level patterns. |
|
||||
| [`client_with_hosted_mcp.py`](client_with_hosted_mcp.py) | Hosted MCP tools and approval workflows. |
|
||||
| [`client_with_local_mcp.py`](client_with_local_mcp.py) | Local MCP integration with the responses client. |
|
||||
| [`client_with_local_shell.py`](client_with_local_shell.py) | Local shell tool sample. |
|
||||
| [`client_with_runtime_json_schema.py`](client_with_runtime_json_schema.py) | Runtime JSON schema output with the responses client. |
|
||||
| [`client_with_session.py`](client_with_session.py) | Session management with the responses client. |
|
||||
| [`client_with_shell.py`](client_with_shell.py) | Hosted shell tool sample. |
|
||||
| [`client_with_structured_output.py`](client_with_structured_output.py) | Structured output with Pydantic models. |
|
||||
| [`client_with_web_search.py`](client_with_web_search.py) | Web search with the responses client. |
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Set these before running the OpenAI provider samples:
|
||||
|
||||
- `OPENAI_API_KEY`
|
||||
- `OPENAI_MODEL`
|
||||
|
||||
Optionally, you can also set:
|
||||
|
||||
- `OPENAI_ORG_ID`
|
||||
- `OPENAI_BASE_URL`
|
||||
|
||||
If your shell also contains `AZURE_OPENAI_*` variables, these samples still stay on OpenAI as long as
|
||||
`OPENAI_API_KEY` is present. To force Azure routing with the generic clients, pass an explicit Azure
|
||||
input such as `credential`, `azure_endpoint`, or `api_version`, or use the Azure provider samples.
|
||||
|
||||
## Optional Dependencies
|
||||
|
||||
Some samples need extra packages:
|
||||
|
||||
- `client_image_generation.py` and `client_streaming_image_generation.py` use Pillow for image display.
|
||||
- MCP samples require the relevant MCP server/tooling you configure locally.
|
||||
@@ -0,0 +1,85 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.openai import OpenAIChatCompletionClient
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Completion Client Basic Example
|
||||
|
||||
This sample demonstrates basic usage of OpenAIChatCompletionClient with explicit model and
|
||||
API key settings, showing both streaming and non-streaming responses.
|
||||
"""
|
||||
|
||||
|
||||
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production.
|
||||
@tool(approval_mode="never_require")
|
||||
def get_weather(
|
||||
location: Annotated[str, Field(description="The location to get the weather for.")],
|
||||
) -> str:
|
||||
"""Get the weather for a given location."""
|
||||
conditions = ["sunny", "cloudy", "rainy", "stormy"]
|
||||
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
|
||||
|
||||
|
||||
async def non_streaming_example() -> None:
|
||||
"""Example of non-streaming response (get the complete result at once)."""
|
||||
print("=== Non-streaming Response Example ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatCompletionClient(
|
||||
model="gpt-5.4-nano",
|
||||
api_key=os.getenv("OPENAI_API_KEY"),
|
||||
),
|
||||
name="WeatherAgent",
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
query = "What's the weather like in Seattle?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Result: {result}\n")
|
||||
|
||||
|
||||
async def streaming_example() -> None:
|
||||
"""Example of streaming response (get results as they are generated)."""
|
||||
print("=== Streaming Response Example ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatCompletionClient(
|
||||
model="gpt-5.4-nano",
|
||||
api_key=os.getenv("OPENAI_API_KEY"),
|
||||
),
|
||||
name="WeatherAgent",
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
query = "What's the weather like in Portland?"
|
||||
print(f"User: {query}")
|
||||
print("Agent: ", end="", flush=True)
|
||||
async for chunk in agent.run(query, stream=True):
|
||||
if chunk.text:
|
||||
print(chunk.text, end="", flush=True)
|
||||
print("\n")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== Basic OpenAI Chat Completion Client Agent Example ===")
|
||||
|
||||
await non_streaming_example()
|
||||
await streaming_example()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.openai import OpenAIChatCompletionClient
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Completion Client with Explicit Settings Example
|
||||
|
||||
This sample demonstrates creating OpenAI Chat Completion Client with explicit configuration
|
||||
settings rather than relying on environment variable defaults.
|
||||
"""
|
||||
|
||||
|
||||
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
|
||||
# see samples/02-agents/tools/function_tool_with_approval.py
|
||||
# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py.
|
||||
@tool(approval_mode="never_require")
|
||||
def get_weather(
|
||||
location: Annotated[str, Field(description="The location to get the weather for.")],
|
||||
) -> str:
|
||||
"""Get the weather for a given location."""
|
||||
conditions = ["sunny", "cloudy", "rainy", "stormy"]
|
||||
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Chat Completion Client with Explicit Settings ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatCompletionClient(
|
||||
model=os.environ["OPENAI_MODEL"],
|
||||
api_key=os.environ["OPENAI_API_KEY"],
|
||||
),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
result = await agent.run("What's the weather like in New York?")
|
||||
print(f"Result: {result}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.openai import OpenAIChatCompletionClient
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Completion Client with Function Tools Example
|
||||
|
||||
This sample demonstrates function tool integration with OpenAI Chat Completion Client,
|
||||
showing both agent-level and query-level tool configuration patterns.
|
||||
"""
|
||||
|
||||
|
||||
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
|
||||
# see samples/02-agents/tools/function_tool_with_approval.py
|
||||
# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py.
|
||||
@tool(approval_mode="never_require")
|
||||
def get_weather(
|
||||
location: Annotated[str, Field(description="The location to get the weather for.")],
|
||||
) -> str:
|
||||
"""Get the weather for a given location."""
|
||||
conditions = ["sunny", "cloudy", "rainy", "stormy"]
|
||||
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
|
||||
|
||||
|
||||
@tool(approval_mode="never_require")
|
||||
def get_time() -> str:
|
||||
"""Get the current UTC time."""
|
||||
current_time = datetime.now(timezone.utc)
|
||||
return f"The current UTC time is {current_time.strftime('%Y-%m-%d %H:%M:%S')}."
|
||||
|
||||
|
||||
async def tools_on_agent_level() -> None:
|
||||
"""Example showing tools defined when creating the agent."""
|
||||
print("=== Tools Defined on Agent Level ===")
|
||||
|
||||
# Tools are provided when creating the agent
|
||||
# The agent can use these tools for any query during its lifetime
|
||||
agent = Agent(
|
||||
client=OpenAIChatCompletionClient(),
|
||||
instructions="You are a helpful assistant that can provide weather and time information.",
|
||||
tools=[get_weather, get_time], # Tools defined at agent creation
|
||||
)
|
||||
|
||||
# First query - agent can use weather tool
|
||||
query1 = "What's the weather like in New York?"
|
||||
print(f"User: {query1}")
|
||||
result1 = await agent.run(query1)
|
||||
print(f"Agent: {result1}\n")
|
||||
|
||||
# Second query - agent can use time tool
|
||||
query2 = "What's the current UTC time?"
|
||||
print(f"User: {query2}")
|
||||
result2 = await agent.run(query2)
|
||||
print(f"Agent: {result2}\n")
|
||||
|
||||
# Third query - agent can use both tools if needed
|
||||
query3 = "What's the weather in London and what's the current UTC time?"
|
||||
print(f"User: {query3}")
|
||||
result3 = await agent.run(query3)
|
||||
print(f"Agent: {result3}\n")
|
||||
|
||||
|
||||
async def tools_on_run_level() -> None:
|
||||
"""Example showing tools passed to the run method."""
|
||||
print("=== Tools Passed to Run Method ===")
|
||||
|
||||
# Agent created without tools
|
||||
agent = Agent(
|
||||
client=OpenAIChatCompletionClient(),
|
||||
instructions="You are a helpful assistant.",
|
||||
# No tools defined here
|
||||
)
|
||||
|
||||
# First query with weather tool
|
||||
query1 = "What's the weather like in Seattle?"
|
||||
print(f"User: {query1}")
|
||||
result1 = await agent.run(query1, tools=[get_weather]) # Tool passed to run method
|
||||
print(f"Agent: {result1}\n")
|
||||
|
||||
# Second query with time tool
|
||||
query2 = "What's the current UTC time?"
|
||||
print(f"User: {query2}")
|
||||
result2 = await agent.run(query2, tools=[get_time]) # Different tool for this query
|
||||
print(f"Agent: {result2}\n")
|
||||
|
||||
# Third query with multiple tools
|
||||
query3 = "What's the weather in Chicago and what's the current UTC time?"
|
||||
print(f"User: {query3}")
|
||||
result3 = await agent.run(query3, tools=[get_weather, get_time]) # Multiple tools
|
||||
print(f"Agent: {result3}\n")
|
||||
|
||||
|
||||
async def mixed_tools_example() -> None:
|
||||
"""Example showing both agent-level tools and run-method tools."""
|
||||
print("=== Mixed Tools Example (Agent + Run Method) ===")
|
||||
|
||||
# Agent created with some base tools
|
||||
agent = Agent(
|
||||
client=OpenAIChatCompletionClient(),
|
||||
instructions="You are a comprehensive assistant that can help with various information requests.",
|
||||
tools=[get_weather], # Base tool available for all queries
|
||||
)
|
||||
|
||||
# Query using both agent tool and additional run-method tools
|
||||
query = "What's the weather in Denver and what's the current UTC time?"
|
||||
print(f"User: {query}")
|
||||
|
||||
# Agent has access to get_weather (from creation) + additional tools from run method
|
||||
result = await agent.run(
|
||||
query,
|
||||
tools=[get_time], # Additional tools for this specific query
|
||||
)
|
||||
print(f"Agent: {result}\n")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Chat Completion Client Agent with Function Tools Examples ===\n")
|
||||
|
||||
await tools_on_agent_level()
|
||||
await tools_on_run_level()
|
||||
await mixed_tools_example()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,92 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Agent, MCPStreamableHTTPTool
|
||||
from agent_framework.openai import OpenAIChatCompletionClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Completion Client with Local MCP Example
|
||||
|
||||
This sample demonstrates integrating Model Context Protocol (MCP) tools with
|
||||
OpenAI Chat Completion Client for extended functionality and external service access.
|
||||
|
||||
The Agent Framework now supports enhanced metadata extraction from MCP tool
|
||||
results, including error states, token usage, costs, and other arbitrary
|
||||
metadata through the _meta field of CallToolResult objects.
|
||||
"""
|
||||
|
||||
|
||||
async def mcp_tools_on_run_level() -> None:
|
||||
"""Example showing MCP tools defined when running the agent."""
|
||||
print("=== Tools Defined on Run Level ===")
|
||||
|
||||
# Tools are provided when running the agent
|
||||
# This means we have to ensure we connect to the MCP server before running the agent
|
||||
# and pass the tools to the run method.
|
||||
async with (
|
||||
MCPStreamableHTTPTool(
|
||||
name="Microsoft Learn MCP",
|
||||
url="https://learn.microsoft.com/api/mcp",
|
||||
) as mcp_server,
|
||||
Agent(
|
||||
client=OpenAIChatCompletionClient(),
|
||||
name="DocsAgent",
|
||||
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
|
||||
) as agent,
|
||||
):
|
||||
# First query
|
||||
query1 = "How to create an Azure storage account using az cli?"
|
||||
print(f"User: {query1}")
|
||||
result1 = await agent.run(query1, tools=mcp_server)
|
||||
print(f"{agent.name}: {result1}\n")
|
||||
print("\n=======================================\n")
|
||||
# Second query
|
||||
query2 = "What is Microsoft Agent Framework?"
|
||||
print(f"User: {query2}")
|
||||
result2 = await agent.run(query2, tools=mcp_server)
|
||||
print(f"{agent.name}: {result2}\n")
|
||||
|
||||
|
||||
async def mcp_tools_on_agent_level() -> None:
|
||||
"""Example showing tools defined when creating the agent."""
|
||||
print("=== Tools Defined on Agent Level ===")
|
||||
|
||||
# Tools are provided when creating the agent
|
||||
# The agent can use these tools for any query during its lifetime
|
||||
# The agent will connect to the MCP server through its context manager.
|
||||
async with Agent(
|
||||
client=OpenAIChatCompletionClient(),
|
||||
name="DocsAgent",
|
||||
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
|
||||
tools=MCPStreamableHTTPTool( # Tools defined at agent creation
|
||||
name="Microsoft Learn MCP",
|
||||
url="https://learn.microsoft.com/api/mcp",
|
||||
),
|
||||
) as agent:
|
||||
# First query
|
||||
query1 = "How to create an Azure storage account using az cli?"
|
||||
print(f"User: {query1}")
|
||||
result1 = await agent.run(query1)
|
||||
print(f"{agent.name}: {result1}\n")
|
||||
print("\n=======================================\n")
|
||||
# Second query
|
||||
query2 = "What is Microsoft Agent Framework?"
|
||||
print(f"User: {query2}")
|
||||
result2 = await agent.run(query2)
|
||||
print(f"{agent.name}: {result2}\n")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Chat Completion Client Agent with MCP Tools Examples ===\n")
|
||||
|
||||
await mcp_tools_on_agent_level()
|
||||
await mcp_tools_on_run_level()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.openai import OpenAIChatCompletionClient, OpenAIChatOptions
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Completion Client Runtime JSON Schema Example
|
||||
|
||||
Demonstrates structured outputs when the schema is only known at runtime.
|
||||
Uses additional_chat_options to pass a JSON Schema payload directly to OpenAI
|
||||
without defining a Pydantic model up front.
|
||||
"""
|
||||
|
||||
|
||||
runtime_schema = {
|
||||
"title": "WeatherDigest",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"location": {"type": "string"},
|
||||
"conditions": {"type": "string"},
|
||||
"temperature_c": {"type": "number"},
|
||||
"advisory": {"type": "string"},
|
||||
},
|
||||
# OpenAI strict mode requires every property to appear in required.
|
||||
"required": ["location", "conditions", "temperature_c", "advisory"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
|
||||
async def non_streaming_example() -> None:
|
||||
print("=== Non-streaming runtime JSON schema example ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatCompletionClient[OpenAIChatOptions](),
|
||||
name="RuntimeSchemaAgent",
|
||||
instructions="Return only JSON that matches the provided schema. Do not add commentary.",
|
||||
)
|
||||
|
||||
query = "Give a brief weather digest for Seattle."
|
||||
print(f"User: {query}")
|
||||
|
||||
response = await agent.run(
|
||||
query,
|
||||
options={
|
||||
"response_format": {
|
||||
"type": "json_schema",
|
||||
"json_schema": {
|
||||
"name": runtime_schema["title"],
|
||||
"strict": True,
|
||||
"schema": runtime_schema,
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
print("Model output:")
|
||||
print(response.text)
|
||||
|
||||
parsed = json.loads(response.text)
|
||||
print("Parsed dict:")
|
||||
print(parsed)
|
||||
|
||||
|
||||
async def streaming_example() -> None:
|
||||
print("=== Streaming runtime JSON schema example ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatCompletionClient(),
|
||||
name="RuntimeSchemaAgent",
|
||||
instructions="Return only JSON that matches the provided schema. Do not add commentary.",
|
||||
)
|
||||
|
||||
query = "Give a brief weather digest for Portland."
|
||||
print(f"User: {query}")
|
||||
|
||||
chunks: list[str] = []
|
||||
async for chunk in agent.run(
|
||||
query,
|
||||
stream=True,
|
||||
options={
|
||||
"response_format": {
|
||||
"type": "json_schema",
|
||||
"json_schema": {
|
||||
"name": runtime_schema["title"],
|
||||
"strict": True,
|
||||
"schema": runtime_schema,
|
||||
},
|
||||
},
|
||||
},
|
||||
):
|
||||
if chunk.text:
|
||||
chunks.append(chunk.text)
|
||||
|
||||
raw_text = "".join(chunks)
|
||||
print("Model output:")
|
||||
print(raw_text)
|
||||
|
||||
parsed = json.loads(raw_text)
|
||||
print("Parsed dict:")
|
||||
print(parsed)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Chat Completion Client with runtime JSON Schema ===")
|
||||
|
||||
await non_streaming_example()
|
||||
await streaming_example()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,153 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import Agent, AgentSession, InMemoryHistoryProvider, tool
|
||||
from agent_framework.openai import OpenAIChatCompletionClient
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Completion Client with Session Management Example
|
||||
|
||||
This sample demonstrates session management with OpenAI Chat Completion Client, showing
|
||||
conversation sessions and message history preservation across interactions.
|
||||
"""
|
||||
|
||||
|
||||
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
|
||||
# see samples/02-agents/tools/function_tool_with_approval.py
|
||||
# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py.
|
||||
@tool(approval_mode="never_require")
|
||||
def get_weather(
|
||||
location: Annotated[str, Field(description="The location to get the weather for.")],
|
||||
) -> str:
|
||||
"""Get the weather for a given location."""
|
||||
conditions = ["sunny", "cloudy", "rainy", "stormy"]
|
||||
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
|
||||
|
||||
|
||||
async def example_with_automatic_session_creation() -> None:
|
||||
"""Example showing automatic session creation (service-managed session)."""
|
||||
print("=== Automatic Session Creation Example ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatCompletionClient(),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
# First conversation - no session provided, will be created automatically
|
||||
query1 = "What's the weather like in Seattle?"
|
||||
print(f"User: {query1}")
|
||||
result1 = await agent.run(query1)
|
||||
print(f"Agent: {result1.text}")
|
||||
|
||||
# Second conversation - still no session provided, will create another new session
|
||||
query2 = "What was the last city I asked about?"
|
||||
print(f"\nUser: {query2}")
|
||||
result2 = await agent.run(query2)
|
||||
print(f"Agent: {result2.text}")
|
||||
print("Note: Each call creates a separate session, so the agent doesn't remember previous context.\n")
|
||||
|
||||
|
||||
async def example_with_session_persistence() -> None:
|
||||
"""Example showing session persistence across multiple conversations."""
|
||||
print("=== Session Persistence Example ===")
|
||||
print("Using the same session across multiple conversations to maintain context.\n")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatCompletionClient(),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
# Create a new session that will be reused
|
||||
session = agent.create_session()
|
||||
|
||||
# First conversation
|
||||
query1 = "What's the weather like in Tokyo?"
|
||||
print(f"User: {query1}")
|
||||
result1 = await agent.run(query1, session=session)
|
||||
print(f"Agent: {result1.text}")
|
||||
|
||||
# Second conversation using the same session - maintains context
|
||||
query2 = "How about London?"
|
||||
print(f"\nUser: {query2}")
|
||||
result2 = await agent.run(query2, session=session)
|
||||
print(f"Agent: {result2.text}")
|
||||
|
||||
# Third conversation - agent should remember both previous cities
|
||||
query3 = "Which of the cities I asked about has better weather?"
|
||||
print(f"\nUser: {query3}")
|
||||
result3 = await agent.run(query3, session=session)
|
||||
print(f"Agent: {result3.text}")
|
||||
print("Note: The agent remembers context from previous messages in the same session.\n")
|
||||
|
||||
|
||||
async def example_with_existing_session_messages() -> None:
|
||||
"""Example showing how to work with existing session messages for OpenAI."""
|
||||
print("=== Existing Session Messages Example ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatCompletionClient(),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
# Start a conversation and build up message history
|
||||
session = agent.create_session()
|
||||
|
||||
query1 = "What's the weather in Paris?"
|
||||
print(f"User: {query1}")
|
||||
result1 = await agent.run(query1, session=session)
|
||||
print(f"Agent: {result1.text}")
|
||||
|
||||
# The session now contains the conversation history in state
|
||||
memory_state = session.state.get(InMemoryHistoryProvider.DEFAULT_SOURCE_ID, {})
|
||||
messages = memory_state.get("messages", [])
|
||||
if messages:
|
||||
print(f"Session contains {len(messages)} messages")
|
||||
|
||||
print("\n--- Continuing with the same session in a new agent instance ---")
|
||||
|
||||
# Create a new agent instance but use the existing session with its message history
|
||||
new_agent = Agent(
|
||||
client=OpenAIChatCompletionClient(),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
# Use the same session object which contains the conversation history
|
||||
query2 = "What was the last city I asked about?"
|
||||
print(f"User: {query2}")
|
||||
result2 = await new_agent.run(query2, session=session)
|
||||
print(f"Agent: {result2.text}")
|
||||
print("Note: The agent continues the conversation using the local message history.\n")
|
||||
|
||||
print("\n--- Alternative: Creating a new session from existing messages ---")
|
||||
|
||||
new_session = AgentSession()
|
||||
|
||||
query3 = "How does the Paris weather compare to London?"
|
||||
print(f"User: {query3}")
|
||||
result3 = await new_agent.run(query3, session=new_session)
|
||||
print(f"Agent: {result3.text}")
|
||||
print("Note: This creates a new session with the same conversation history.\n")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Chat Completion Client Agent Session Management Examples ===\n")
|
||||
|
||||
await example_with_automatic_session_creation()
|
||||
await example_with_session_persistence()
|
||||
await example_with_existing_session_messages()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,55 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.openai import OpenAIChatCompletionClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Completion Client with Web Search Example
|
||||
|
||||
This sample demonstrates using get_web_search_tool() with OpenAI Chat Completion Client
|
||||
for real-time information retrieval and current data access.
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
client = OpenAIChatCompletionClient(model="gpt-4o-search-preview")
|
||||
|
||||
# Create web search tool with location context
|
||||
web_search_tool = client.get_web_search_tool(
|
||||
web_search_options={
|
||||
"user_location": {
|
||||
"type": "approximate",
|
||||
"approximate": {"city": "Seattle", "country": "US"},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
client=client,
|
||||
instructions="You are a helpful assistant that can search the web for current information.",
|
||||
tools=[web_search_tool],
|
||||
)
|
||||
|
||||
message = "What is the current weather? Do not ask for my current location."
|
||||
stream = False
|
||||
print(f"User: {message}")
|
||||
|
||||
if stream:
|
||||
print("Assistant: ", end="")
|
||||
async for chunk in agent.run(message, stream=True):
|
||||
if chunk.text:
|
||||
print(chunk.text, end="")
|
||||
print("")
|
||||
else:
|
||||
response = await agent.run(message)
|
||||
print(f"Assistant: {response}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,85 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client Basic Example
|
||||
|
||||
This sample demonstrates basic usage of OpenAIChatClient with explicit model and
|
||||
API key settings, showing both streaming and non-streaming responses.
|
||||
"""
|
||||
|
||||
|
||||
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production.
|
||||
@tool(approval_mode="never_require")
|
||||
def get_weather(
|
||||
location: Annotated[str, Field(description="The location to get the weather for.")],
|
||||
) -> str:
|
||||
"""Get the weather for a given location."""
|
||||
conditions = ["sunny", "cloudy", "rainy", "stormy"]
|
||||
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
|
||||
|
||||
|
||||
async def non_streaming_example() -> None:
|
||||
"""Example of non-streaming response (get the complete result at once)."""
|
||||
print("=== Non-streaming Response Example ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(
|
||||
model="gpt-5.4-nano",
|
||||
api_key=os.getenv("OPENAI_API_KEY"),
|
||||
),
|
||||
name="WeatherAgent",
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
query = "What's the weather in Seattle?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Result: {result}\n")
|
||||
|
||||
|
||||
async def streaming_example() -> None:
|
||||
"""Example of streaming response (get results as they are generated)."""
|
||||
print("=== Streaming Response Example ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(
|
||||
model="gpt-5.4-nano",
|
||||
api_key=os.getenv("OPENAI_API_KEY"),
|
||||
),
|
||||
name="WeatherAgent",
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
query = "What's the weather in Portland?"
|
||||
print(f"User: {query}")
|
||||
print("Agent: ", end="", flush=True)
|
||||
async for chunk in agent.run(query, stream=True):
|
||||
if chunk.text:
|
||||
print(chunk.text, end="", flush=True)
|
||||
print("\n")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== Basic OpenAI Chat Client Agent Example ===")
|
||||
|
||||
await non_streaming_example()
|
||||
await streaming_example()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,43 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Agent, Content
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client Image Analysis Example
|
||||
|
||||
This sample demonstrates using OpenAI Chat Client for image analysis and vision tasks,
|
||||
showing multi-modal content handling with text and images.
|
||||
"""
|
||||
|
||||
|
||||
async def main():
|
||||
print("=== OpenAI Chat Client Agent with Image Analysis ===")
|
||||
|
||||
# 1. Create an OpenAI Chat agent with vision capabilities
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
name="VisionAgent",
|
||||
instructions="You are a image analysist, you get a image and need to respond with what you see in the picture.",
|
||||
)
|
||||
|
||||
# 2. Get the agent's response
|
||||
print("User: What do you see in this image? [Image provided]")
|
||||
result = await agent.run(
|
||||
Content.from_uri(
|
||||
uri="https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800",
|
||||
media_type="image/jpeg",
|
||||
)
|
||||
)
|
||||
print(f"Agent: {result.text}")
|
||||
print()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,107 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import tempfile
|
||||
import urllib.request as urllib_request
|
||||
from pathlib import Path
|
||||
|
||||
from agent_framework import Agent, Content
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client Image Generation Example
|
||||
|
||||
This sample demonstrates how to generate images using OpenAI's DALL-E models
|
||||
through the Chat Client. Image generation capabilities enable AI to create visual content from text,
|
||||
making it ideal for creative applications, content creation, design prototyping,
|
||||
and automated visual asset generation.
|
||||
"""
|
||||
|
||||
|
||||
def save_image(output: Content) -> None:
|
||||
"""Save the generated image to a temporary directory.
|
||||
|
||||
This sample is simplified, usually a async aware storing method would be better.
|
||||
"""
|
||||
filename = "generated_image.webp"
|
||||
file_path = Path(tempfile.gettempdir()) / filename
|
||||
|
||||
data_bytes: bytes | None = None
|
||||
uri = getattr(output, "uri", None)
|
||||
|
||||
if isinstance(uri, str):
|
||||
if ";base64," in uri:
|
||||
try:
|
||||
b64 = uri.split(";base64,", 1)[1]
|
||||
data_bytes = base64.b64decode(b64)
|
||||
except Exception:
|
||||
data_bytes = None
|
||||
else:
|
||||
try:
|
||||
data_bytes = urllib_request.urlopen(uri).read()
|
||||
except Exception:
|
||||
data_bytes = None
|
||||
|
||||
if data_bytes is None:
|
||||
raise RuntimeError("Image output present but could not retrieve bytes.")
|
||||
|
||||
with open(file_path, "wb") as f:
|
||||
f.write(data_bytes)
|
||||
|
||||
print(f"Image downloaded and saved to: {file_path}")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Chat Image Generation Agent Example ===")
|
||||
|
||||
# Create an agent with customized image generation options
|
||||
client = OpenAIChatClient()
|
||||
agent = Agent(
|
||||
client=client,
|
||||
instructions="You are a helpful AI that can generate images.",
|
||||
tools=[
|
||||
client.get_image_generation_tool(
|
||||
size="1024x1024",
|
||||
output_format="webp",
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
query = "Generate a black furry cat."
|
||||
print(f"User: {query}")
|
||||
print("Generating image with parameters: 1024x1024 size, WebP format...")
|
||||
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result.text}")
|
||||
|
||||
# Find and save the generated image
|
||||
image_saved = False
|
||||
for message in result.messages:
|
||||
for content in message.contents:
|
||||
if content.type == "image_generation_tool_result" and content.outputs:
|
||||
output = content.outputs
|
||||
if isinstance(output, Content) and output.uri:
|
||||
save_image(output)
|
||||
image_saved = True
|
||||
elif isinstance(output, list):
|
||||
for out in output:
|
||||
if isinstance(out, Content) and out.uri:
|
||||
save_image(out)
|
||||
image_saved = True
|
||||
break
|
||||
if image_saved:
|
||||
break
|
||||
if image_saved:
|
||||
break
|
||||
|
||||
if not image_saved:
|
||||
print("No image data found in the agent response.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,86 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.openai import OpenAIChatClient, OpenAIChatOptions
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client Reasoning Example
|
||||
|
||||
This sample demonstrates advanced reasoning capabilities using OpenAI's gpt-5 models,
|
||||
showing step-by-step reasoning process visualization and complex problem-solving.
|
||||
|
||||
This uses the default_options parameter to enable reasoning with high effort and detailed summaries.
|
||||
You can also set these options at the run level using the options parameter.
|
||||
Since these are api and/or provider specific, you will need to lookup
|
||||
the correct values for your provider, as they are passed through as-is.
|
||||
|
||||
In this case they are here: https://platform.openai.com/docs/api-reference/responses/create#responses-create-reasoning
|
||||
"""
|
||||
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient[OpenAIChatOptions](model="gpt-5"),
|
||||
name="MathHelper",
|
||||
instructions="You are a personal math tutor. When asked a math question, "
|
||||
"reason over how best to approach the problem and share your thought process.",
|
||||
default_options={"reasoning": {"effort": "high", "summary": "detailed"}},
|
||||
)
|
||||
|
||||
|
||||
async def reasoning_example() -> None:
|
||||
"""Example of reasoning response (get results as they are generated)."""
|
||||
print("\033[92m=== Reasoning Example ===\033[0m")
|
||||
|
||||
query = "I need to solve the equation 3x + 11 = 14 and I need to prove the pythagorean theorem. Can you help me?"
|
||||
print(f"User: {query}")
|
||||
print(f"{agent.name}: ", end="", flush=True)
|
||||
response = await agent.run(query)
|
||||
for msg in response.messages:
|
||||
if msg.contents:
|
||||
for content in msg.contents:
|
||||
if content.type == "text_reasoning":
|
||||
print(f"\033[94m{content.text}\033[0m", end="", flush=True)
|
||||
elif content.type == "text":
|
||||
print(content.text, end="", flush=True)
|
||||
print("\n")
|
||||
if response.usage_details:
|
||||
print(f"Usage: {response.usage_details}")
|
||||
|
||||
|
||||
async def streaming_reasoning_example() -> None:
|
||||
"""Example of reasoning response (get results as they are generated)."""
|
||||
print("\033[92m=== Streaming Reasoning Example ===\033[0m")
|
||||
|
||||
query = "I need to solve the equation 3x + 11 = 14 and I need to prove the pythagorean theorem. Can you help me?"
|
||||
print(f"User: {query}")
|
||||
print(f"{agent.name}: ", end="", flush=True)
|
||||
usage = None
|
||||
async for chunk in agent.run(query, stream=True):
|
||||
if chunk.contents:
|
||||
for content in chunk.contents:
|
||||
if content.type == "text_reasoning":
|
||||
print(f"\033[94m{content.text}\033[0m", end="", flush=True)
|
||||
elif content.type == "text":
|
||||
print(content.text, end="", flush=True)
|
||||
elif content.type == "usage":
|
||||
usage = content
|
||||
print("\n")
|
||||
if usage:
|
||||
print(f"Usage: {usage.usage_details}")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("\033[92m=== Basic OpenAI Chat Reasoning Agent Example ===\033[0m")
|
||||
|
||||
await reasoning_example()
|
||||
await streaming_reasoning_example()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,92 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import anyio
|
||||
from agent_framework import Agent, Content
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
"""OpenAI Chat Client Streaming Image Generation Example
|
||||
Demonstrates streaming partial image generation using OpenAI's image generation tool.
|
||||
Shows progressive image rendering with partial images for improved user experience.
|
||||
Note: The number of partial images received depends on generation speed:
|
||||
- High quality/complex images: More partials (generation takes longer)
|
||||
- Low quality/simple images: Fewer partials (generation completes quickly)
|
||||
- You may receive fewer partial images than requested if generation is fast
|
||||
Important: The final partial image IS the complete, full-quality image. Each partial
|
||||
represents a progressive refinement, with the last one being the finished result.
|
||||
"""
|
||||
|
||||
|
||||
async def save_image_from_data_uri(data_uri: str, filename: str) -> None:
|
||||
"""Save an image from a data URI to a file."""
|
||||
try:
|
||||
if data_uri.startswith("data:image/"):
|
||||
# Extract base64 data
|
||||
base64_data = data_uri.split(",", 1)[1]
|
||||
image_bytes = base64.b64decode(base64_data)
|
||||
# Save to file
|
||||
await anyio.Path(filename).write_bytes(image_bytes)
|
||||
print(f" Saved: {filename} ({len(image_bytes) / 1024:.1f} KB)")
|
||||
except Exception as e:
|
||||
print(f" Error saving {filename}: {e}")
|
||||
|
||||
|
||||
async def main():
|
||||
"""Demonstrate streaming image generation with partial images."""
|
||||
print("=== OpenAI Streaming Image Generation Example ===\n")
|
||||
# Create agent with streaming image generation enabled
|
||||
client = OpenAIChatClient()
|
||||
agent = Agent(
|
||||
client=client,
|
||||
instructions="You are a helpful agent that can generate images.",
|
||||
tools=[
|
||||
client.get_image_generation_tool(
|
||||
size="1024x1024",
|
||||
quality="high",
|
||||
partial_images=3,
|
||||
)
|
||||
],
|
||||
)
|
||||
query = "Draw a beautiful sunset over a calm ocean with sailboats"
|
||||
print(f" User: {query}")
|
||||
print()
|
||||
# Track partial images
|
||||
image_count = 0
|
||||
# Use temp directory for output
|
||||
output_dir = Path(tempfile.gettempdir()) / "generated_images"
|
||||
output_dir.mkdir(exist_ok=True)
|
||||
print(" Streaming response:")
|
||||
async for update in agent.run(query, stream=True):
|
||||
for content in update.contents:
|
||||
# Handle partial images
|
||||
# The final partial image IS the complete, full-quality image. Each partial
|
||||
# represents a progressive refinement, with the last one being the finished result.
|
||||
if content.type == "image_generation_tool_result" and isinstance(content.outputs, Content):
|
||||
image_output: Content = content.outputs
|
||||
if image_output.type == "data" and image_output.additional_properties.get("is_partial_image"):
|
||||
print(f" Image {image_count} received")
|
||||
# Extract file extension from media_type (e.g., "image/png" -> "png")
|
||||
extension = "png" # Default fallback
|
||||
if image_output.media_type and "/" in image_output.media_type:
|
||||
extension = image_output.media_type.split("/")[-1]
|
||||
# Save images with correct extension
|
||||
filename = output_dir / f"image{image_count}.{extension}"
|
||||
if image_output.uri is not None:
|
||||
await save_image_from_data_uri(image_output.uri, str(filename))
|
||||
image_count += 1
|
||||
# Summary
|
||||
print("\n Summary:")
|
||||
print(f" Images received: {image_count}")
|
||||
print(f" Output directory: {output_dir}")
|
||||
print("\n Streaming image generation completed!")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,73 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
from typing import Literal
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.openai import OpenAIChatClient, OpenAIChatOptions
|
||||
from dotenv import load_dotenv
|
||||
|
||||
Verbosity = Literal["low", "medium", "high"]
|
||||
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client Verbosity Example
|
||||
|
||||
Demonstrates the GPT-5 ``verbosity`` parameter on the Responses API. ``verbosity``
|
||||
controls how concise or detailed the model's natural-language output is and accepts
|
||||
``"low"``, ``"medium"``, or ``"high"``.
|
||||
|
||||
The framework exposes ``verbosity`` as a top-level option on ``OpenAIChatOptions``
|
||||
(parallel to ``reasoning``) and translates it to ``text.verbosity`` when calling the
|
||||
Responses API.
|
||||
"""
|
||||
|
||||
|
||||
PROMPT = "Explain in your own words what photosynthesis is and why it matters."
|
||||
|
||||
|
||||
async def run_with_verbosity(level: Verbosity) -> None:
|
||||
"""Run the same prompt with a different verbosity setting and print the output length."""
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient[OpenAIChatOptions](model="gpt-5"),
|
||||
name=f"Explainer-{level}",
|
||||
instructions="You are a friendly science explainer.",
|
||||
default_options={"verbosity": level},
|
||||
)
|
||||
|
||||
print(f"\033[92m=== verbosity={level!r} ===\033[0m")
|
||||
response = await agent.run(PROMPT)
|
||||
text = response.text or ""
|
||||
print(text)
|
||||
print(f"\n[chars: {len(text)}]\n")
|
||||
|
||||
|
||||
async def run_per_call_override() -> None:
|
||||
"""Show that verbosity can be overridden per ``run`` call."""
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient[OpenAIChatOptions](model="gpt-5"),
|
||||
name="Explainer-default",
|
||||
instructions="You are a friendly science explainer.",
|
||||
default_options={"verbosity": "high"},
|
||||
)
|
||||
|
||||
print("\033[92m=== per-call override: verbosity='low' ===\033[0m")
|
||||
response = await agent.run(PROMPT, options={"verbosity": "low"})
|
||||
text = response.text or ""
|
||||
print(text)
|
||||
print(f"\n[chars: {len(text)}]\n")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("\033[92m=== OpenAI Chat Client Verbosity Example ===\033[0m\n")
|
||||
|
||||
levels: tuple[Verbosity, ...] = ("low", "medium", "high")
|
||||
for level in levels:
|
||||
await run_with_verbosity(level)
|
||||
|
||||
await run_per_call_override()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,73 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Awaitable, Callable
|
||||
|
||||
from agent_framework import Agent, FunctionInvocationContext
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client Agent-as-Tool Example
|
||||
|
||||
Demonstrates hierarchical agent architectures where one agent delegates
|
||||
work to specialized sub-agents wrapped as tools using as_tool().
|
||||
|
||||
This pattern is useful when you want a coordinator agent to orchestrate
|
||||
multiple specialized agents, each focusing on specific tasks.
|
||||
"""
|
||||
|
||||
|
||||
async def logging_middleware(
|
||||
context: FunctionInvocationContext,
|
||||
call_next: Callable[[], Awaitable[None]],
|
||||
) -> None:
|
||||
"""MiddlewareTypes that logs tool invocations to show the delegation flow."""
|
||||
print(f"[Calling tool: {context.function.name}]")
|
||||
print(f"[Request: {context.arguments}]")
|
||||
|
||||
await call_next()
|
||||
|
||||
print(f"[Response: {context.result}]")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Chat Client Agent-as-Tool Pattern ===")
|
||||
|
||||
client = OpenAIChatClient()
|
||||
|
||||
# Create a specialized writer agent
|
||||
writer = Agent(
|
||||
client=client,
|
||||
name="WriterAgent",
|
||||
instructions="You are a creative writer. Write short, engaging content.",
|
||||
)
|
||||
|
||||
# Convert writer agent to a tool using as_tool()
|
||||
writer_tool = writer.as_tool(
|
||||
name="creative_writer",
|
||||
description="Generate creative content like taglines, slogans, or short copy",
|
||||
arg_name="request",
|
||||
arg_description="What to write",
|
||||
)
|
||||
|
||||
# Create coordinator agent with writer as a tool
|
||||
coordinator = Agent(
|
||||
client=client,
|
||||
name="CoordinatorAgent",
|
||||
instructions="You coordinate with specialized agents. Delegate writing tasks to the creative_writer tool.",
|
||||
tools=[writer_tool],
|
||||
middleware=[logging_middleware],
|
||||
)
|
||||
|
||||
query = "Create a tagline for a coffee shop"
|
||||
print(f"User: {query}")
|
||||
result = await coordinator.run(query)
|
||||
print(f"Coordinator: {result}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,57 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
|
||||
from agent_framework import (
|
||||
Agent,
|
||||
Content,
|
||||
)
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client with Code Interpreter Example
|
||||
|
||||
This sample demonstrates using get_code_interpreter_tool() with OpenAI Chat Client
|
||||
for Python code execution and mathematical problem solving.
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Example showing how to use the code interpreter tool with OpenAI Chat."""
|
||||
print("=== OpenAI Chat Client Agent with Code Interpreter Example ===")
|
||||
|
||||
client = OpenAIChatClient()
|
||||
agent = Agent(
|
||||
client=client,
|
||||
instructions="You are a helpful assistant that can write and execute Python code to solve problems.",
|
||||
tools=client.get_code_interpreter_tool(),
|
||||
)
|
||||
|
||||
query = "Use code to get the factorial of 100?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Result: {result}\n")
|
||||
|
||||
for message in result.messages:
|
||||
code_blocks = [c for c in message.contents if c.type == "code_interpreter_tool_call"]
|
||||
outputs = [c for c in message.contents if c.type == "code_interpreter_tool_result"]
|
||||
|
||||
if code_blocks:
|
||||
code_inputs = code_blocks[0].inputs or []
|
||||
for content in code_inputs:
|
||||
if isinstance(content, Content) and content.type == "text":
|
||||
print(f"Generated code:\n{content.text}")
|
||||
break
|
||||
if outputs:
|
||||
print("Execution outputs:")
|
||||
for out in outputs[0].outputs or []:
|
||||
if isinstance(out, Content) and out.type == "text":
|
||||
print(out.text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,90 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
from openai import AsyncOpenAI
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client with Code Interpreter and Files Example
|
||||
|
||||
This sample demonstrates using get_code_interpreter_tool() with OpenAI Chat Client
|
||||
for Python code execution and data analysis with uploaded files.
|
||||
"""
|
||||
|
||||
# Helper functions
|
||||
|
||||
|
||||
async def create_sample_file_and_upload(openai_client: AsyncOpenAI) -> tuple[str, str]:
|
||||
"""Create a sample CSV file and upload it to OpenAI."""
|
||||
csv_data = """name,department,salary,years_experience
|
||||
Alice Johnson,Engineering,95000,5
|
||||
Bob Smith,Sales,75000,3
|
||||
Carol Williams,Engineering,105000,8
|
||||
David Brown,Marketing,68000,2
|
||||
Emma Davis,Sales,82000,4
|
||||
Frank Wilson,Engineering,88000,6
|
||||
"""
|
||||
|
||||
# Create temporary CSV file
|
||||
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as temp_file:
|
||||
temp_file.write(csv_data)
|
||||
temp_file_path = temp_file.name
|
||||
|
||||
# Upload file to OpenAI
|
||||
print("Uploading file to OpenAI...")
|
||||
with open(temp_file_path, "rb") as file:
|
||||
uploaded_file = await openai_client.files.create(
|
||||
file=file,
|
||||
purpose="assistants", # Required for code interpreter
|
||||
)
|
||||
|
||||
print(f"File uploaded with ID: {uploaded_file.id}")
|
||||
return temp_file_path, uploaded_file.id
|
||||
|
||||
|
||||
async def cleanup_files(openai_client: AsyncOpenAI, temp_file_path: str, file_id: str) -> None:
|
||||
"""Clean up both local temporary file and uploaded file."""
|
||||
# Clean up: delete the uploaded file
|
||||
await openai_client.files.delete(file_id)
|
||||
print(f"Cleaned up uploaded file: {file_id}")
|
||||
|
||||
# Clean up temporary local file
|
||||
os.unlink(temp_file_path)
|
||||
print(f"Cleaned up temporary file: {temp_file_path}")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Complete example of uploading a file to OpenAI and using it with code interpreter."""
|
||||
print("=== OpenAI Code Interpreter with File Upload ===")
|
||||
|
||||
openai_client = AsyncOpenAI()
|
||||
|
||||
temp_file_path, file_id = await create_sample_file_and_upload(openai_client)
|
||||
|
||||
# Create agent using OpenAI Chat client
|
||||
client = OpenAIChatClient()
|
||||
agent = Agent(
|
||||
client=client,
|
||||
instructions="You are a helpful assistant that can analyze data files using Python code.",
|
||||
tools=client.get_code_interpreter_tool(file_ids=[file_id]),
|
||||
)
|
||||
|
||||
# Test the code interpreter with the uploaded file
|
||||
query = "Analyze the employee data in the uploaded CSV file. Calculate average salary by department."
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result.text}")
|
||||
|
||||
await cleanup_files(openai_client, temp_file_path, file_id)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,55 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client with Explicit Settings Example
|
||||
|
||||
This sample demonstrates creating OpenAI Chat Client with explicit configuration
|
||||
settings rather than relying on environment variable defaults.
|
||||
"""
|
||||
|
||||
|
||||
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
|
||||
# see samples/02-agents/tools/function_tool_with_approval.py
|
||||
# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py.
|
||||
@tool(approval_mode="never_require")
|
||||
def get_weather(
|
||||
location: Annotated[str, Field(description="The location to get the weather for.")],
|
||||
) -> str:
|
||||
"""Get the weather for a given location."""
|
||||
conditions = ["sunny", "cloudy", "rainy", "stormy"]
|
||||
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Chat Client with Explicit Settings ===")
|
||||
|
||||
_client = OpenAIChatClient(
|
||||
model=os.environ["OPENAI_MODEL"],
|
||||
api_key=os.environ["OPENAI_API_KEY"],
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
client=_client,
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
result = await agent.run("What's the weather like in New York?")
|
||||
print(f"Result: {result}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,72 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client with File Search Example
|
||||
|
||||
This sample demonstrates using get_file_search_tool() with OpenAI Chat Client
|
||||
for direct document-based question answering and information retrieval.
|
||||
"""
|
||||
|
||||
# Helper functions
|
||||
|
||||
|
||||
async def create_vector_store(client: OpenAIChatClient) -> tuple[str, str]:
|
||||
"""Create a vector store with sample documents."""
|
||||
file = await client.client.files.create(
|
||||
file=("todays_weather.txt", b"The weather today is sunny with a high of 75F."), purpose="user_data"
|
||||
)
|
||||
vector_store = await client.client.vector_stores.create(
|
||||
name="knowledge_base",
|
||||
expires_after={"anchor": "last_active_at", "days": 1},
|
||||
)
|
||||
result = await client.client.vector_stores.files.create_and_poll(vector_store_id=vector_store.id, file_id=file.id)
|
||||
if result.last_error is not None:
|
||||
raise Exception(f"Vector store file processing failed with status: {result.last_error.message}")
|
||||
|
||||
return file.id, vector_store.id
|
||||
|
||||
|
||||
async def delete_vector_store(client: OpenAIChatClient, file_id: str, vector_store_id: str) -> None:
|
||||
"""Delete the vector store after using it."""
|
||||
await client.client.vector_stores.delete(vector_store_id=vector_store_id)
|
||||
await client.client.files.delete(file_id=file_id)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
client = OpenAIChatClient()
|
||||
|
||||
message = "What is the weather today? Do a file search to find the answer."
|
||||
|
||||
stream = False
|
||||
print(f"User: {message}")
|
||||
file_id, vector_store_id = await create_vector_store(client)
|
||||
|
||||
agent = Agent(
|
||||
client=client,
|
||||
instructions="You are a helpful assistant that can search through files to find information.",
|
||||
tools=[client.get_file_search_tool(vector_store_ids=[vector_store_id])],
|
||||
)
|
||||
|
||||
if stream:
|
||||
print("Agent: ", end="")
|
||||
async for chunk in agent.run(message, stream=True):
|
||||
if chunk.text:
|
||||
print(chunk.text, end="")
|
||||
print("")
|
||||
else:
|
||||
response = await agent.run(message)
|
||||
print(f"Agent: {response}")
|
||||
await delete_vector_store(client, file_id, vector_store_id)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,136 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client with Function Tools Example
|
||||
|
||||
This sample demonstrates function tool integration with OpenAI Chat Client,
|
||||
showing both agent-level and query-level tool configuration patterns.
|
||||
"""
|
||||
|
||||
|
||||
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
|
||||
# see samples/02-agents/tools/function_tool_with_approval.py
|
||||
# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py.
|
||||
@tool(approval_mode="never_require")
|
||||
def get_weather(
|
||||
location: Annotated[str, Field(description="The location to get the weather for.")],
|
||||
) -> str:
|
||||
"""Get the weather for a given location."""
|
||||
conditions = ["sunny", "cloudy", "rainy", "stormy"]
|
||||
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
|
||||
|
||||
|
||||
@tool(approval_mode="never_require")
|
||||
def get_time() -> str:
|
||||
"""Get the current UTC time."""
|
||||
current_time = datetime.now(timezone.utc)
|
||||
return f"The current UTC time is {current_time.strftime('%Y-%m-%d %H:%M:%S')}."
|
||||
|
||||
|
||||
async def tools_on_agent_level() -> None:
|
||||
"""Example showing tools defined when creating the agent."""
|
||||
print("=== Tools Defined on Agent Level ===")
|
||||
|
||||
# Tools are provided when creating the agent
|
||||
# The agent can use these tools for any query during its lifetime
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
instructions="You are a helpful assistant that can provide weather and time information.",
|
||||
tools=[get_weather, get_time], # Tools defined at agent creation
|
||||
)
|
||||
|
||||
# First query - agent can use weather tool
|
||||
query1 = "What's the weather like in New York?"
|
||||
print(f"User: {query1}")
|
||||
result1 = await agent.run(query1)
|
||||
print(f"Agent: {result1}\n")
|
||||
|
||||
# Second query - agent can use time tool
|
||||
query2 = "What's the current UTC time?"
|
||||
print(f"User: {query2}")
|
||||
result2 = await agent.run(query2)
|
||||
print(f"Agent: {result2}\n")
|
||||
|
||||
# Third query - agent can use both tools if needed
|
||||
query3 = "What's the weather in London and what's the current UTC time?"
|
||||
print(f"User: {query3}")
|
||||
result3 = await agent.run(query3)
|
||||
print(f"Agent: {result3}\n")
|
||||
|
||||
|
||||
async def tools_on_run_level() -> None:
|
||||
"""Example showing tools passed to the run method."""
|
||||
print("=== Tools Passed to Run Method ===")
|
||||
|
||||
# Agent created without tools
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
instructions="You are a helpful assistant.",
|
||||
# No tools defined here
|
||||
)
|
||||
|
||||
# First query with weather tool
|
||||
query1 = "What's the weather like in Seattle?"
|
||||
print(f"User: {query1}")
|
||||
result1 = await agent.run(query1, tools=[get_weather]) # Tool passed to run method
|
||||
print(f"Agent: {result1}\n")
|
||||
|
||||
# Second query with time tool
|
||||
query2 = "What's the current UTC time?"
|
||||
print(f"User: {query2}")
|
||||
result2 = await agent.run(query2, tools=[get_time]) # Different tool for this query
|
||||
print(f"Agent: {result2}\n")
|
||||
|
||||
# Third query with multiple tools
|
||||
query3 = "What's the weather in Chicago and what's the current UTC time?"
|
||||
print(f"User: {query3}")
|
||||
result3 = await agent.run(query3, tools=[get_weather, get_time]) # Multiple tools
|
||||
print(f"Agent: {result3}\n")
|
||||
|
||||
|
||||
async def mixed_tools_example() -> None:
|
||||
"""Example showing both agent-level tools and run-method tools."""
|
||||
print("=== Mixed Tools Example (Agent + Run Method) ===")
|
||||
|
||||
# Agent created with some base tools
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
instructions="You are a comprehensive assistant that can help with various information requests.",
|
||||
tools=[get_weather], # Base tool available for all queries
|
||||
)
|
||||
|
||||
# Query using both agent tool and additional run-method tools
|
||||
query = "What's the weather in Denver and what's the current UTC time?"
|
||||
print(f"User: {query}")
|
||||
|
||||
# Agent has access to get_weather (from creation) + additional tools from run method
|
||||
result = await agent.run(
|
||||
query,
|
||||
tools=[get_time], # Additional tools for this specific query
|
||||
)
|
||||
print(f"Agent: {result}\n")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Chat Client Agent with Function Tools Examples ===\n")
|
||||
|
||||
await tools_on_agent_level()
|
||||
await tools_on_run_level()
|
||||
await mixed_tools_example()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,252 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from agent_framework import AgentSession
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client with Hosted MCP Example
|
||||
|
||||
This sample demonstrates integrating hosted Model Context Protocol (MCP) tools with
|
||||
OpenAI Chat Client, including user approval workflows for function call security.
|
||||
"""
|
||||
|
||||
|
||||
async def handle_approvals_without_session(query: str, agent: Agent[Any]):
|
||||
"""When we don't have a session, we need to ensure we return with the input, approval request and approval."""
|
||||
from agent_framework import Message
|
||||
|
||||
result = await agent.run(query)
|
||||
while len(result.user_input_requests) > 0:
|
||||
new_inputs: list[Any] = [query]
|
||||
for user_input_needed in result.user_input_requests:
|
||||
if user_input_needed.function_call is None:
|
||||
continue
|
||||
print(
|
||||
f"User Input Request for function from {agent.name}: {user_input_needed.function_call.name}"
|
||||
f" with arguments: {user_input_needed.function_call.arguments}"
|
||||
)
|
||||
new_inputs.append(Message(role="assistant", contents=[user_input_needed]))
|
||||
user_approval = input("Approve function call? (y/n): ")
|
||||
new_inputs.append(
|
||||
Message(
|
||||
role="user",
|
||||
contents=[user_input_needed.to_function_approval_response(user_approval.lower() == "y")],
|
||||
)
|
||||
)
|
||||
|
||||
result = await agent.run(new_inputs)
|
||||
return result
|
||||
|
||||
|
||||
async def handle_approvals_with_session(query: str, agent: Agent[Any], session: "AgentSession"):
|
||||
"""Here we let the session deal with the previous responses, and we just rerun with the approval."""
|
||||
from agent_framework import ChatOptions, Message
|
||||
|
||||
result = await agent.run(query, session=session, options=ChatOptions(store=True))
|
||||
while len(result.user_input_requests) > 0:
|
||||
new_input: list[Any] = []
|
||||
for user_input_needed in result.user_input_requests:
|
||||
if user_input_needed.function_call is None:
|
||||
continue
|
||||
print(
|
||||
f"User Input Request for function from {agent.name}: {user_input_needed.function_call.name}"
|
||||
f" with arguments: {user_input_needed.function_call.arguments}"
|
||||
)
|
||||
user_approval = input("Approve function call? (y/n): ")
|
||||
new_input.append(
|
||||
Message(
|
||||
role="user",
|
||||
contents=[user_input_needed.to_function_approval_response(user_approval.lower() == "y")],
|
||||
)
|
||||
)
|
||||
result = await agent.run(new_input, session=session, options=ChatOptions(store=True))
|
||||
return result
|
||||
|
||||
|
||||
async def handle_approvals_with_session_streaming(query: str, agent: Agent[Any], session: "AgentSession"):
|
||||
"""Here we let the session deal with the previous responses, and we just rerun with the approval."""
|
||||
from agent_framework import ChatOptions, Message
|
||||
|
||||
new_input: list[Message | str] = [query]
|
||||
new_input_added = True
|
||||
while new_input_added:
|
||||
new_input_added = False
|
||||
async for update in agent.run(new_input, session=session, stream=True, options=ChatOptions(store=True)):
|
||||
if update.user_input_requests:
|
||||
# Reset input to only contain new approval responses for the next iteration
|
||||
new_input = []
|
||||
for user_input_needed in update.user_input_requests:
|
||||
if user_input_needed.function_call is None:
|
||||
continue
|
||||
print(
|
||||
f"User Input Request for function from {agent.name}: {user_input_needed.function_call.name}"
|
||||
f" with arguments: {user_input_needed.function_call.arguments}"
|
||||
)
|
||||
user_approval = input("Approve function call? (y/n): ")
|
||||
new_input.append(
|
||||
Message(
|
||||
role="user",
|
||||
contents=[user_input_needed.to_function_approval_response(user_approval.lower() == "y")],
|
||||
)
|
||||
)
|
||||
new_input_added = True
|
||||
else:
|
||||
yield update
|
||||
|
||||
|
||||
async def run_hosted_mcp_without_session_and_specific_approval() -> None:
|
||||
"""Example showing Mcp Tools with approvals without using a session."""
|
||||
print("=== Mcp with approvals and without session ===")
|
||||
|
||||
client = OpenAIChatClient()
|
||||
# Create MCP tool with specific approval mode
|
||||
mcp_tool = client.get_mcp_tool(
|
||||
name="Microsoft Learn MCP",
|
||||
url="https://learn.microsoft.com/api/mcp",
|
||||
# we don't require approval for microsoft_docs_search tool calls
|
||||
# but we do for any other tool
|
||||
approval_mode={"never_require_approval": ["microsoft_docs_search"]},
|
||||
)
|
||||
|
||||
async with Agent(
|
||||
client=client,
|
||||
name="DocsAgent",
|
||||
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
|
||||
tools=mcp_tool,
|
||||
) as agent:
|
||||
# First query
|
||||
query1 = "How to create an Azure storage account using az cli?"
|
||||
print(f"User: {query1}")
|
||||
result1 = await handle_approvals_without_session(query1, agent)
|
||||
print(f"{agent.name}: {result1}\n")
|
||||
print("\n=======================================\n")
|
||||
# Second query
|
||||
query2 = "What is Microsoft Agent Framework?"
|
||||
print(f"User: {query2}")
|
||||
result2 = await handle_approvals_without_session(query2, agent)
|
||||
print(f"{agent.name}: {result2}\n")
|
||||
|
||||
|
||||
async def run_hosted_mcp_without_approval() -> None:
|
||||
"""Example showing Mcp Tools without approvals."""
|
||||
print("=== Mcp without approvals ===")
|
||||
|
||||
client = OpenAIChatClient()
|
||||
# Create MCP tool that never requires approval
|
||||
mcp_tool = client.get_mcp_tool(
|
||||
name="Microsoft Learn MCP",
|
||||
url="https://learn.microsoft.com/api/mcp",
|
||||
# we don't require approval for any function calls
|
||||
approval_mode="never_require",
|
||||
)
|
||||
|
||||
async with Agent(
|
||||
client=client,
|
||||
name="DocsAgent",
|
||||
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
|
||||
tools=mcp_tool,
|
||||
) as agent:
|
||||
# First query
|
||||
query1 = "How to create an Azure storage account using az cli?"
|
||||
print(f"User: {query1}")
|
||||
result1 = await handle_approvals_without_session(query1, agent)
|
||||
print(f"{agent.name}: {result1}\n")
|
||||
print("\n=======================================\n")
|
||||
# Second query
|
||||
query2 = "What is Microsoft Agent Framework?"
|
||||
print(f"User: {query2}")
|
||||
result2 = await handle_approvals_without_session(query2, agent)
|
||||
print(f"{agent.name}: {result2}\n")
|
||||
|
||||
|
||||
async def run_hosted_mcp_with_session() -> None:
|
||||
"""Example showing Mcp Tools with approvals using a session."""
|
||||
print("=== Mcp with approvals and with session ===")
|
||||
|
||||
client = OpenAIChatClient()
|
||||
# Create MCP tool that always requires approval
|
||||
mcp_tool = client.get_mcp_tool(
|
||||
name="Microsoft Learn MCP",
|
||||
url="https://learn.microsoft.com/api/mcp",
|
||||
# we require approval for all function calls
|
||||
approval_mode="always_require",
|
||||
)
|
||||
|
||||
async with Agent(
|
||||
client=client,
|
||||
name="DocsAgent",
|
||||
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
|
||||
tools=mcp_tool,
|
||||
) as agent:
|
||||
# First query
|
||||
session = agent.create_session()
|
||||
query1 = "How to create an Azure storage account using az cli?"
|
||||
print(f"User: {query1}")
|
||||
result1 = await handle_approvals_with_session(query1, agent, session)
|
||||
print(f"{agent.name}: {result1}\n")
|
||||
print("\n=======================================\n")
|
||||
# Second query
|
||||
query2 = "What is Microsoft Agent Framework?"
|
||||
print(f"User: {query2}")
|
||||
result2 = await handle_approvals_with_session(query2, agent, session)
|
||||
print(f"{agent.name}: {result2}\n")
|
||||
|
||||
|
||||
async def run_hosted_mcp_with_session_streaming() -> None:
|
||||
"""Example showing Mcp Tools with approvals using a session."""
|
||||
print("=== Mcp with approvals and with session ===")
|
||||
|
||||
client = OpenAIChatClient()
|
||||
# Create MCP tool that always requires approval
|
||||
mcp_tool = client.get_mcp_tool(
|
||||
name="Microsoft Learn MCP",
|
||||
url="https://learn.microsoft.com/api/mcp",
|
||||
# we require approval for all function calls
|
||||
approval_mode="always_require",
|
||||
)
|
||||
|
||||
async with Agent(
|
||||
client=client,
|
||||
name="DocsAgent",
|
||||
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
|
||||
tools=mcp_tool,
|
||||
) as agent:
|
||||
# First query
|
||||
session = agent.create_session()
|
||||
query1 = "How to create an Azure storage account using az cli?"
|
||||
print(f"User: {query1}")
|
||||
print(f"{agent.name}: ", end="")
|
||||
async for update in handle_approvals_with_session_streaming(query1, agent, session):
|
||||
print(update, end="")
|
||||
print("\n")
|
||||
print("\n=======================================\n")
|
||||
# Second query
|
||||
query2 = "What is Microsoft Agent Framework?"
|
||||
print(f"User: {query2}")
|
||||
print(f"{agent.name}: ", end="")
|
||||
async for update in handle_approvals_with_session_streaming(query2, agent, session):
|
||||
print(update, end="")
|
||||
print("\n")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Chat Client Agent with Hosted Mcp Tools Examples ===\n")
|
||||
|
||||
await run_hosted_mcp_without_approval()
|
||||
await run_hosted_mcp_without_session_and_specific_approval()
|
||||
await run_hosted_mcp_with_session()
|
||||
await run_hosted_mcp_with_session_streaming()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,97 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Agent, MCPStreamableHTTPTool
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client with Local MCP Example
|
||||
|
||||
This sample demonstrates integrating local Model Context Protocol (MCP) tools with
|
||||
OpenAI Chat Client for direct response generation with external capabilities.
|
||||
"""
|
||||
|
||||
|
||||
async def streaming_with_mcp(show_raw_stream: bool = False) -> None:
|
||||
"""Example showing tools defined when creating the agent.
|
||||
|
||||
If you want to access the full stream of events that has come from the model, you can access it,
|
||||
through the raw_representation. You can view this, by setting the show_raw_stream parameter to True.
|
||||
"""
|
||||
print("=== Tools Defined on Agent Level ===")
|
||||
# Tools are provided when creating the agent
|
||||
# The agent can use these tools for any query during its lifetime
|
||||
async with Agent(
|
||||
client=OpenAIChatClient(),
|
||||
name="DocsAgent",
|
||||
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
|
||||
tools=MCPStreamableHTTPTool( # Tools defined at agent creation
|
||||
name="Microsoft Learn MCP",
|
||||
url="https://learn.microsoft.com/api/mcp",
|
||||
),
|
||||
) as agent:
|
||||
# First query
|
||||
query1 = "How to create an Azure storage account using az cli?"
|
||||
print(f"User: {query1}")
|
||||
print(f"{agent.name}: ", end="")
|
||||
async for chunk in agent.run(query1, stream=True):
|
||||
if show_raw_stream:
|
||||
print("Streamed event: ", chunk.raw_representation.raw_representation) # type:ignore
|
||||
elif chunk.text:
|
||||
print(chunk.text, end="")
|
||||
print("")
|
||||
print("\n=======================================\n")
|
||||
# Second query
|
||||
query2 = "What is Microsoft Agent Framework?"
|
||||
print(f"User: {query2}")
|
||||
print(f"{agent.name}: ", end="")
|
||||
async for chunk in agent.run(query2, stream=True):
|
||||
if show_raw_stream:
|
||||
print("Streamed event: ", chunk.raw_representation.raw_representation) # type:ignore
|
||||
elif chunk.text:
|
||||
print(chunk.text, end="")
|
||||
print("\n\n")
|
||||
|
||||
|
||||
async def run_with_mcp() -> None:
|
||||
"""Example showing tools defined when creating the agent."""
|
||||
print("=== Tools Defined on Agent Level ===")
|
||||
|
||||
# Tools are provided when creating the agent
|
||||
# The agent can use these tools for any query during its lifetime
|
||||
async with Agent(
|
||||
client=OpenAIChatClient(),
|
||||
name="DocsAgent",
|
||||
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
|
||||
tools=MCPStreamableHTTPTool( # Tools defined at agent creation
|
||||
name="Microsoft Learn MCP",
|
||||
url="https://learn.microsoft.com/api/mcp",
|
||||
),
|
||||
) as agent:
|
||||
# First query
|
||||
query1 = "How to create an Azure storage account using az cli?"
|
||||
print(f"User: {query1}")
|
||||
result1 = await agent.run(query1)
|
||||
print(f"{agent.name}: {result1}\n")
|
||||
print("\n=======================================\n")
|
||||
# Second query
|
||||
query2 = "What is Microsoft Agent Framework?"
|
||||
print(f"User: {query2}")
|
||||
result2 = await agent.run(query2)
|
||||
print(f"{agent.name}: {result2}\n")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Chat Client Agent with Function Tools Examples ===\n")
|
||||
|
||||
await run_with_mcp()
|
||||
await streaming_with_mcp()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,97 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
from typing import Any
|
||||
|
||||
from agent_framework import Agent, Message
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from agent_framework_tools.shell import LocalShellTool
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client with Local Shell Tool Example
|
||||
|
||||
This sample uses ``LocalShellTool`` from ``agent-framework-tools`` — the
|
||||
framework-supplied cross-OS shell executor with safe defaults (approval
|
||||
required, timeout, output truncation, workdir confinement). Operators
|
||||
can additionally supply a ``ShellPolicy`` with allow/deny patterns as a
|
||||
UX pre-filter; the tool ships with no default deny patterns.
|
||||
|
||||
Currently not all models support the shell tool. Refer to the OpenAI
|
||||
documentation for the list of supported models:
|
||||
https://developers.openai.com/api/docs/models/
|
||||
|
||||
SECURITY NOTE: This example executes real commands on your local machine.
|
||||
``LocalShellTool`` requires approval by default; only accept commands you
|
||||
understand.
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Agent with LocalShellTool Example ===")
|
||||
print("NOTE: Commands will execute on your local machine.\n")
|
||||
|
||||
client = OpenAIChatClient(model="gpt-5.4-nano")
|
||||
|
||||
async with LocalShellTool() as shell:
|
||||
agent = Agent(
|
||||
client=client,
|
||||
instructions="You are a helpful assistant that can run shell commands to help the user.",
|
||||
tools=[client.get_shell_tool(func=shell.as_function())],
|
||||
)
|
||||
|
||||
query = "Use the shell tool to execute `python --version` and show only the command output."
|
||||
print(f"User: {query}")
|
||||
result = await run_with_approvals(query, agent)
|
||||
if isinstance(result, str):
|
||||
print(f"Agent: {result}\n")
|
||||
return
|
||||
if result.text:
|
||||
print(f"Agent: {result.text}\n")
|
||||
else:
|
||||
printed = False
|
||||
for message in result.messages:
|
||||
for content in message.contents:
|
||||
if content.type == "function_result" and content.result:
|
||||
print(f"Agent (tool output): {content.result}\n")
|
||||
printed = True
|
||||
if not printed:
|
||||
print("Agent: (no text output returned)\n")
|
||||
|
||||
|
||||
async def run_with_approvals(query: str, agent: Agent) -> Any:
|
||||
"""Run the agent and handle shell approvals outside tool execution."""
|
||||
current_input: str | list[Any] = query
|
||||
|
||||
while True:
|
||||
result = await agent.run(current_input)
|
||||
if not result.user_input_requests:
|
||||
return result
|
||||
|
||||
next_input: list[Any] = [query]
|
||||
rejected = False
|
||||
for user_input_needed in result.user_input_requests:
|
||||
if user_input_needed.function_call is None:
|
||||
continue
|
||||
print(
|
||||
f"\nShell request: {user_input_needed.function_call.name}"
|
||||
f"\nArguments: {user_input_needed.function_call.arguments}"
|
||||
)
|
||||
user_approval = await asyncio.to_thread(input, "\nApprove shell command? (y/n): ")
|
||||
approved = user_approval.strip().lower() == "y"
|
||||
next_input.append(Message("assistant", [user_input_needed]))
|
||||
next_input.append(Message("user", [user_input_needed.to_function_approval_response(approved)]))
|
||||
if not approved:
|
||||
rejected = True
|
||||
break
|
||||
if rejected:
|
||||
print("\nShell command rejected. Stopping without additional approval prompts.")
|
||||
return "Shell command execution was rejected by user."
|
||||
current_input = next_input
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,118 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client Runtime JSON Schema Example
|
||||
|
||||
Demonstrates structured outputs when the schema is only known at runtime.
|
||||
Uses additional_chat_options to pass a JSON Schema payload directly to OpenAI
|
||||
without defining a Pydantic model up front.
|
||||
"""
|
||||
|
||||
|
||||
runtime_schema = {
|
||||
"title": "WeatherDigest",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"location": {"type": "string"},
|
||||
"conditions": {"type": "string"},
|
||||
"temperature_c": {"type": "number"},
|
||||
"advisory": {"type": "string"},
|
||||
},
|
||||
# OpenAI strict mode requires every property to appear in required.
|
||||
"required": ["location", "conditions", "temperature_c", "advisory"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
|
||||
async def non_streaming_example() -> None:
|
||||
print("=== Non-streaming runtime JSON schema example ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
name="RuntimeSchemaAgent",
|
||||
instructions="Return only JSON that matches the provided schema. Do not add commentary.",
|
||||
)
|
||||
|
||||
query = "Give a brief weather digest for Seattle."
|
||||
print(f"User: {query}")
|
||||
|
||||
response = await agent.run(
|
||||
query,
|
||||
options={
|
||||
"response_format": {
|
||||
"type": "json_schema",
|
||||
"json_schema": {
|
||||
"name": runtime_schema["title"],
|
||||
"strict": True,
|
||||
"schema": runtime_schema,
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
print("Model output:")
|
||||
print(response.text)
|
||||
|
||||
parsed = json.loads(response.text)
|
||||
print("Parsed dict:")
|
||||
print(parsed)
|
||||
|
||||
|
||||
async def streaming_example() -> None:
|
||||
print("=== Streaming runtime JSON schema example ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
name="RuntimeSchemaAgent",
|
||||
instructions="Return only JSON that matches the provided schema. Do not add commentary.",
|
||||
)
|
||||
|
||||
query = "Give a brief weather digest for Portland."
|
||||
print(f"User: {query}")
|
||||
|
||||
chunks: list[str] = []
|
||||
async for chunk in agent.run(
|
||||
query,
|
||||
stream=True,
|
||||
options={
|
||||
"response_format": {
|
||||
"type": "json_schema",
|
||||
"json_schema": {
|
||||
"name": runtime_schema["title"],
|
||||
"strict": True,
|
||||
"schema": runtime_schema,
|
||||
},
|
||||
},
|
||||
},
|
||||
):
|
||||
if chunk.text:
|
||||
chunks.append(chunk.text)
|
||||
|
||||
raw_text = "".join(chunks)
|
||||
print("Model output:")
|
||||
print(raw_text)
|
||||
|
||||
parsed = json.loads(raw_text)
|
||||
print("Parsed dict:")
|
||||
print(parsed)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Chat Client with runtime JSON Schema ===")
|
||||
|
||||
await non_streaming_example()
|
||||
await streaming_example()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,154 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import Agent, AgentSession, tool
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client with Session Management Example
|
||||
|
||||
This sample demonstrates session management with OpenAI Chat Client, showing
|
||||
persistent conversation context and simplified response handling.
|
||||
"""
|
||||
|
||||
|
||||
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
|
||||
# see samples/02-agents/tools/function_tool_with_approval.py
|
||||
# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py.
|
||||
@tool(approval_mode="never_require")
|
||||
def get_weather(
|
||||
location: Annotated[str, Field(description="The location to get the weather for.")],
|
||||
) -> str:
|
||||
"""Get the weather for a given location."""
|
||||
conditions = ["sunny", "cloudy", "rainy", "stormy"]
|
||||
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
|
||||
|
||||
|
||||
async def example_with_automatic_session_creation() -> None:
|
||||
"""Example showing automatic session creation."""
|
||||
print("=== Automatic Session Creation Example ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
# First conversation - no session provided, will be created automatically
|
||||
query1 = "What's the weather like in Seattle?"
|
||||
print(f"User: {query1}")
|
||||
result1 = await agent.run(query1)
|
||||
print(f"Agent: {result1.text}")
|
||||
|
||||
# Second conversation - still no session provided, will create another new session
|
||||
query2 = "What was the last city I asked about?"
|
||||
print(f"\nUser: {query2}")
|
||||
result2 = await agent.run(query2)
|
||||
print(f"Agent: {result2.text}")
|
||||
print("Note: Each call creates a separate session, so the agent doesn't remember previous context.\n")
|
||||
|
||||
|
||||
async def example_with_session_persistence_in_memory() -> None:
|
||||
"""
|
||||
Example showing session persistence across multiple conversations.
|
||||
In this example, messages are stored in-memory.
|
||||
"""
|
||||
print("=== Session Persistence Example (In-Memory) ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
# Create a new session that will be reused
|
||||
session = agent.create_session()
|
||||
|
||||
# First conversation
|
||||
query1 = "What's the weather like in Tokyo?"
|
||||
print(f"User: {query1}")
|
||||
result1 = await agent.run(query1, session=session, options={"store": False})
|
||||
print(f"Agent: {result1.text}")
|
||||
|
||||
# Second conversation using the same session - maintains context
|
||||
query2 = "How about London?"
|
||||
print(f"\nUser: {query2}")
|
||||
result2 = await agent.run(query2, session=session, options={"store": False})
|
||||
print(f"Agent: {result2.text}")
|
||||
|
||||
# Third conversation - agent should remember both previous cities
|
||||
query3 = "Which of the cities I asked about has better weather?"
|
||||
print(f"\nUser: {query3}")
|
||||
result3 = await agent.run(query3, session=session, options={"store": False})
|
||||
print(f"Agent: {result3.text}")
|
||||
print("Note: The agent remembers context from previous messages in the same session.\n")
|
||||
|
||||
|
||||
async def example_with_existing_session_id() -> None:
|
||||
"""
|
||||
Example showing how to work with an existing session ID from the service.
|
||||
In this example, messages are stored on the server using OpenAI conversation state.
|
||||
"""
|
||||
print("=== Existing Session ID Example ===")
|
||||
|
||||
# First, create a conversation and capture the session ID
|
||||
existing_session_id = None
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
# Start a conversation and get the session ID
|
||||
session = agent.create_session()
|
||||
|
||||
query1 = "What's the weather in Paris?"
|
||||
print(f"User: {query1}")
|
||||
result1 = await agent.run(query1, session=session)
|
||||
print(f"Agent: {result1.text}")
|
||||
|
||||
# The session ID is set after the first response
|
||||
existing_session_id = session.service_session_id
|
||||
print(f"Session ID: {existing_session_id}")
|
||||
|
||||
if existing_session_id:
|
||||
print("\n--- Continuing with the same session ID in a new agent instance ---")
|
||||
|
||||
# In a hosted multi-user app, do not echo this service session ID to clients
|
||||
# and accept it back unscoped. OpenAI scopes it to the API key/project, so
|
||||
# store it server-side and verify it belongs to the authenticated user or tenant.
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
# Create a session with the existing ID
|
||||
session = AgentSession(service_session_id=existing_session_id)
|
||||
|
||||
query2 = "What was the last city I asked about?"
|
||||
print(f"User: {query2}")
|
||||
result2 = await agent.run(query2, session=session)
|
||||
print(f"Agent: {result2.text}")
|
||||
print("Note: The agent continues the conversation from the previous session by using session ID.\n")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Response Client Agent Session Management Examples ===\n")
|
||||
|
||||
await example_with_automatic_session_creation()
|
||||
await example_with_session_persistence_in_memory()
|
||||
await example_with_existing_session_id()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,67 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client with Shell Tool Example
|
||||
|
||||
This sample demonstrates using get_shell_tool() with OpenAI Chat Client
|
||||
for executing shell commands in a managed container environment hosted by OpenAI.
|
||||
|
||||
The shell tool allows the model to run commands like listing files, running scripts,
|
||||
or performing system operations within a secure, sandboxed container.
|
||||
|
||||
Currently not all models support the shell tool. Refer to the OpenAI documentation
|
||||
for the list of supported models: https://developers.openai.com/api/docs/models/
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Example showing how to use the shell tool with OpenAI Chat."""
|
||||
print("=== OpenAI Chat Client Agent with Shell Tool Example ===")
|
||||
|
||||
# Currently not all models support the shell tool. Refer to the OpenAI
|
||||
# documentation for the list of supported models:
|
||||
# https://developers.openai.com/api/docs/models/
|
||||
client = OpenAIChatClient(model="gpt-5.4-nano")
|
||||
|
||||
# Create a hosted shell tool with the default auto container environment
|
||||
shell_tool = client.get_shell_tool()
|
||||
|
||||
agent = Agent(
|
||||
client=client,
|
||||
instructions="You are a helpful assistant that can execute shell commands to answer questions.",
|
||||
tools=shell_tool,
|
||||
)
|
||||
|
||||
query = "Use a shell command to show the current date and time"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Result: {result}\n")
|
||||
|
||||
# Print shell-specific content details
|
||||
for message in result.messages:
|
||||
shell_calls = [c for c in message.contents if c.type == "shell_tool_call"]
|
||||
shell_results = [c for c in message.contents if c.type == "shell_tool_result"]
|
||||
|
||||
if shell_calls:
|
||||
print(f"Shell commands: {shell_calls[0].commands}")
|
||||
if shell_results and shell_results[0].outputs:
|
||||
for output in shell_results[0].outputs:
|
||||
if output.stdout:
|
||||
print(f"Stdout: {output.stdout}")
|
||||
if output.stderr:
|
||||
print(f"Stderr: {output.stderr}")
|
||||
if output.exit_code is not None:
|
||||
print(f"Exit code: {output.exit_code}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,92 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Agent, AgentResponse
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import BaseModel
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client with Structured Output Example
|
||||
|
||||
This sample demonstrates using structured output capabilities with OpenAI Chat Client,
|
||||
showing Pydantic model integration for type-safe response parsing and data extraction.
|
||||
"""
|
||||
|
||||
|
||||
class OutputStruct(BaseModel):
|
||||
"""A structured output for testing purposes."""
|
||||
|
||||
city: str
|
||||
description: str
|
||||
|
||||
|
||||
async def non_streaming_example() -> None:
|
||||
print("=== Non-streaming example ===")
|
||||
|
||||
# Create an OpenAI Chat agent
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
name="CityAgent",
|
||||
instructions="You are a helpful agent that describes cities in a structured format.",
|
||||
)
|
||||
|
||||
# Ask the agent about a city
|
||||
query = "Tell me about Paris, France"
|
||||
print(f"User: {query}")
|
||||
|
||||
# Get structured response from the agent using response_format parameter
|
||||
result = await agent.run(query, options={"response_format": OutputStruct})
|
||||
|
||||
# Access the structured output using the parsed value
|
||||
if structured_data := result.value:
|
||||
print("Structured Output Agent:")
|
||||
print(f"City: {structured_data.city}")
|
||||
print(f"Description: {structured_data.description}")
|
||||
else:
|
||||
print(f"Failed to parse response: {result.text}")
|
||||
|
||||
|
||||
async def streaming_example() -> None:
|
||||
print("=== Streaming example ===")
|
||||
|
||||
# Create an OpenAI Chat agent
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
name="CityAgent",
|
||||
instructions="You are a helpful agent that describes cities in a structured format.",
|
||||
)
|
||||
|
||||
# Ask the agent about a city
|
||||
query = "Tell me about Tokyo, Japan"
|
||||
print(f"User: {query}")
|
||||
|
||||
# Get structured response from streaming agent using AgentResponse.from_update_generator
|
||||
# This method collects all streaming updates and combines them into a single AgentResponse
|
||||
result = await AgentResponse.from_update_generator(
|
||||
agent.run(query, stream=True, options={"response_format": OutputStruct}),
|
||||
output_format_type=OutputStruct,
|
||||
)
|
||||
|
||||
# Access the structured output using the parsed value
|
||||
if structured_data := result.value:
|
||||
print("Structured Output (from streaming with AgentResponse.from_update_generator):")
|
||||
print(f"City: {structured_data.city}")
|
||||
print(f"Description: {structured_data.description}")
|
||||
else:
|
||||
print(f"Failed to parse response: {result.text}")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Chat Client Agent with Structured Output ===")
|
||||
|
||||
await non_streaming_example()
|
||||
await streaming_example()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,50 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client with Web Search Example
|
||||
|
||||
This sample demonstrates using get_web_search_tool() with OpenAI Chat Client
|
||||
for direct real-time information retrieval and current data access.
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
client = OpenAIChatClient()
|
||||
|
||||
# Create web search tool with location context
|
||||
web_search_tool = client.get_web_search_tool(
|
||||
user_location={"city": "Seattle", "country": "US"},
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
client=client,
|
||||
instructions="You are a helpful assistant that can search the web for current information.",
|
||||
tools=[web_search_tool],
|
||||
)
|
||||
|
||||
message = "What is the current weather? Do not ask for my current location."
|
||||
stream = False
|
||||
print(f"User: {message}")
|
||||
|
||||
if stream:
|
||||
print("Assistant: ", end="")
|
||||
async for chunk in agent.run(message, stream=True):
|
||||
if chunk.text:
|
||||
print(chunk.text, end="")
|
||||
print("")
|
||||
else:
|
||||
response = await agent.run(message)
|
||||
print(f"Assistant: {response}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user