mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
Merge branch 'main' into local-branch-fix-samples-and-sample-validation
This commit is contained in:
@@ -57,8 +57,8 @@ Depending on the selected client, set the appropriate environment variables:
|
||||
|
||||
**For OpenAI clients:**
|
||||
- `OPENAI_API_KEY`: Your OpenAI API key
|
||||
- `OPENAI_CHAT_MODEL_ID`: The OpenAI model for `openai_chat` and `openai_assistants`
|
||||
- `OPENAI_RESPONSES_MODEL_ID`: The OpenAI model for `openai_responses`
|
||||
- `OPENAI_CHAT_MODEL`: The OpenAI model for `openai_chat` and `openai_assistants`
|
||||
- `OPENAI_RESPONSES_MODEL`: The OpenAI model for `openai_responses`
|
||||
|
||||
**For Anthropic client (`anthropic`):**
|
||||
- `ANTHROPIC_API_KEY`: Your Anthropic API key
|
||||
|
||||
+9
-8
@@ -4,8 +4,9 @@ import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.azure import AzureAISearchContextProvider, AzureOpenAIEmbeddingClient
|
||||
from agent_framework.azure import AzureAISearchContextProvider
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from agent_framework.openai import OpenAIEmbeddingClient
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
@@ -31,8 +32,8 @@ Prerequisites:
|
||||
- AZURE_SEARCH_INDEX_NAME: Your search index name
|
||||
- FOUNDRY_PROJECT_ENDPOINT: Your Azure AI Foundry project endpoint
|
||||
- AZURE_AI_MODEL_DEPLOYMENT_NAME: Your model deployment name (e.g., "gpt-4o")
|
||||
- AZURE_OPENAI_EMBEDDING_MODEL_ID: (Optional) Your embedding model for hybrid search (e.g., "text-embedding-3-small")
|
||||
- AZURE_OPENAI_ENDPOINT: (Optional) Your Azure OpenAI resource URL, required if using an OpenAI embedding model for hybrid search
|
||||
- AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME: (Optional) Your Azure OpenAI embedding deployment for hybrid search
|
||||
- AZURE_OPENAI_ENDPOINT: (Optional) Your Azure OpenAI resource URL, required if using Azure OpenAI embeddings
|
||||
"""
|
||||
|
||||
# Sample queries to demonstrate RAG
|
||||
@@ -55,13 +56,13 @@ async def main() -> None:
|
||||
project_endpoint = os.environ["FOUNDRY_PROJECT_ENDPOINT"]
|
||||
model_deployment = os.environ.get("AZURE_AI_MODEL_DEPLOYMENT_NAME", "gpt-4o")
|
||||
openai_endpoint = os.environ.get("AZURE_OPENAI_ENDPOINT")
|
||||
embedding_model = os.environ.get("AZURE_OPENAI_EMBEDDING_MODEL_ID", "text-embedding-3-small")
|
||||
embedding_deployment = os.environ.get("AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME")
|
||||
|
||||
embedding_client = None
|
||||
if openai_endpoint and embedding_model:
|
||||
embedding_client = AzureOpenAIEmbeddingClient(
|
||||
endpoint=openai_endpoint,
|
||||
model=embedding_model,
|
||||
if openai_endpoint and embedding_deployment:
|
||||
embedding_client = OpenAIEmbeddingClient(
|
||||
azure_endpoint=openai_endpoint,
|
||||
model=embedding_deployment,
|
||||
credential=credential,
|
||||
)
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.declarative import AgentFactory
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
@@ -31,16 +32,17 @@ description: A agent that performs diagnostics on systems and can escalate issue
|
||||
|
||||
model:
|
||||
id: =Env.AZURE_OPENAI_MODEL
|
||||
connection:
|
||||
kind: remote
|
||||
endpoint: =Env.FOUNDRY_PROJECT_ENDPOINT
|
||||
"""
|
||||
# create the agent from the yaml
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AgentFactory(client_kwargs={"credential": credential}, safe_mode=False).create_agent_from_yaml(
|
||||
yaml_definition
|
||||
) as agent,
|
||||
AgentFactory(
|
||||
client_kwargs={
|
||||
"credential": credential,
|
||||
"project_endpoint": os.environ["FOUNDRY_PROJECT_ENDPOINT"],
|
||||
},
|
||||
safe_mode=False,
|
||||
).create_agent_from_yaml(yaml_definition) as agent,
|
||||
):
|
||||
response = await agent.run("What can you do for me?")
|
||||
print("Agent response:", response.text)
|
||||
|
||||
@@ -85,7 +85,7 @@ Alternatively, set environment variables globally:
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY="your-key-here"
|
||||
export OPENAI_CHAT_MODEL_ID="gpt-4o"
|
||||
export OPENAI_CHAT_MODEL="gpt-4o"
|
||||
```
|
||||
|
||||
## Using DevUI with Your Own Agents
|
||||
|
||||
@@ -2,55 +2,59 @@
|
||||
|
||||
# Run with: uv run samples/02-agents/embeddings/azure_openai_embeddings.py
|
||||
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.azure import AzureOpenAIEmbeddingClient
|
||||
from agent_framework.openai import OpenAIEmbeddingClient
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
"""Azure OpenAI Embedding Client Example
|
||||
|
||||
This sample demonstrates how to generate embeddings using the Azure OpenAI embedding client.
|
||||
It supports both API key and Azure credential authentication.
|
||||
"""This sample demonstrates Azure OpenAI embedding generation with ``OpenAIEmbeddingClient``.
|
||||
|
||||
Prerequisites:
|
||||
Set the following environment variables or add them to a .env file:
|
||||
- AZURE_OPENAI_ENDPOINT: Your Azure OpenAI endpoint URL
|
||||
- AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME: The embedding model deployment name
|
||||
- AZURE_OPENAI_API_KEY: Your API key (or use Azure credential instead)
|
||||
Set the following environment variables or add them to a local ``.env`` file:
|
||||
- ``AZURE_OPENAI_ENDPOINT``: Your Azure OpenAI endpoint URL
|
||||
- ``AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME``: The embedding deployment name
|
||||
- ``AZURE_OPENAI_API_VERSION``: Optional API version override
|
||||
|
||||
Sign in with ``az login`` before running the sample.
|
||||
"""
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Generate embeddings with Azure OpenAI."""
|
||||
# 1. Create a client using environment variables.
|
||||
# Reads AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME,
|
||||
# and AZURE_OPENAI_API_KEY from environment.
|
||||
client = AzureOpenAIEmbeddingClient()
|
||||
async with AzureCliCredential() as credential:
|
||||
client = OpenAIEmbeddingClient(
|
||||
model=os.getenv("AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME"),
|
||||
azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
|
||||
api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
|
||||
credential=credential,
|
||||
)
|
||||
|
||||
# 2. Generate a single embedding.
|
||||
result = await client.get_embeddings(["Hello, world!"])
|
||||
print(f"Single embedding dimensions: {result[0].dimensions}")
|
||||
print(f"First 5 values: {result[0].vector[:5]}")
|
||||
print(f"Model: {result[0].model_id}")
|
||||
print(f"Usage: {result.usage}")
|
||||
print()
|
||||
# 1. Generate a single embedding.
|
||||
result = await client.get_embeddings(["Hello, world!"])
|
||||
print(f"Single embedding dimensions: {result[0].dimensions}")
|
||||
print(f"First 5 values: {result[0].vector[:5]}")
|
||||
print(f"Model: {result[0].model}")
|
||||
print(f"Usage: {result.usage}")
|
||||
print()
|
||||
|
||||
# 3. Generate embeddings for multiple inputs.
|
||||
texts = [
|
||||
"The weather is sunny today.",
|
||||
"It is raining outside.",
|
||||
"Machine learning is fascinating.",
|
||||
]
|
||||
result = await client.get_embeddings(texts)
|
||||
print(f"Batch of {len(result)} embeddings, each with {result[0].dimensions} dimensions")
|
||||
print()
|
||||
# 2. Generate embeddings for multiple inputs.
|
||||
texts = [
|
||||
"The weather is sunny today.",
|
||||
"It is raining outside.",
|
||||
"Machine learning is fascinating.",
|
||||
]
|
||||
result = await client.get_embeddings(texts)
|
||||
print(f"Batch of {len(result)} embeddings, each with {result[0].dimensions} dimensions")
|
||||
print(f"First embedding vector: {result[0].vector[:5]}")
|
||||
print()
|
||||
|
||||
# 4. Generate embeddings with custom dimensions.
|
||||
result = await client.get_embeddings(["Custom dimensions example"], options={"dimensions": 256})
|
||||
print(f"Custom dimensions: {result[0].dimensions}")
|
||||
# 3. Generate embeddings with custom dimensions.
|
||||
result = await client.get_embeddings(["Custom dimensions example"], options={"dimensions": 256})
|
||||
print(f"Custom dimensions: {result[0].dimensions}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -3,31 +3,32 @@
|
||||
# Run with: uv run samples/02-agents/embeddings/openai_embeddings.py
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.openai import OpenAIEmbeddingClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
"""OpenAI Embedding Client Example
|
||||
|
||||
This sample demonstrates how to generate embeddings using the OpenAI embedding client.
|
||||
It shows single and batch embedding generation, as well as custom dimensions.
|
||||
"""This sample demonstrates OpenAI embedding generation with explicit constructor settings.
|
||||
|
||||
Prerequisites:
|
||||
Set the OPENAI_API_KEY environment variable or add it to a .env file.
|
||||
Set ``OPENAI_API_KEY`` in your environment or in a local ``.env`` file.
|
||||
"""
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Generate embeddings with OpenAI."""
|
||||
client = OpenAIEmbeddingClient(model="text-embedding-3-small")
|
||||
client = OpenAIEmbeddingClient(
|
||||
model="text-embedding-3-small",
|
||||
api_key=os.getenv("OPENAI_API_KEY"),
|
||||
)
|
||||
|
||||
# 1. Generate a single embedding.
|
||||
result = await client.get_embeddings(["Hello, world!"])
|
||||
print(f"Single embedding dimensions: {result[0].dimensions}")
|
||||
print(f"First 5 values: {result[0].vector[:5]}")
|
||||
print(f"Model: {result[0].model_id}")
|
||||
print(f"Model: {result[0].model}")
|
||||
print(f"Usage: {result.usage}")
|
||||
print()
|
||||
|
||||
@@ -39,7 +40,7 @@ async def main() -> None:
|
||||
]
|
||||
result = await client.get_embeddings(texts)
|
||||
print(f"Batch of {len(result)} embeddings, each with {result[0].dimensions} dimensions")
|
||||
print(f"First embedding vector: {result[0].vector[:5]}") # Print first 5 values of the first embedding
|
||||
print(f"First embedding vector: {result[0].vector[:5]}")
|
||||
print()
|
||||
|
||||
# 3. Generate embeddings with custom dimensions.
|
||||
|
||||
@@ -17,7 +17,7 @@ The Model Context Protocol (MCP) is an open standard for connecting AI agents to
|
||||
## Prerequisites
|
||||
|
||||
- `OPENAI_API_KEY` environment variable
|
||||
- `OPENAI_RESPONSES_MODEL_ID` environment variable
|
||||
- `OPENAI_RESPONSES_MODEL` environment variable
|
||||
|
||||
For `mcp_github_pat.py`:
|
||||
- `GITHUB_PAT` - Your GitHub Personal Access Token (create at https://github.com/settings/tokens)
|
||||
|
||||
@@ -25,7 +25,7 @@ The new usage tracking sample uses `OpenAIResponsesClient`, so set the usual Ope
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY="your-openai-api-key"
|
||||
export OPENAI_RESPONSES_MODEL_ID="gpt-4.1-mini"
|
||||
export OPENAI_RESPONSES_MODEL="gpt-4.1-mini"
|
||||
```
|
||||
|
||||
Then run:
|
||||
|
||||
@@ -40,8 +40,8 @@ ENABLE_SENSITIVE_DATA=true
|
||||
# OpenAI specific variables
|
||||
# ==========================
|
||||
OPENAI_API_KEY="..."
|
||||
OPENAI_RESPONSES_MODEL_ID="gpt-4o-2024-08-06"
|
||||
OPENAI_CHAT_MODEL_ID="gpt-4o-2024-08-06"
|
||||
OPENAI_RESPONSES_MODEL="gpt-4o-2024-08-06"
|
||||
OPENAI_CHAT_MODEL="gpt-4o-2024-08-06"
|
||||
|
||||
# Azure AI Foundry specific variables
|
||||
# ====================================
|
||||
|
||||
@@ -1,12 +1,48 @@
|
||||
# Azure Provider Samples
|
||||
|
||||
This folder contains Azure OpenAI chat completion samples for Agent Framework.
|
||||
This folder contains Azure-backed samples for the generic OpenAI clients in
|
||||
`agent_framework.openai`.
|
||||
|
||||
## Azure OpenAI ChatCompletionClient Samples
|
||||
## Chat Completions API samples (`OpenAIChatCompletionClient`)
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| [`openai_chat_completion_client_azure_basic.py`](openai_chat_completion_client_azure_basic.py) | Azure OpenAI Chat Client Basic Example |
|
||||
| [`openai_chat_completion_client_azure_with_explicit_settings.py`](openai_chat_completion_client_azure_with_explicit_settings.py) | Azure OpenAI Chat Client with Explicit Settings Example |
|
||||
| [`openai_chat_completion_client_azure_with_function_tools.py`](openai_chat_completion_client_azure_with_function_tools.py) | Azure OpenAI Chat Client with Function Tools Example |
|
||||
| [`openai_chat_completion_client_azure_with_session.py`](openai_chat_completion_client_azure_with_session.py) | Azure OpenAI Chat Client with Session Management Example |
|
||||
| [`openai_chat_completion_client_basic.py`](openai_chat_completion_client_basic.py) | Basic Azure chat completions sample using explicit Azure settings and `credential=AzureCliCredential()`. |
|
||||
| [`openai_chat_completion_client_with_explicit_settings.py`](openai_chat_completion_client_with_explicit_settings.py) | Azure chat completions sample with explicit settings. |
|
||||
| [`openai_chat_completion_client_with_function_tools.py`](openai_chat_completion_client_with_function_tools.py) | Azure chat completions sample with function tools. |
|
||||
| [`openai_chat_completion_client_with_session.py`](openai_chat_completion_client_with_session.py) | Azure chat completions sample with session management. |
|
||||
|
||||
## Responses API samples (`OpenAIChatClient`)
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| [`openai_client_basic.py`](openai_client_basic.py) | Basic Azure responses sample using explicit settings and `credential=AzureCliCredential()`. |
|
||||
| [`openai_client_with_function_tools.py`](openai_client_with_function_tools.py) | Azure responses sample with function tools. |
|
||||
| [`openai_client_with_session.py`](openai_client_with_session.py) | Azure responses sample with session management. |
|
||||
| [`openai_client_with_structured_output.py`](openai_client_with_structured_output.py) | Azure responses sample with structured output. |
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Set these before running the Azure provider samples:
|
||||
|
||||
- `AZURE_OPENAI_ENDPOINT`
|
||||
- `AZURE_OPENAI_DEPLOYMENT_NAME`
|
||||
|
||||
Optionally, you can also set:
|
||||
|
||||
- `AZURE_OPENAI_API_KEY`
|
||||
- `AZURE_OPENAI_API_VERSION`
|
||||
- `AZURE_OPENAI_BASE_URL`
|
||||
|
||||
These Azure samples are written around explicit Azure inputs such as
|
||||
`credential=AzureCliCredential()`, so they stay on Azure even if `OPENAI_API_KEY` is also present.
|
||||
|
||||
## Optional Dependencies
|
||||
|
||||
Credential-based samples require `azure-identity`:
|
||||
|
||||
```bash
|
||||
pip install azure-identity
|
||||
```
|
||||
|
||||
Run `az login` before executing the credential-based samples.
|
||||
|
||||
+19
-14
@@ -1,6 +1,7 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
@@ -16,14 +17,12 @@ load_dotenv()
|
||||
"""
|
||||
Azure OpenAI Chat Client Basic Example
|
||||
|
||||
This sample demonstrates basic usage of OpenAIChatCompletionClient for direct chat-based
|
||||
interactions, showing both streaming and non-streaming responses.
|
||||
This sample demonstrates basic usage of OpenAIChatCompletionClient with explicit Azure
|
||||
settings and a credential, showing both streaming and non-streaming responses.
|
||||
"""
|
||||
|
||||
|
||||
# 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.
|
||||
# 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.")],
|
||||
@@ -37,11 +36,14 @@ async def non_streaming_example() -> None:
|
||||
"""Example of non-streaming response (get the complete result at once)."""
|
||||
print("=== Non-streaming Response Example ===")
|
||||
|
||||
# Create agent with Azure Chat Client
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
agent = Agent(
|
||||
client=OpenAIChatCompletionClient(credential=AzureCliCredential()),
|
||||
client=OpenAIChatCompletionClient(
|
||||
model=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"),
|
||||
azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
|
||||
api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
|
||||
credential=AzureCliCredential(),
|
||||
),
|
||||
name="WeatherAgent",
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
@@ -56,11 +58,14 @@ async def streaming_example() -> None:
|
||||
"""Example of streaming response (get results as they are generated)."""
|
||||
print("=== Streaming Response Example ===")
|
||||
|
||||
# Create agent with Azure Chat Client
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
agent = Agent(
|
||||
client=OpenAIChatCompletionClient(credential=AzureCliCredential()),
|
||||
client=OpenAIChatCompletionClient(
|
||||
model=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"),
|
||||
azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
|
||||
api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
|
||||
credential=AzureCliCredential(),
|
||||
),
|
||||
name="WeatherAgent",
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
@@ -75,7 +80,7 @@ async def streaming_example() -> None:
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== Basic Azure Chat Client Agent Example ===")
|
||||
print("=== Basic Azure Chat Completion Client Agent Example ===")
|
||||
|
||||
await non_streaming_example()
|
||||
await streaming_example()
|
||||
+10
-11
@@ -15,16 +15,16 @@ from pydantic import Field
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure OpenAI Chat Client with Explicit Settings Example
|
||||
OpenAI Chat Completion Client with Explicit Settings Example
|
||||
|
||||
This sample demonstrates creating Azure OpenAI Chat Client with explicit configuration
|
||||
This samples connects to Azure OpenAI.
|
||||
|
||||
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.
|
||||
# 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.")],
|
||||
@@ -39,13 +39,12 @@ async def main() -> None:
|
||||
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
_client = OpenAIChatCompletionClient(
|
||||
model=os.environ["AZURE_OPENAI_CHAT_DEPLOYMENT_NAME"],
|
||||
endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
|
||||
credential=AzureCliCredential(),
|
||||
)
|
||||
agent = Agent(
|
||||
client=_client,
|
||||
client=OpenAIChatCompletionClient(
|
||||
model=os.environ["AZURE_OPENAI_CHAT_DEPLOYMENT_NAME"],
|
||||
azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
|
||||
credential=AzureCliCredential(),
|
||||
),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=[get_weather],
|
||||
)
|
||||
@@ -0,0 +1,90 @@
|
||||
# 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 azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure OpenAI Chat Client Basic Example
|
||||
|
||||
This sample demonstrates basic usage of OpenAIChatClient with explicit Azure
|
||||
settings and a credential, 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=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"),
|
||||
azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
|
||||
api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
|
||||
credential=AzureCliCredential(),
|
||||
),
|
||||
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=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"),
|
||||
azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
|
||||
api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
|
||||
credential=AzureCliCredential(),
|
||||
),
|
||||
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 Azure OpenAI Chat Client Agent Example ===")
|
||||
|
||||
await non_streaming_example()
|
||||
await streaming_example()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,137 @@
|
||||
# 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 azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure OpenAI Chat Client with Function Tools Example
|
||||
|
||||
This sample demonstrates function tool integration with Azure 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(credential=AzureCliCredential()),
|
||||
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(credential=AzureCliCredential()),
|
||||
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(credential=AzureCliCredential()),
|
||||
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("=== Azure 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,152 @@
|
||||
# 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 azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure OpenAI Chat Client with Session Management Example
|
||||
|
||||
This sample demonstrates session management with Azure 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(credential=AzureCliCredential()),
|
||||
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(credential=AzureCliCredential()),
|
||||
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, 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, 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, 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(credential=AzureCliCredential()),
|
||||
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 ---")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(credential=AzureCliCredential()),
|
||||
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("=== Azure OpenAI Chat Client 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,93 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Agent, AgentResponse
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import BaseModel
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure OpenAI Chat Client with Structured Output Example
|
||||
|
||||
This sample demonstrates using structured output capabilities with Azure 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 Azure OpenAI Chat agent
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(credential=AzureCliCredential()),
|
||||
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 Azure OpenAI Chat agent
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(credential=AzureCliCredential()),
|
||||
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("=== Azure OpenAI Chat Client Agent with Structured Output ===")
|
||||
|
||||
await non_streaming_example()
|
||||
await streaming_example()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -27,7 +27,7 @@ Both approaches allow you to extend the framework for your specific use cases wh
|
||||
|
||||
## Understanding Raw Client Classes
|
||||
|
||||
The framework provides `Raw...Client` classes (e.g., `RawOpenAIChatClient`, `RawOpenAIResponsesClient`, `RawAzureAIClient`) that are intermediate implementations without middleware, telemetry, or function invocation support.
|
||||
The framework provides `Raw...Client` classes (e.g., `RawOpenAIChatClient`, `RawOpenAIChatCompletionClient`, `RawAzureAIClient`) that are intermediate implementations without middleware, telemetry, or function invocation support.
|
||||
|
||||
### Warning: Raw Clients Should Not Normally Be Used Directly
|
||||
|
||||
@@ -60,8 +60,8 @@ class MyCustomClient(
|
||||
|
||||
For most use cases, use the fully-featured public client classes which already have all layers correctly composed:
|
||||
|
||||
- `OpenAIChatClient` - OpenAI Chat completions with all layers
|
||||
- `OpenAIResponsesClient` - OpenAI Responses API with all layers
|
||||
- `OpenAIChatCompletionClient` - OpenAI Chat Completions API with all layers
|
||||
- `OpenAIChatClient` - OpenAI Responses API with all layers
|
||||
- `AzureOpenAIChatClient` - Azure OpenAI Chat with all layers
|
||||
- `AzureOpenAIResponsesClient` - Azure OpenAI Responses with all layers
|
||||
- `AzureAIClient` - Azure AI Project with all layers
|
||||
|
||||
@@ -19,6 +19,8 @@ from typing import Annotated
|
||||
|
||||
from agent_framework import tool
|
||||
from agent_framework.github import GitHubCopilotAgent
|
||||
from copilot.generated.session_events import PermissionRequest
|
||||
from copilot.types import PermissionRequestResult
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
@@ -26,6 +28,19 @@ from pydantic import Field
|
||||
load_dotenv()
|
||||
|
||||
|
||||
def prompt_permission(request: PermissionRequest, context: dict[str, str]) -> PermissionRequestResult:
|
||||
"""Permission handler that prompts the user for approval."""
|
||||
print(f"\n[Permission Request: {request.kind}]")
|
||||
|
||||
if request.full_command_text is not None:
|
||||
print(f" Command: {request.full_command_text}")
|
||||
|
||||
response = input("Approve? (y/n): ").strip().lower()
|
||||
if response in ("y", "yes"):
|
||||
return PermissionRequestResult(kind="approved")
|
||||
return PermissionRequestResult(kind="denied-interactively-by-user")
|
||||
|
||||
|
||||
# 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.
|
||||
@@ -45,6 +60,7 @@ async def non_streaming_example() -> None:
|
||||
agent = GitHubCopilotAgent(
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=[get_weather],
|
||||
default_options={"on_permission_request": prompt_permission},
|
||||
)
|
||||
|
||||
async with agent:
|
||||
@@ -61,6 +77,7 @@ async def streaming_example() -> None:
|
||||
agent = GitHubCopilotAgent(
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=[get_weather],
|
||||
default_options={"on_permission_request": prompt_permission},
|
||||
)
|
||||
|
||||
async with agent:
|
||||
@@ -80,6 +97,7 @@ async def runtime_options_example() -> None:
|
||||
agent = GitHubCopilotAgent(
|
||||
instructions="Always respond in exactly 3 words.",
|
||||
tools=[get_weather],
|
||||
default_options={"on_permission_request": prompt_permission},
|
||||
)
|
||||
|
||||
async with agent:
|
||||
|
||||
@@ -69,9 +69,10 @@ async def main() -> None:
|
||||
print(f"Agent: {result1}\n")
|
||||
|
||||
# Query that exercises the remote Microsoft Learn MCP server
|
||||
# Remote MCP calls may take longer, so increase the timeout
|
||||
query2 = "Search Microsoft Learn for 'Azure Functions Python' and summarize the top result"
|
||||
print(f"User: {query2}")
|
||||
result2 = await agent.run(query2)
|
||||
result2 = await agent.run(query2, options={"timeout": 120})
|
||||
print(f"Agent: {result2}\n")
|
||||
|
||||
|
||||
|
||||
@@ -14,9 +14,24 @@ from typing import Annotated
|
||||
|
||||
from agent_framework import tool
|
||||
from agent_framework.github import GitHubCopilotAgent
|
||||
from copilot.generated.session_events import PermissionRequest
|
||||
from copilot.types import PermissionRequestResult
|
||||
from pydantic import Field
|
||||
|
||||
|
||||
def prompt_permission(request: PermissionRequest, context: dict[str, str]) -> PermissionRequestResult:
|
||||
"""Permission handler that prompts the user for approval."""
|
||||
print(f"\n[Permission Request: {request.kind}]")
|
||||
|
||||
if request.full_command_text is not None:
|
||||
print(f" Command: {request.full_command_text}")
|
||||
|
||||
response = input("Approve? (y/n): ").strip().lower()
|
||||
if response in ("y", "yes"):
|
||||
return PermissionRequestResult(kind="approved")
|
||||
return PermissionRequestResult(kind="denied-interactively-by-user")
|
||||
|
||||
|
||||
# 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.
|
||||
@@ -36,6 +51,7 @@ async def example_with_automatic_session_creation() -> None:
|
||||
agent = GitHubCopilotAgent(
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=[get_weather],
|
||||
default_options={"on_permission_request": prompt_permission},
|
||||
)
|
||||
|
||||
async with agent:
|
||||
@@ -50,7 +66,7 @@ async def example_with_automatic_session_creation() -> None:
|
||||
print(f"\nUser: {query2}")
|
||||
result2 = await agent.run(query2)
|
||||
print(f"Agent: {result2}")
|
||||
print("Note: Each call creates a separate session, so the agent doesn't remember previous context.\n")
|
||||
print("Note: Each call creates a separate session, so the agent may not remember previous context.\n")
|
||||
|
||||
|
||||
async def example_with_session_persistence() -> None:
|
||||
@@ -60,6 +76,7 @@ async def example_with_session_persistence() -> None:
|
||||
agent = GitHubCopilotAgent(
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=[get_weather],
|
||||
default_options={"on_permission_request": prompt_permission},
|
||||
)
|
||||
|
||||
async with agent:
|
||||
@@ -96,6 +113,7 @@ async def example_with_existing_session_id() -> None:
|
||||
agent1 = GitHubCopilotAgent(
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=[get_weather],
|
||||
default_options={"on_permission_request": prompt_permission},
|
||||
)
|
||||
|
||||
async with agent1:
|
||||
@@ -117,6 +135,7 @@ async def example_with_existing_session_id() -> None:
|
||||
agent2 = GitHubCopilotAgent(
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=[get_weather],
|
||||
default_options={"on_permission_request": prompt_permission},
|
||||
)
|
||||
|
||||
async with agent2:
|
||||
|
||||
@@ -1,66 +1,63 @@
|
||||
# OpenAI Agent Framework Examples
|
||||
# OpenAI Provider Samples
|
||||
|
||||
This folder contains examples demonstrating different ways to create and use agents with the OpenAI clients from the `agent_framework.openai` package.
|
||||
This folder contains OpenAI provider samples for the generic clients in
|
||||
`agent_framework.openai`.
|
||||
|
||||
## Examples
|
||||
## Chat Completions API samples (`OpenAIChatCompletionClient`)
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| [`openai_assistants_basic.py`](openai_assistants_basic.py) | Basic usage of `OpenAIAssistantProvider` with streaming and non-streaming responses. |
|
||||
| [`openai_assistants_provider_methods.py`](openai_assistants_provider_methods.py) | Demonstrates all `OpenAIAssistantProvider` methods: `create_agent()`, `get_agent()`, and `as_agent()`. |
|
||||
| [`openai_assistants_with_code_interpreter.py`](openai_assistants_with_code_interpreter.py) | Using `OpenAIAssistantsClient.get_code_interpreter_tool()` with `OpenAIAssistantProvider` to execute Python code. |
|
||||
| [`openai_assistants_with_existing_assistant.py`](openai_assistants_with_existing_assistant.py) | Working with pre-existing assistants using `get_agent()` and `as_agent()` methods. |
|
||||
| [`openai_assistants_with_explicit_settings.py`](openai_assistants_with_explicit_settings.py) | Configuring `OpenAIAssistantProvider` with explicit settings including API key and model ID. |
|
||||
| [`openai_assistants_with_file_search.py`](openai_assistants_with_file_search.py) | Using `OpenAIAssistantsClient.get_file_search_tool()` with `OpenAIAssistantProvider` for file search capabilities. |
|
||||
| [`openai_assistants_with_function_tools.py`](openai_assistants_with_function_tools.py) | Function tools with `OpenAIAssistantProvider` at both agent-level and query-level. |
|
||||
| [`openai_assistants_with_response_format.py`](openai_assistants_with_response_format.py) | Structured outputs with `OpenAIAssistantProvider` using Pydantic models. |
|
||||
| [`openai_assistants_with_session.py`](openai_assistants_with_session.py) | Session management with `OpenAIAssistantProvider` for conversation context persistence. |
|
||||
| [`openai_chat_client_basic.py`](openai_chat_client_basic.py) | The simplest way to create an agent using `Agent` with `OpenAIChatClient`. Shows both streaming and non-streaming responses for chat-based interactions with OpenAI models. |
|
||||
| [`openai_chat_client_with_explicit_settings.py`](openai_chat_client_with_explicit_settings.py) | Shows how to initialize an agent with a specific chat client, configuring settings explicitly including API key and model ID. |
|
||||
| [`openai_chat_client_with_function_tools.py`](openai_chat_client_with_function_tools.py) | Demonstrates how to use function tools with agents. Shows both agent-level tools (defined when creating the agent) and query-level tools (provided with specific queries). |
|
||||
| [`openai_chat_client_with_local_mcp.py`](openai_chat_client_with_local_mcp.py) | Shows how to integrate OpenAI agents with local Model Context Protocol (MCP) servers for enhanced functionality and tool integration. |
|
||||
| [`openai_chat_client_with_session.py`](openai_chat_client_with_session.py) | Demonstrates session management with OpenAI agents, including automatic session creation for stateless conversations and explicit session management for maintaining conversation context across multiple interactions. |
|
||||
| [`openai_chat_client_with_web_search.py`](openai_chat_client_with_web_search.py) | Shows how to use `OpenAIChatClient.get_web_search_tool()` for web search capabilities with OpenAI agents. |
|
||||
| [`openai_chat_client_with_runtime_json_schema.py`](openai_chat_client_with_runtime_json_schema.py) | Shows how to supply a runtime JSON Schema via `additional_chat_options` for structured output without defining a Pydantic model. |
|
||||
| [`openai_responses_client_basic.py`](openai_responses_client_basic.py) | The simplest way to create an agent using `Agent` with `OpenAIResponsesClient`. Shows both streaming and non-streaming responses for structured response generation with OpenAI models. |
|
||||
| [`openai_responses_client_image_analysis.py`](openai_responses_client_image_analysis.py) | Demonstrates how to use vision capabilities with agents to analyze images. |
|
||||
| [`openai_responses_client_image_generation.py`](openai_responses_client_image_generation.py) | Demonstrates how to use `OpenAIResponsesClient.get_image_generation_tool()` to create images based on text descriptions. |
|
||||
| [`openai_responses_client_reasoning.py`](openai_responses_client_reasoning.py) | Demonstrates how to use reasoning capabilities with OpenAI agents, showing how the agent can provide detailed reasoning for its responses. |
|
||||
| [`openai_responses_client_streaming_image_generation.py`](openai_responses_client_streaming_image_generation.py) | Demonstrates streaming image generation with partial images for real-time image creation feedback and improved user experience. |
|
||||
| [`openai_responses_client_with_agent_as_tool.py`](openai_responses_client_with_agent_as_tool.py) | Shows how to use the agent-as-tool pattern with OpenAI Responses Client, where one agent delegates work to specialized sub-agents wrapped as tools using `as_tool()`. Demonstrates hierarchical agent architectures. |
|
||||
| [`openai_responses_client_with_code_interpreter.py`](openai_responses_client_with_code_interpreter.py) | Shows how to use `OpenAIResponsesClient.get_code_interpreter_tool()` to write and execute Python code. |
|
||||
| [`openai_responses_client_with_code_interpreter_files.py`](openai_responses_client_with_code_interpreter_files.py) | Shows how to use code interpreter with uploaded files for data analysis. |
|
||||
| [`openai_responses_client_with_explicit_settings.py`](openai_responses_client_with_explicit_settings.py) | Shows how to initialize an agent with a specific responses client, configuring settings explicitly including API key and model ID. |
|
||||
| [`openai_responses_client_with_file_search.py`](openai_responses_client_with_file_search.py) | Demonstrates how to use `OpenAIResponsesClient.get_file_search_tool()` for searching through uploaded files. |
|
||||
| [`openai_responses_client_with_function_tools.py`](openai_responses_client_with_function_tools.py) | Demonstrates how to use function tools with agents. Shows both agent-level tools (defined when creating the agent) and run-level tools (provided with specific queries). |
|
||||
| [`openai_responses_client_with_hosted_mcp.py`](openai_responses_client_with_hosted_mcp.py) | Shows how to use `OpenAIResponsesClient.get_mcp_tool()` for hosted MCP servers, including approval workflows. |
|
||||
| [`openai_responses_client_with_local_mcp.py`](openai_responses_client_with_local_mcp.py) | Shows how to integrate OpenAI agents with local Model Context Protocol (MCP) servers for enhanced functionality and tool integration. |
|
||||
| [`openai_responses_client_with_runtime_json_schema.py`](openai_responses_client_with_runtime_json_schema.py) | Shows how to supply a runtime JSON Schema via `additional_chat_options` for structured output without defining a Pydantic model. |
|
||||
| [`openai_responses_client_with_structured_output.py`](openai_responses_client_with_structured_output.py) | Demonstrates how to use structured outputs with OpenAI agents to get structured data responses in predefined formats. |
|
||||
| [`openai_responses_client_with_session.py`](openai_responses_client_with_session.py) | Demonstrates session management with OpenAI agents, including automatic session creation for stateless conversations and explicit session management for maintaining conversation context across multiple interactions. |
|
||||
| [`openai_responses_client_with_web_search.py`](openai_responses_client_with_web_search.py) | Shows how to use `OpenAIResponsesClient.get_web_search_tool()` for web search capabilities. |
|
||||
| [`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_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
|
||||
|
||||
Make sure to set the following environment variables before running the examples:
|
||||
Set these before running the OpenAI provider samples:
|
||||
|
||||
- `OPENAI_API_KEY`: Your OpenAI API key
|
||||
- `OPENAI_MODEL`: The OpenAI model to use (e.g., `gpt-4o`, `gpt-4o-mini`, `gpt-3.5-turbo`)
|
||||
- For image processing examples, use a vision-capable model like `gpt-4o` or `gpt-4o-mini`
|
||||
- `OPENAI_API_KEY`
|
||||
- `OPENAI_MODEL`
|
||||
|
||||
Optionally, you can set:
|
||||
- `OPENAI_ORG_ID`: Your OpenAI organization ID (if applicable)
|
||||
- `OPENAI_API_BASE_URL`: Your OpenAI base URL (if using a different base URL)
|
||||
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 examples require additional dependencies:
|
||||
Some samples need extra packages:
|
||||
|
||||
- **Image Generation Example**: The `openai_responses_client_image_generation.py` example requires PIL (Pillow) for image display. Install with:
|
||||
```bash
|
||||
# Using uv
|
||||
uv add pillow
|
||||
|
||||
# Or using pip
|
||||
pip install pillow
|
||||
```
|
||||
- `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())
|
||||
+8
-10
@@ -6,7 +6,7 @@ from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from agent_framework.openai import OpenAIChatCompletionClient
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
@@ -14,9 +14,9 @@ from pydantic import Field
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Responses Client with Explicit Settings Example
|
||||
OpenAI Chat Completion Client with Explicit Settings Example
|
||||
|
||||
This sample demonstrates creating OpenAI Responses Client with explicit configuration
|
||||
This sample demonstrates creating OpenAI Chat Completion Client with explicit configuration
|
||||
settings rather than relying on environment variable defaults.
|
||||
"""
|
||||
|
||||
@@ -34,15 +34,13 @@ def get_weather(
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Responses Client with Explicit Settings ===")
|
||||
|
||||
_client = OpenAIResponsesClient(
|
||||
model=os.environ["OPENAI_MODEL"],
|
||||
api_key=os.environ["OPENAI_API_KEY"],
|
||||
)
|
||||
print("=== OpenAI Chat Completion Client with Explicit Settings ===")
|
||||
|
||||
agent = Agent(
|
||||
client=_client,
|
||||
client=OpenAIChatCompletionClient(
|
||||
model=os.environ["OPENAI_MODEL"],
|
||||
api_key=os.environ["OPENAI_API_KEY"],
|
||||
),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
+7
-7
@@ -6,7 +6,7 @@ from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from agent_framework.openai import OpenAIChatCompletionClient
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
@@ -14,9 +14,9 @@ from pydantic import Field
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Responses Client with Function Tools Example
|
||||
OpenAI Chat Completion Client with Function Tools Example
|
||||
|
||||
This sample demonstrates function tool integration with OpenAI Responses Client,
|
||||
This sample demonstrates function tool integration with OpenAI Chat Completion Client,
|
||||
showing both agent-level and query-level tool configuration patterns.
|
||||
"""
|
||||
|
||||
@@ -47,7 +47,7 @@ async def tools_on_agent_level() -> None:
|
||||
# Tools are provided when creating the agent
|
||||
# The agent can use these tools for any query during its lifetime
|
||||
agent = Agent(
|
||||
client=OpenAIResponsesClient(),
|
||||
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
|
||||
)
|
||||
@@ -77,7 +77,7 @@ async def tools_on_run_level() -> None:
|
||||
|
||||
# Agent created without tools
|
||||
agent = Agent(
|
||||
client=OpenAIResponsesClient(),
|
||||
client=OpenAIChatCompletionClient(),
|
||||
instructions="You are a helpful assistant.",
|
||||
# No tools defined here
|
||||
)
|
||||
@@ -107,7 +107,7 @@ async def mixed_tools_example() -> None:
|
||||
|
||||
# Agent created with some base tools
|
||||
agent = Agent(
|
||||
client=OpenAIResponsesClient(),
|
||||
client=OpenAIChatCompletionClient(),
|
||||
instructions="You are a comprehensive assistant that can help with various information requests.",
|
||||
tools=[get_weather], # Base tool available for all queries
|
||||
)
|
||||
@@ -125,7 +125,7 @@ async def mixed_tools_example() -> None:
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Responses Client Agent with Function Tools Examples ===\n")
|
||||
print("=== OpenAI Chat Completion Client Agent with Function Tools Examples ===\n")
|
||||
|
||||
await tools_on_agent_level()
|
||||
await tools_on_run_level()
|
||||
+6
-6
@@ -3,17 +3,17 @@
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Agent, MCPStreamableHTTPTool
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from agent_framework.openai import OpenAIChatCompletionClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client with Local MCP Example
|
||||
OpenAI Chat Completion Client with Local MCP Example
|
||||
|
||||
This sample demonstrates integrating Model Context Protocol (MCP) tools with
|
||||
OpenAI Chat Client for extended functionality and external service access.
|
||||
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
|
||||
@@ -34,7 +34,7 @@ async def mcp_tools_on_run_level() -> None:
|
||||
url="https://learn.microsoft.com/api/mcp",
|
||||
) as mcp_server,
|
||||
Agent(
|
||||
client=OpenAIChatClient(),
|
||||
client=OpenAIChatCompletionClient(),
|
||||
name="DocsAgent",
|
||||
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
|
||||
) as agent,
|
||||
@@ -60,7 +60,7 @@ async def mcp_tools_on_agent_level() -> None:
|
||||
# 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=OpenAIChatClient(),
|
||||
client=OpenAIChatCompletionClient(),
|
||||
name="DocsAgent",
|
||||
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
|
||||
tools=MCPStreamableHTTPTool( # Tools defined at agent creation
|
||||
@@ -82,7 +82,7 @@ async def mcp_tools_on_agent_level() -> None:
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Chat Client Agent with MCP Tools Examples ===\n")
|
||||
print("=== OpenAI Chat Completion Client Agent with MCP Tools Examples ===\n")
|
||||
|
||||
await mcp_tools_on_agent_level()
|
||||
await mcp_tools_on_run_level()
|
||||
+5
-5
@@ -4,14 +4,14 @@ import asyncio
|
||||
import json
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from agent_framework.openai import OpenAIChatCompletionClient, OpenAIChatOptions
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client Runtime JSON Schema Example
|
||||
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
|
||||
@@ -38,7 +38,7 @@ async def non_streaming_example() -> None:
|
||||
print("=== Non-streaming runtime JSON schema example ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIResponsesClient(),
|
||||
client=OpenAIChatCompletionClient[OpenAIChatOptions](),
|
||||
name="RuntimeSchemaAgent",
|
||||
instructions="Return only JSON that matches the provided schema. Do not add commentary.",
|
||||
)
|
||||
@@ -72,7 +72,7 @@ async def streaming_example() -> None:
|
||||
print("=== Streaming runtime JSON schema example ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIResponsesClient(),
|
||||
client=OpenAIChatCompletionClient(),
|
||||
name="RuntimeSchemaAgent",
|
||||
instructions="Return only JSON that matches the provided schema. Do not add commentary.",
|
||||
)
|
||||
@@ -108,7 +108,7 @@ async def streaming_example() -> None:
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Chat Client with runtime JSON Schema ===")
|
||||
print("=== OpenAI Chat Completion Client with runtime JSON Schema ===")
|
||||
|
||||
await non_streaming_example()
|
||||
await streaming_example()
|
||||
+8
-8
@@ -5,7 +5,7 @@ from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import Agent, AgentSession, InMemoryHistoryProvider, tool
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from agent_framework.openai import OpenAIChatCompletionClient
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
@@ -13,9 +13,9 @@ from pydantic import Field
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client with Session Management Example
|
||||
OpenAI Chat Completion Client with Session Management Example
|
||||
|
||||
This sample demonstrates session management with OpenAI Chat Client, showing
|
||||
This sample demonstrates session management with OpenAI Chat Completion Client, showing
|
||||
conversation sessions and message history preservation across interactions.
|
||||
"""
|
||||
|
||||
@@ -37,7 +37,7 @@ async def example_with_automatic_session_creation() -> None:
|
||||
print("=== Automatic Session Creation Example ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
client=OpenAIChatCompletionClient(),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
@@ -62,7 +62,7 @@ async def example_with_session_persistence() -> None:
|
||||
print("Using the same session across multiple conversations to maintain context.\n")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
client=OpenAIChatCompletionClient(),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
@@ -95,7 +95,7 @@ async def example_with_existing_session_messages() -> None:
|
||||
print("=== Existing Session Messages Example ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
client=OpenAIChatCompletionClient(),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
@@ -118,7 +118,7 @@ async def example_with_existing_session_messages() -> None:
|
||||
|
||||
# Create a new agent instance but use the existing session with its message history
|
||||
new_agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
client=OpenAIChatCompletionClient(),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
@@ -142,7 +142,7 @@ async def example_with_existing_session_messages() -> None:
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Chat Client Agent Session Management Examples ===\n")
|
||||
print("=== OpenAI Chat Completion Client Agent Session Management Examples ===\n")
|
||||
|
||||
await example_with_automatic_session_creation()
|
||||
await example_with_session_persistence()
|
||||
+4
-4
@@ -3,22 +3,22 @@
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from agent_framework.openai import OpenAIChatCompletionClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Chat Client with Web Search Example
|
||||
OpenAI Chat Completion Client with Web Search Example
|
||||
|
||||
This sample demonstrates using get_web_search_tool() with OpenAI Chat Client
|
||||
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 = OpenAIChatClient(model="gpt-4o-search-preview")
|
||||
client = OpenAIChatCompletionClient(model="gpt-4o-search-preview")
|
||||
|
||||
# Create web search tool with location context
|
||||
web_search_tool = client.get_web_search_tool(
|
||||
+16
-10
@@ -1,12 +1,14 @@
|
||||
# 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()
|
||||
@@ -14,17 +16,15 @@ load_dotenv()
|
||||
"""
|
||||
OpenAI Chat Client Basic Example
|
||||
|
||||
This sample demonstrates basic usage of OpenAIChatClient for direct chat-based
|
||||
interactions, showing both streaming and non-streaming responses.
|
||||
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;
|
||||
# see samples/02-agents/tools/function_tool_with_approval.py
|
||||
# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py.
|
||||
# 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, "The location to get the weather for."],
|
||||
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"]
|
||||
@@ -36,13 +36,16 @@ async def non_streaming_example() -> None:
|
||||
print("=== Non-streaming Response Example ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
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 like in Seattle?"
|
||||
query = "What's the weather in Seattle?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Result: {result}\n")
|
||||
@@ -53,13 +56,16 @@ async def streaming_example() -> None:
|
||||
print("=== Streaming Response Example ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
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 like in Portland?"
|
||||
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):
|
||||
+6
-6
@@ -3,26 +3,26 @@
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Agent, Content
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Responses Client Image Analysis Example
|
||||
OpenAI Chat Client Image Analysis Example
|
||||
|
||||
This sample demonstrates using OpenAI Responses Client for image analysis and vision tasks,
|
||||
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 Responses Agent with Image Analysis ===")
|
||||
print("=== OpenAI Chat Client Agent with Image Analysis ===")
|
||||
|
||||
# 1. Create an OpenAI Responses agent with vision capabilities
|
||||
# 1. Create an OpenAI Chat agent with vision capabilities
|
||||
agent = Agent(
|
||||
client=OpenAIResponsesClient(),
|
||||
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.",
|
||||
)
|
||||
+5
-5
@@ -7,17 +7,17 @@ import urllib.request as urllib_request
|
||||
from pathlib import Path
|
||||
|
||||
from agent_framework import Agent, Content
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Responses Client Image Generation Example
|
||||
OpenAI Chat Client Image Generation Example
|
||||
|
||||
This sample demonstrates how to generate images using OpenAI's DALL-E models
|
||||
through the Responses Client. Image generation capabilities enable AI to create visual content from text,
|
||||
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.
|
||||
"""
|
||||
@@ -57,10 +57,10 @@ def save_image(output: Content) -> None:
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Responses Image Generation Agent Example ===")
|
||||
print("=== OpenAI Chat Image Generation Agent Example ===")
|
||||
|
||||
# Create an agent with customized image generation options
|
||||
client = OpenAIResponsesClient()
|
||||
client = OpenAIChatClient()
|
||||
agent = Agent(
|
||||
client=client,
|
||||
instructions="You are a helpful AI that can generate images.",
|
||||
+4
-4
@@ -3,14 +3,14 @@
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.openai import OpenAIResponsesClient, OpenAIResponsesOptions
|
||||
from agent_framework.openai import OpenAIChatClient, OpenAIChatOptions
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Responses Client Reasoning Example
|
||||
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.
|
||||
@@ -25,7 +25,7 @@ In this case they are here: https://platform.openai.com/docs/api-reference/respo
|
||||
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIResponsesClient[OpenAIResponsesOptions](model_id="gpt-5"),
|
||||
client=OpenAIChatClient[OpenAIChatOptions](model_id="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.",
|
||||
@@ -76,7 +76,7 @@ async def streaming_reasoning_example() -> None:
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("\033[92m=== Basic OpenAI Responses Reasoning Agent Example ===\033[0m")
|
||||
print("\033[92m=== Basic OpenAI Chat Reasoning Agent Example ===\033[0m")
|
||||
|
||||
await reasoning_example()
|
||||
await streaming_reasoning_example()
|
||||
+3
-3
@@ -7,12 +7,12 @@ from pathlib import Path
|
||||
|
||||
import anyio
|
||||
from agent_framework import Agent, Content
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
"""OpenAI Responses Client Streaming Image Generation Example
|
||||
"""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:
|
||||
@@ -42,7 +42,7 @@ 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 = OpenAIResponsesClient()
|
||||
client = OpenAIChatClient()
|
||||
agent = Agent(
|
||||
client=client,
|
||||
instructions="You are a helpful agent that can generate images.",
|
||||
+4
-4
@@ -4,14 +4,14 @@ import asyncio
|
||||
from collections.abc import Awaitable, Callable
|
||||
|
||||
from agent_framework import Agent, FunctionInvocationContext
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Responses Client Agent-as-Tool Example
|
||||
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().
|
||||
@@ -35,9 +35,9 @@ async def logging_middleware(
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Responses Client Agent-as-Tool Pattern ===")
|
||||
print("=== OpenAI Chat Client Agent-as-Tool Pattern ===")
|
||||
|
||||
client = OpenAIResponsesClient()
|
||||
client = OpenAIChatClient()
|
||||
|
||||
# Create a specialized writer agent
|
||||
writer = Agent(
|
||||
+6
-6
@@ -6,25 +6,25 @@ from agent_framework import (
|
||||
Agent,
|
||||
Content,
|
||||
)
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Responses Client with Code Interpreter Example
|
||||
OpenAI Chat Client with Code Interpreter Example
|
||||
|
||||
This sample demonstrates using get_code_interpreter_tool() with OpenAI Responses Client
|
||||
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 Responses."""
|
||||
print("=== OpenAI Responses Agent with Code Interpreter Example ===")
|
||||
"""Example showing how to use the code interpreter tool with OpenAI Chat."""
|
||||
print("=== OpenAI Chat Client Agent with Code Interpreter Example ===")
|
||||
|
||||
client = OpenAIResponsesClient()
|
||||
client = OpenAIChatClient()
|
||||
agent = Agent(
|
||||
client=client,
|
||||
instructions="You are a helpful assistant that can write and execute Python code to solve problems.",
|
||||
+5
-5
@@ -5,7 +5,7 @@ import os
|
||||
import tempfile
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
from openai import AsyncOpenAI
|
||||
|
||||
@@ -13,9 +13,9 @@ from openai import AsyncOpenAI
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Responses Client with Code Interpreter and Files Example
|
||||
OpenAI Chat Client with Code Interpreter and Files Example
|
||||
|
||||
This sample demonstrates using get_code_interpreter_tool() with OpenAI Responses Client
|
||||
This sample demonstrates using get_code_interpreter_tool() with OpenAI Chat Client
|
||||
for Python code execution and data analysis with uploaded files.
|
||||
"""
|
||||
|
||||
@@ -69,8 +69,8 @@ async def main() -> None:
|
||||
|
||||
temp_file_path, file_id = await create_sample_file_and_upload(openai_client)
|
||||
|
||||
# Create agent using OpenAI Responses client
|
||||
client = OpenAIResponsesClient()
|
||||
# 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.",
|
||||
+6
-6
@@ -3,23 +3,23 @@
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Responses Client with File Search Example
|
||||
OpenAI Chat Client with File Search Example
|
||||
|
||||
This sample demonstrates using get_file_search_tool() with OpenAI Responses Client
|
||||
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: OpenAIResponsesClient) -> tuple[str, str]:
|
||||
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"
|
||||
@@ -35,14 +35,14 @@ async def create_vector_store(client: OpenAIResponsesClient) -> tuple[str, str]:
|
||||
return file.id, vector_store.id
|
||||
|
||||
|
||||
async def delete_vector_store(client: OpenAIResponsesClient, file_id: str, vector_store_id: str) -> None:
|
||||
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 = OpenAIResponsesClient()
|
||||
client = OpenAIChatClient()
|
||||
|
||||
message = "What is the weather today? Do a file search to find the answer."
|
||||
|
||||
+8
-8
@@ -4,7 +4,7 @@ import asyncio
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -14,10 +14,10 @@ if TYPE_CHECKING:
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Responses Client with Hosted MCP Example
|
||||
OpenAI Chat Client with Hosted MCP Example
|
||||
|
||||
This sample demonstrates integrating hosted Model Context Protocol (MCP) tools with
|
||||
OpenAI Responses Client, including user approval workflows for function call security.
|
||||
OpenAI Chat Client, including user approval workflows for function call security.
|
||||
"""
|
||||
|
||||
|
||||
@@ -102,7 +102,7 @@ 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 = OpenAIResponsesClient()
|
||||
client = OpenAIChatClient()
|
||||
# Create MCP tool with specific approval mode
|
||||
mcp_tool = client.get_mcp_tool(
|
||||
name="Microsoft Learn MCP",
|
||||
@@ -135,7 +135,7 @@ async def run_hosted_mcp_without_approval() -> None:
|
||||
"""Example showing Mcp Tools without approvals."""
|
||||
print("=== Mcp without approvals ===")
|
||||
|
||||
client = OpenAIResponsesClient()
|
||||
client = OpenAIChatClient()
|
||||
# Create MCP tool that never requires approval
|
||||
mcp_tool = client.get_mcp_tool(
|
||||
name="Microsoft Learn MCP",
|
||||
@@ -167,7 +167,7 @@ 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 = OpenAIResponsesClient()
|
||||
client = OpenAIChatClient()
|
||||
# Create MCP tool that always requires approval
|
||||
mcp_tool = client.get_mcp_tool(
|
||||
name="Microsoft Learn MCP",
|
||||
@@ -200,7 +200,7 @@ 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 = OpenAIResponsesClient()
|
||||
client = OpenAIChatClient()
|
||||
# Create MCP tool that always requires approval
|
||||
mcp_tool = client.get_mcp_tool(
|
||||
name="Microsoft Learn MCP",
|
||||
@@ -234,7 +234,7 @@ async def run_hosted_mcp_with_session_streaming() -> None:
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Responses Client Agent with Hosted Mcp Tools Examples ===\n")
|
||||
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()
|
||||
+6
-6
@@ -3,17 +3,17 @@
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Agent, MCPStreamableHTTPTool
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Responses Client with Local MCP Example
|
||||
OpenAI Chat Client with Local MCP Example
|
||||
|
||||
This sample demonstrates integrating local Model Context Protocol (MCP) tools with
|
||||
OpenAI Responses Client for direct response generation with external capabilities.
|
||||
OpenAI Chat Client for direct response generation with external capabilities.
|
||||
"""
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ async def streaming_with_mcp(show_raw_stream: bool = False) -> None:
|
||||
# Tools are provided when creating the agent
|
||||
# The agent can use these tools for any query during its lifetime
|
||||
async with Agent(
|
||||
client=OpenAIResponsesClient(),
|
||||
client=OpenAIChatClient(),
|
||||
name="DocsAgent",
|
||||
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
|
||||
tools=MCPStreamableHTTPTool( # Tools defined at agent creation
|
||||
@@ -65,7 +65,7 @@ async def run_with_mcp() -> None:
|
||||
# Tools are provided when creating the agent
|
||||
# The agent can use these tools for any query during its lifetime
|
||||
async with Agent(
|
||||
client=OpenAIResponsesClient(),
|
||||
client=OpenAIChatClient(),
|
||||
name="DocsAgent",
|
||||
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
|
||||
tools=MCPStreamableHTTPTool( # Tools defined at agent creation
|
||||
@@ -87,7 +87,7 @@ async def run_with_mcp() -> None:
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Responses Client Agent with Function Tools Examples ===\n")
|
||||
print("=== OpenAI Chat Client Agent with Function Tools Examples ===\n")
|
||||
|
||||
await run_with_mcp()
|
||||
await streaming_with_mcp()
|
||||
+3
-3
@@ -5,14 +5,14 @@ import subprocess
|
||||
from typing import Any
|
||||
|
||||
from agent_framework import Agent, Message, tool
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Responses Client with Local Shell Tool Example
|
||||
OpenAI Chat Client with Local Shell Tool Example
|
||||
|
||||
This sample demonstrates implementing a local shell tool using get_shell_tool(func=...)
|
||||
that wraps Python's subprocess module. Unlike the hosted shell tool (get_shell_tool()),
|
||||
@@ -53,7 +53,7 @@ async def main() -> None:
|
||||
print("=== OpenAI Agent with Local Shell Tool Example ===")
|
||||
print("NOTE: Commands will execute on your local machine.\n")
|
||||
|
||||
client = OpenAIResponsesClient()
|
||||
client = OpenAIChatClient()
|
||||
local_shell_tool = client.get_shell_tool(
|
||||
func=run_bash,
|
||||
)
|
||||
+2
-2
@@ -4,7 +4,7 @@ import asyncio
|
||||
import json
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.openai import OpenAIChatClient, OpenAIChatOptions
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
@@ -38,7 +38,7 @@ async def non_streaming_example() -> None:
|
||||
print("=== Non-streaming runtime JSON schema example ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient[OpenAIChatOptions](),
|
||||
client=OpenAIChatClient(),
|
||||
name="RuntimeSchemaAgent",
|
||||
instructions="Return only JSON that matches the provided schema. Do not add commentary.",
|
||||
)
|
||||
+7
-7
@@ -5,7 +5,7 @@ from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import Agent, AgentSession, tool
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
@@ -13,9 +13,9 @@ from pydantic import Field
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Responses Client with Session Management Example
|
||||
OpenAI Chat Client with Session Management Example
|
||||
|
||||
This sample demonstrates session management with OpenAI Responses Client, showing
|
||||
This sample demonstrates session management with OpenAI Chat Client, showing
|
||||
persistent conversation context and simplified response handling.
|
||||
"""
|
||||
|
||||
@@ -37,7 +37,7 @@ async def example_with_automatic_session_creation() -> None:
|
||||
print("=== Automatic Session Creation Example ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIResponsesClient(),
|
||||
client=OpenAIChatClient(),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
@@ -64,7 +64,7 @@ async def example_with_session_persistence_in_memory() -> None:
|
||||
print("=== Session Persistence Example (In-Memory) ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIResponsesClient(),
|
||||
client=OpenAIChatClient(),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
@@ -103,7 +103,7 @@ async def example_with_existing_session_id() -> None:
|
||||
existing_session_id = None
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIResponsesClient(),
|
||||
client=OpenAIChatClient(),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
@@ -124,7 +124,7 @@ async def example_with_existing_session_id() -> None:
|
||||
print("\n--- Continuing with the same session ID in a new agent instance ---")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIResponsesClient(),
|
||||
client=OpenAIChatClient(),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
+6
-6
@@ -3,16 +3,16 @@
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Responses Client with Shell Tool Example
|
||||
OpenAI Chat Client with Shell Tool Example
|
||||
|
||||
This sample demonstrates using get_shell_tool() with OpenAI Responses Client
|
||||
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,
|
||||
@@ -21,10 +21,10 @@ or performing system operations within a secure, sandboxed container.
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Example showing how to use the shell tool with OpenAI Responses."""
|
||||
print("=== OpenAI Responses Agent with Shell Tool Example ===")
|
||||
"""Example showing how to use the shell tool with OpenAI Chat."""
|
||||
print("=== OpenAI Chat Client Agent with Shell Tool Example ===")
|
||||
|
||||
client = OpenAIResponsesClient()
|
||||
client = OpenAIChatClient()
|
||||
|
||||
# Create a hosted shell tool with the default auto container environment
|
||||
shell_tool = client.get_shell_tool()
|
||||
+8
-8
@@ -3,7 +3,7 @@
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Agent, AgentResponse
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import BaseModel
|
||||
|
||||
@@ -11,9 +11,9 @@ from pydantic import BaseModel
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Responses Client with Structured Output Example
|
||||
OpenAI Chat Client with Structured Output Example
|
||||
|
||||
This sample demonstrates using structured output capabilities with OpenAI Responses Client,
|
||||
This sample demonstrates using structured output capabilities with OpenAI Chat Client,
|
||||
showing Pydantic model integration for type-safe response parsing and data extraction.
|
||||
"""
|
||||
|
||||
@@ -28,9 +28,9 @@ class OutputStruct(BaseModel):
|
||||
async def non_streaming_example() -> None:
|
||||
print("=== Non-streaming example ===")
|
||||
|
||||
# Create an OpenAI Responses agent
|
||||
# Create an OpenAI Chat agent
|
||||
agent = Agent(
|
||||
client=OpenAIResponsesClient(),
|
||||
client=OpenAIChatClient(),
|
||||
name="CityAgent",
|
||||
instructions="You are a helpful agent that describes cities in a structured format.",
|
||||
)
|
||||
@@ -54,9 +54,9 @@ async def non_streaming_example() -> None:
|
||||
async def streaming_example() -> None:
|
||||
print("=== Streaming example ===")
|
||||
|
||||
# Create an OpenAI Responses agent
|
||||
# Create an OpenAI Chat agent
|
||||
agent = Agent(
|
||||
client=OpenAIResponsesClient(),
|
||||
client=OpenAIChatClient(),
|
||||
name="CityAgent",
|
||||
instructions="You are a helpful agent that describes cities in a structured format.",
|
||||
)
|
||||
@@ -82,7 +82,7 @@ async def streaming_example() -> None:
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Responses Agent with Structured Output ===")
|
||||
print("=== OpenAI Chat Client Agent with Structured Output ===")
|
||||
|
||||
await non_streaming_example()
|
||||
await streaming_example()
|
||||
+4
-4
@@ -3,22 +3,22 @@
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Responses Client with Web Search Example
|
||||
OpenAI Chat Client with Web Search Example
|
||||
|
||||
This sample demonstrates using get_web_search_tool() with OpenAI Responses Client
|
||||
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 = OpenAIResponsesClient()
|
||||
client = OpenAIChatClient()
|
||||
|
||||
# Create web search tool with location context
|
||||
web_search_tool = client.get_web_search_tool(
|
||||
@@ -1,98 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import tool
|
||||
from agent_framework.openai import OpenAIAssistantProvider
|
||||
from dotenv import load_dotenv
|
||||
from openai import AsyncOpenAI
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Assistants Basic Example
|
||||
|
||||
This sample demonstrates basic usage of OpenAIAssistantProvider with automatic
|
||||
assistant lifecycle management, showing both streaming and non-streaming responses.
|
||||
"""
|
||||
|
||||
|
||||
# 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 non_streaming_example() -> None:
|
||||
"""Example of non-streaming response (get the complete result at once)."""
|
||||
print("=== Non-streaming Response Example ===")
|
||||
|
||||
client = AsyncOpenAI()
|
||||
provider = OpenAIAssistantProvider(client)
|
||||
|
||||
# Create a new assistant via the provider
|
||||
agent = await provider.create_agent(
|
||||
name="WeatherAssistant",
|
||||
model=os.environ.get("OPENAI_MODEL", "gpt-4"),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=[get_weather],
|
||||
)
|
||||
|
||||
try:
|
||||
query = "What's the weather like in Seattle?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
finally:
|
||||
# Clean up the assistant from OpenAI
|
||||
await client.beta.assistants.delete(agent.id)
|
||||
|
||||
|
||||
async def streaming_example() -> None:
|
||||
"""Example of streaming response (get results as they are generated)."""
|
||||
print("=== Streaming Response Example ===")
|
||||
|
||||
client = AsyncOpenAI()
|
||||
provider = OpenAIAssistantProvider(client)
|
||||
|
||||
# Create a new assistant via the provider
|
||||
agent = await provider.create_agent(
|
||||
name="WeatherAssistant",
|
||||
model=os.environ.get("OPENAI_MODEL", "gpt-4"),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=[get_weather],
|
||||
)
|
||||
|
||||
try:
|
||||
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")
|
||||
finally:
|
||||
# Clean up the assistant from OpenAI
|
||||
await client.beta.assistants.delete(agent.id)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== Basic OpenAI Assistants Provider Example ===")
|
||||
|
||||
await non_streaming_example()
|
||||
await streaming_example()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,158 +0,0 @@
|
||||
# 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 OpenAIAssistantProvider
|
||||
from dotenv import load_dotenv
|
||||
from openai import AsyncOpenAI
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Assistant Provider Methods Example
|
||||
|
||||
This sample demonstrates the methods available on the OpenAIAssistantProvider class:
|
||||
- create_agent(): Create a new assistant on the service
|
||||
- get_agent(): Retrieve an existing assistant by ID
|
||||
- as_agent(): Wrap an SDK Assistant object without making HTTP calls
|
||||
"""
|
||||
|
||||
|
||||
# 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 create_agent_example() -> None:
|
||||
"""Create a new assistant using provider.create_agent()."""
|
||||
print("\n--- create_agent() ---")
|
||||
|
||||
async with (
|
||||
AsyncOpenAI() as client,
|
||||
OpenAIAssistantProvider(client) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="WeatherAssistant",
|
||||
model=os.environ.get("OPENAI_MODEL", "gpt-4"),
|
||||
instructions="You are a helpful weather assistant.",
|
||||
tools=[get_weather],
|
||||
)
|
||||
|
||||
try:
|
||||
print(f"Created: {agent.name} (ID: {agent.id})")
|
||||
result = await agent.run("What's the weather in Seattle?")
|
||||
print(f"Response: {result}")
|
||||
finally:
|
||||
await client.beta.assistants.delete(agent.id)
|
||||
|
||||
|
||||
async def get_agent_example() -> None:
|
||||
"""Retrieve an existing assistant by ID using provider.get_agent()."""
|
||||
print("\n--- get_agent() ---")
|
||||
|
||||
async with (
|
||||
AsyncOpenAI() as client,
|
||||
OpenAIAssistantProvider(client) as provider,
|
||||
):
|
||||
# Create an assistant directly with SDK (simulating pre-existing assistant)
|
||||
sdk_assistant = await client.beta.assistants.create(
|
||||
model=os.environ.get("OPENAI_MODEL", "gpt-4"),
|
||||
name="ExistingAssistant",
|
||||
instructions="You always respond with 'Hello!'",
|
||||
)
|
||||
|
||||
try:
|
||||
# Retrieve using provider
|
||||
agent = await provider.get_agent(sdk_assistant.id)
|
||||
print(f"Retrieved: {agent.name} (ID: {agent.id})")
|
||||
|
||||
result = await agent.run("Hi there!")
|
||||
print(f"Response: {result}")
|
||||
finally:
|
||||
await client.beta.assistants.delete(sdk_assistant.id)
|
||||
|
||||
|
||||
async def as_agent_example() -> None:
|
||||
"""Wrap an SDK Assistant object using Agent(client=provider, ...)."""
|
||||
print("\n--- as_agent() ---")
|
||||
|
||||
async with (
|
||||
AsyncOpenAI() as client,
|
||||
OpenAIAssistantProvider(client) as provider,
|
||||
):
|
||||
# Create assistant using SDK
|
||||
sdk_assistant = await client.beta.assistants.create(
|
||||
model=os.environ.get("OPENAI_MODEL", "gpt-4"),
|
||||
name="WrappedAssistant",
|
||||
instructions="You respond with poetry.",
|
||||
)
|
||||
|
||||
try:
|
||||
# Wrap synchronously (no HTTP call)
|
||||
agent = Agent(client=provider, agent=sdk_assistant)
|
||||
print(f"Wrapped: {agent.name} (ID: {agent.id})")
|
||||
|
||||
result = await agent.run("Tell me about the sunset.")
|
||||
print(f"Response: {result}")
|
||||
finally:
|
||||
await client.beta.assistants.delete(sdk_assistant.id)
|
||||
|
||||
|
||||
async def multiple_agents_example() -> None:
|
||||
"""Create and manage multiple assistants with a single provider."""
|
||||
print("\n--- Multiple Agents ---")
|
||||
|
||||
async with (
|
||||
AsyncOpenAI() as client,
|
||||
OpenAIAssistantProvider(client) as provider,
|
||||
):
|
||||
weather_agent = await provider.create_agent(
|
||||
name="WeatherSpecialist",
|
||||
model=os.environ.get("OPENAI_MODEL", "gpt-4"),
|
||||
instructions="You are a weather specialist.",
|
||||
tools=[get_weather],
|
||||
)
|
||||
|
||||
greeter_agent = await provider.create_agent(
|
||||
name="GreeterAgent",
|
||||
model=os.environ.get("OPENAI_MODEL", "gpt-4"),
|
||||
instructions="You are a friendly greeter.",
|
||||
)
|
||||
|
||||
try:
|
||||
print(f"Created: {weather_agent.name}, {greeter_agent.name}")
|
||||
|
||||
greeting = await greeter_agent.run("Hello!")
|
||||
print(f"Greeter: {greeting}")
|
||||
|
||||
weather = await weather_agent.run("What's the weather in Tokyo?")
|
||||
print(f"Weather: {weather}")
|
||||
finally:
|
||||
await client.beta.assistants.delete(weather_agent.id)
|
||||
await client.beta.assistants.delete(greeter_agent.id)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("OpenAI Assistant Provider Methods")
|
||||
|
||||
await create_agent_example()
|
||||
await get_agent_example()
|
||||
await as_agent_example()
|
||||
await multiple_agents_example()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,81 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework import AgentResponseUpdate, ChatResponseUpdate
|
||||
from agent_framework.openai import OpenAIAssistantProvider, OpenAIAssistantsClient
|
||||
from dotenv import load_dotenv
|
||||
from openai import AsyncOpenAI
|
||||
from openai.types.beta.threads.runs import (
|
||||
CodeInterpreterToolCallDelta,
|
||||
RunStepDelta,
|
||||
RunStepDeltaEvent,
|
||||
ToolCallDeltaObject,
|
||||
)
|
||||
from openai.types.beta.threads.runs.code_interpreter_tool_call_delta import CodeInterpreter
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Assistants with Code Interpreter Example
|
||||
|
||||
This sample demonstrates using get_code_interpreter_tool() with OpenAI Assistants
|
||||
for Python code execution and mathematical problem solving.
|
||||
"""
|
||||
|
||||
|
||||
def get_code_interpreter_chunk(chunk: AgentResponseUpdate) -> str | None:
|
||||
"""Helper method to access code interpreter data."""
|
||||
if (
|
||||
isinstance(chunk.raw_representation, ChatResponseUpdate)
|
||||
and isinstance(chunk.raw_representation.raw_representation, RunStepDeltaEvent)
|
||||
and isinstance(chunk.raw_representation.raw_representation.delta, RunStepDelta)
|
||||
and isinstance(chunk.raw_representation.raw_representation.delta.step_details, ToolCallDeltaObject)
|
||||
and chunk.raw_representation.raw_representation.delta.step_details.tool_calls
|
||||
):
|
||||
for tool_call in chunk.raw_representation.raw_representation.delta.step_details.tool_calls:
|
||||
if (
|
||||
isinstance(tool_call, CodeInterpreterToolCallDelta)
|
||||
and isinstance(tool_call.code_interpreter, CodeInterpreter)
|
||||
and tool_call.code_interpreter.input is not None
|
||||
):
|
||||
return tool_call.code_interpreter.input
|
||||
return None
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Example showing how to use the code interpreter tool with OpenAI Assistants."""
|
||||
print("=== OpenAI Assistants Provider with Code Interpreter Example ===")
|
||||
|
||||
client = AsyncOpenAI()
|
||||
provider = OpenAIAssistantProvider(client)
|
||||
chat_client = OpenAIAssistantsClient(client=client)
|
||||
|
||||
agent = await provider.create_agent(
|
||||
name="CodeHelper",
|
||||
model=os.environ.get("OPENAI_MODEL", "gpt-4"),
|
||||
instructions="You are a helpful assistant that can write and execute Python code to solve problems.",
|
||||
tools=[chat_client.get_code_interpreter_tool()],
|
||||
)
|
||||
|
||||
try:
|
||||
query = "Use code to get the factorial of 100?"
|
||||
print(f"User: {query}")
|
||||
print("Agent: ", end="", flush=True)
|
||||
generated_code = ""
|
||||
async for chunk in agent.run(query, stream=True):
|
||||
if chunk.text:
|
||||
print(chunk.text, end="", flush=True)
|
||||
code_interpreter_chunk = get_code_interpreter_chunk(chunk)
|
||||
if code_interpreter_chunk is not None:
|
||||
generated_code += code_interpreter_chunk
|
||||
|
||||
print(f"\nGenerated code:\n{generated_code}")
|
||||
finally:
|
||||
await client.beta.assistants.delete(agent.id)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
-118
@@ -1,118 +0,0 @@
|
||||
# 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 OpenAIAssistantProvider
|
||||
from dotenv import load_dotenv
|
||||
from openai import AsyncOpenAI
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Assistants with Existing Assistant Example
|
||||
|
||||
This sample demonstrates working with pre-existing OpenAI Assistants
|
||||
using the provider's get_agent() and as_agent() methods.
|
||||
"""
|
||||
|
||||
|
||||
# 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_get_agent_by_id() -> None:
|
||||
"""Example: Using get_agent() to retrieve an existing assistant by ID."""
|
||||
print("=== Get Existing Assistant by ID ===")
|
||||
|
||||
client = AsyncOpenAI()
|
||||
provider = OpenAIAssistantProvider(client)
|
||||
|
||||
# Create an assistant via SDK (simulating an existing assistant)
|
||||
created_assistant = await client.beta.assistants.create(
|
||||
model=os.environ.get("OPENAI_MODEL", "gpt-4"),
|
||||
name="WeatherAssistant",
|
||||
tools=[
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"description": "Get the weather for a given location.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"location": {"type": "string", "description": "The location"}},
|
||||
"required": ["location"],
|
||||
},
|
||||
},
|
||||
}
|
||||
],
|
||||
)
|
||||
print(f"Created assistant: {created_assistant.id}")
|
||||
|
||||
try:
|
||||
# Use get_agent() to retrieve the existing assistant
|
||||
agent = await provider.get_agent(
|
||||
assistant_id=created_assistant.id,
|
||||
tools=[get_weather], # Required: implementation for function tools
|
||||
instructions="You are a helpful weather agent.",
|
||||
)
|
||||
|
||||
result = await agent.run("What's the weather like in Tokyo?")
|
||||
print(f"Agent: {result}\n")
|
||||
finally:
|
||||
await client.beta.assistants.delete(created_assistant.id)
|
||||
print("Assistant deleted.\n")
|
||||
|
||||
|
||||
async def example_as_agent_wrap_sdk_object() -> None:
|
||||
"""Example: Using as_agent() to wrap an existing SDK Assistant object."""
|
||||
print("=== Wrap Existing SDK Assistant Object ===")
|
||||
|
||||
client = AsyncOpenAI()
|
||||
provider = OpenAIAssistantProvider(client)
|
||||
|
||||
# Create and fetch an assistant via SDK
|
||||
created_assistant = await client.beta.assistants.create(
|
||||
model=os.environ.get("OPENAI_MODEL", "gpt-4"),
|
||||
name="SimpleAssistant",
|
||||
instructions="You are a friendly assistant.",
|
||||
)
|
||||
print(f"Created assistant: {created_assistant.id}")
|
||||
|
||||
try:
|
||||
# Use as_agent() to wrap the SDK object
|
||||
agent = Agent(
|
||||
client=provider,
|
||||
agent=created_assistant,
|
||||
instructions="You are an extremely helpful assistant. Be enthusiastic!",
|
||||
)
|
||||
|
||||
result = await agent.run("Hello! What can you help me with?")
|
||||
print(f"Agent: {result}\n")
|
||||
finally:
|
||||
await client.beta.assistants.delete(created_assistant.id)
|
||||
print("Assistant deleted.\n")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Assistants Provider with Existing Assistant Examples ===\n")
|
||||
|
||||
await example_get_agent_by_id()
|
||||
await example_as_agent_wrap_sdk_object()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,61 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import tool
|
||||
from agent_framework.openai import OpenAIAssistantProvider
|
||||
from dotenv import load_dotenv
|
||||
from openai import AsyncOpenAI
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Assistants with Explicit Settings Example
|
||||
|
||||
This sample demonstrates creating OpenAI Assistants 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 Assistants Provider with Explicit Settings ===")
|
||||
|
||||
# Create client with explicit API key
|
||||
client = AsyncOpenAI(api_key=os.environ["OPENAI_API_KEY"])
|
||||
provider = OpenAIAssistantProvider(client)
|
||||
|
||||
agent = await provider.create_agent(
|
||||
name="WeatherAssistant",
|
||||
model=os.environ["OPENAI_MODEL"],
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=[get_weather],
|
||||
)
|
||||
|
||||
try:
|
||||
query = "What's the weather like in New York?"
|
||||
print(f"Query: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Result: {result}\n")
|
||||
finally:
|
||||
await client.beta.assistants.delete(agent.id)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,78 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework import Content
|
||||
from agent_framework.openai import OpenAIAssistantProvider, OpenAIAssistantsClient
|
||||
from dotenv import load_dotenv
|
||||
from openai import AsyncOpenAI
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Assistants with File Search Example
|
||||
|
||||
This sample demonstrates using get_file_search_tool() with OpenAI Assistants
|
||||
for document-based question answering and information retrieval.
|
||||
"""
|
||||
|
||||
|
||||
async def create_vector_store(client: AsyncOpenAI) -> tuple[str, Content]:
|
||||
"""Create a vector store with sample documents."""
|
||||
file = await 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.vector_stores.create(
|
||||
name="knowledge_base",
|
||||
expires_after={"anchor": "last_active_at", "days": 1},
|
||||
)
|
||||
result = await 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, Content.from_hosted_vector_store(vector_store_id=vector_store.id)
|
||||
|
||||
|
||||
async def delete_vector_store(client: AsyncOpenAI, file_id: str, vector_store_id: str) -> None:
|
||||
"""Delete the vector store after using it."""
|
||||
await client.vector_stores.delete(vector_store_id=vector_store_id)
|
||||
await client.files.delete(file_id=file_id)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Assistants Provider with File Search Example ===\n")
|
||||
|
||||
client = AsyncOpenAI()
|
||||
provider = OpenAIAssistantProvider(client)
|
||||
chat_client = OpenAIAssistantsClient(client=client)
|
||||
|
||||
agent = await provider.create_agent(
|
||||
name="SearchAssistant",
|
||||
model=os.environ.get("OPENAI_MODEL", "gpt-4"),
|
||||
instructions="You are a helpful assistant that searches files in a knowledge base.",
|
||||
tools=[chat_client.get_file_search_tool()],
|
||||
)
|
||||
|
||||
try:
|
||||
query = "What is the weather today? Do a file search to find the answer."
|
||||
file_id, vector_store_content = await create_vector_store(client)
|
||||
|
||||
print(f"User: {query}")
|
||||
print("Agent: ", end="", flush=True)
|
||||
async for chunk in agent.run(
|
||||
query,
|
||||
stream=True,
|
||||
options={"tool_resources": {"file_search": {"vector_store_ids": [vector_store_content.vector_store_id]}}},
|
||||
):
|
||||
if chunk.text:
|
||||
print(chunk.text, end="", flush=True)
|
||||
|
||||
await delete_vector_store(client, file_id, vector_store_content.vector_store_id)
|
||||
finally:
|
||||
await client.beta.assistants.delete(agent.id)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,159 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import tool
|
||||
from agent_framework.openai import OpenAIAssistantProvider
|
||||
from dotenv import load_dotenv
|
||||
from openai import AsyncOpenAI
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Assistants with Function Tools Example
|
||||
|
||||
This sample demonstrates function tool integration with OpenAI Assistants,
|
||||
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 ===")
|
||||
|
||||
client = AsyncOpenAI()
|
||||
provider = OpenAIAssistantProvider(client)
|
||||
|
||||
# Tools are provided when creating the agent
|
||||
# The agent can use these tools for any query during its lifetime
|
||||
agent = await provider.create_agent(
|
||||
name="InfoAssistant",
|
||||
model=os.environ.get("OPENAI_MODEL", "gpt-4"),
|
||||
instructions="You are a helpful assistant that can provide weather and time information.",
|
||||
tools=[get_weather, get_time], # Tools defined at agent creation
|
||||
)
|
||||
|
||||
try:
|
||||
# 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")
|
||||
finally:
|
||||
await client.beta.assistants.delete(agent.id)
|
||||
|
||||
|
||||
async def tools_on_run_level() -> None:
|
||||
"""Example showing tools passed to the run method."""
|
||||
print("=== Tools Passed to Run Method ===")
|
||||
|
||||
client = AsyncOpenAI()
|
||||
provider = OpenAIAssistantProvider(client)
|
||||
|
||||
# Agent created with base tools, additional tools can be passed at run time
|
||||
agent = await provider.create_agent(
|
||||
name="FlexibleAssistant",
|
||||
model=os.environ.get("OPENAI_MODEL", "gpt-4"),
|
||||
instructions="You are a helpful assistant.",
|
||||
tools=[get_weather], # Base tool
|
||||
)
|
||||
|
||||
try:
|
||||
# First query using base weather tool
|
||||
query1 = "What's the weather like in Seattle?"
|
||||
print(f"User: {query1}")
|
||||
result1 = await agent.run(query1)
|
||||
print(f"Agent: {result1}\n")
|
||||
|
||||
# Second query with additional time tool
|
||||
query2 = "What's the current UTC time?"
|
||||
print(f"User: {query2}")
|
||||
result2 = await agent.run(query2, tools=[get_time]) # Additional tool for this query
|
||||
print(f"Agent: {result2}\n")
|
||||
|
||||
# Third query with both 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_time]) # Time tool adds to weather
|
||||
print(f"Agent: {result3}\n")
|
||||
finally:
|
||||
await client.beta.assistants.delete(agent.id)
|
||||
|
||||
|
||||
async def mixed_tools_example() -> None:
|
||||
"""Example showing both agent-level tools and run-method tools."""
|
||||
print("=== Mixed Tools Example (Agent + Run Method) ===")
|
||||
|
||||
client = AsyncOpenAI()
|
||||
provider = OpenAIAssistantProvider(client)
|
||||
|
||||
# Agent created with some base tools
|
||||
agent = await provider.create_agent(
|
||||
name="ComprehensiveAssistant",
|
||||
model=os.environ.get("OPENAI_MODEL", "gpt-4"),
|
||||
instructions="You are a comprehensive assistant that can help with various information requests.",
|
||||
tools=[get_weather], # Base tool available for all queries
|
||||
)
|
||||
|
||||
try:
|
||||
# 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")
|
||||
finally:
|
||||
await client.beta.assistants.delete(agent.id)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Assistants Provider 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())
|
||||
@@ -1,96 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.openai import OpenAIAssistantProvider
|
||||
from dotenv import load_dotenv
|
||||
from openai import AsyncOpenAI
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Assistant Provider Response Format Example
|
||||
|
||||
This sample demonstrates using OpenAIAssistantProvider with response_format
|
||||
for structured outputs in two ways:
|
||||
1. Setting default response_format at agent creation time (default_options)
|
||||
2. Overriding response_format at runtime (options parameter in agent.run)
|
||||
"""
|
||||
|
||||
|
||||
class WeatherInfo(BaseModel):
|
||||
"""Structured weather information."""
|
||||
|
||||
location: str
|
||||
temperature: int
|
||||
conditions: str
|
||||
recommendation: str
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
class CityInfo(BaseModel):
|
||||
"""Structured city information."""
|
||||
|
||||
city_name: str
|
||||
population: int
|
||||
country: str
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Example of using response_format at creation time and runtime."""
|
||||
|
||||
async with (
|
||||
AsyncOpenAI() as client,
|
||||
OpenAIAssistantProvider(client) as provider,
|
||||
):
|
||||
# Create agent with default response_format (WeatherInfo)
|
||||
agent = await provider.create_agent(
|
||||
name="StructuredReporter",
|
||||
model=os.environ.get("OPENAI_MODEL", "gpt-4"),
|
||||
instructions="Return structured JSON based on the requested format.",
|
||||
default_options={"response_format": WeatherInfo},
|
||||
)
|
||||
|
||||
try:
|
||||
# Request 1: Uses default response_format from agent creation
|
||||
print("--- Request 1: Using default response_format (WeatherInfo) ---")
|
||||
query1 = "What's the weather like in Paris today?"
|
||||
print(f"User: {query1}")
|
||||
|
||||
result1 = await agent.run(query1)
|
||||
|
||||
try:
|
||||
weather = result1.value
|
||||
print("Agent:")
|
||||
print(f" Location: {weather.location}")
|
||||
print(f" Temperature: {weather.temperature}")
|
||||
print(f" Conditions: {weather.conditions}")
|
||||
print(f" Recommendation: {weather.recommendation}")
|
||||
except Exception:
|
||||
print(f"Failed to parse response: {result1.text}")
|
||||
|
||||
# Request 2: Override response_format at runtime with CityInfo
|
||||
print("\n--- Request 2: Runtime override with CityInfo ---")
|
||||
query2 = "Tell me about Tokyo."
|
||||
print(f"User: {query2}")
|
||||
|
||||
result2 = await agent.run(query2, options={"response_format": CityInfo})
|
||||
|
||||
try:
|
||||
city = result2.value
|
||||
print("Agent:")
|
||||
print(f" City: {city.city_name}")
|
||||
print(f" Population: {city.population}")
|
||||
print(f" Country: {city.country}")
|
||||
except Exception:
|
||||
print(f"Failed to parse response: {result2.text}")
|
||||
finally:
|
||||
await client.beta.assistants.delete(agent.id)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,172 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import AgentSession, tool
|
||||
from agent_framework.openai import OpenAIAssistantProvider
|
||||
from dotenv import load_dotenv
|
||||
from openai import AsyncOpenAI
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Assistants with Session Management Example
|
||||
|
||||
This sample demonstrates session management with OpenAI Assistants, showing
|
||||
persistent conversation sessions and context 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 ===")
|
||||
|
||||
client = AsyncOpenAI()
|
||||
provider = OpenAIAssistantProvider(client)
|
||||
|
||||
agent = await provider.create_agent(
|
||||
name="WeatherAssistant",
|
||||
model=os.environ.get("OPENAI_MODEL", "gpt-4"),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=[get_weather],
|
||||
)
|
||||
|
||||
try:
|
||||
# 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")
|
||||
finally:
|
||||
await client.beta.assistants.delete(agent.id)
|
||||
|
||||
|
||||
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")
|
||||
|
||||
client = AsyncOpenAI()
|
||||
provider = OpenAIAssistantProvider(client)
|
||||
|
||||
agent = await provider.create_agent(
|
||||
name="WeatherAssistant",
|
||||
model=os.environ.get("OPENAI_MODEL", "gpt-4"),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=[get_weather],
|
||||
)
|
||||
|
||||
try:
|
||||
# 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")
|
||||
finally:
|
||||
await client.beta.assistants.delete(agent.id)
|
||||
|
||||
|
||||
async def example_with_existing_session_id() -> None:
|
||||
"""Example showing how to work with an existing session ID from the service."""
|
||||
print("=== Existing Session ID Example ===")
|
||||
print("Using a specific session ID to continue an existing conversation.\n")
|
||||
|
||||
client = AsyncOpenAI()
|
||||
provider = OpenAIAssistantProvider(client)
|
||||
|
||||
# First, create a conversation and capture the session ID
|
||||
existing_session_id = None
|
||||
assistant_id = None
|
||||
|
||||
agent = await provider.create_agent(
|
||||
name="WeatherAssistant",
|
||||
model=os.environ.get("OPENAI_MODEL", "gpt-4"),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=[get_weather],
|
||||
)
|
||||
assistant_id = agent.id
|
||||
|
||||
try:
|
||||
# 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 using get_agent ---")
|
||||
|
||||
# Get the existing assistant by ID
|
||||
agent2 = await provider.get_agent(
|
||||
assistant_id=assistant_id,
|
||||
tools=[get_weather], # Must provide function implementations
|
||||
)
|
||||
|
||||
# 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 agent2.run(query2, session=session)
|
||||
print(f"Agent: {result2.text}")
|
||||
print("Note: The agent continues the conversation from the previous session.\n")
|
||||
finally:
|
||||
if assistant_id:
|
||||
await client.beta.assistants.delete(assistant_id)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== OpenAI Assistants Provider Session Management Examples ===\n")
|
||||
|
||||
await example_with_automatic_session_creation()
|
||||
await example_with_session_persistence()
|
||||
await example_with_existing_session_id()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,132 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Awaitable, Callable
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import (
|
||||
Agent,
|
||||
ChatContext,
|
||||
ChatResponse,
|
||||
Message,
|
||||
MiddlewareTermination,
|
||||
Role,
|
||||
chat_middleware,
|
||||
tool,
|
||||
)
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
OpenAI Responses Client Basic Example
|
||||
|
||||
This sample demonstrates basic usage of OpenAIResponsesClient for structured
|
||||
response generation, showing both streaming and non-streaming responses.
|
||||
"""
|
||||
|
||||
|
||||
@chat_middleware
|
||||
async def security_and_override_middleware(
|
||||
context: ChatContext,
|
||||
call_next: Callable[[], Awaitable[None]],
|
||||
) -> None:
|
||||
"""Function-based middleware that implements security filtering and response override."""
|
||||
print("[SecurityMiddleware] Processing input...")
|
||||
|
||||
# Security check - block sensitive information
|
||||
blocked_terms = ["password", "secret", "api_key", "token"]
|
||||
|
||||
for message in context.messages:
|
||||
if message.text:
|
||||
message_lower = message.text.lower()
|
||||
for term in blocked_terms:
|
||||
if term in message_lower:
|
||||
print(f"[SecurityMiddleware] BLOCKED: Found '{term}' in message")
|
||||
|
||||
# Override the response instead of calling AI
|
||||
context.result = ChatResponse(
|
||||
messages=[
|
||||
Message(
|
||||
role=Role.ASSISTANT,
|
||||
text="I cannot process requests containing sensitive information. "
|
||||
"Please rephrase your question without including passwords, secrets, or other "
|
||||
"sensitive data.",
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
# Terminate middleware execution with the blocked response
|
||||
raise MiddlewareTermination(result=context.result)
|
||||
|
||||
# Continue to next middleware or AI execution
|
||||
await call_next()
|
||||
|
||||
print("[SecurityMiddleware] Response generated.")
|
||||
print(type(context.result))
|
||||
|
||||
|
||||
# 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 non_streaming_example() -> None:
|
||||
"""Example of non-streaming response (get the complete result at once)."""
|
||||
print("=== Non-streaming Response Example ===")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIResponsesClient(),
|
||||
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=OpenAIResponsesClient(
|
||||
middleware=[security_and_override_middleware],
|
||||
),
|
||||
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)
|
||||
response = agent.run(query, stream=True)
|
||||
async for chunk in response:
|
||||
if chunk.text:
|
||||
print(chunk.text, end="", flush=True)
|
||||
print("\n")
|
||||
print(f"Final Result: {await response.get_final_response()}")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== Basic OpenAI Responses Client Agent Example ===")
|
||||
|
||||
await streaming_example()
|
||||
await non_streaming_example()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,21 +1,20 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
"""Host multiple Foundry-powered agents inside a single Azure Functions app.
|
||||
"""Host multiple Azure OpenAI-powered agents inside a single Azure Functions app.
|
||||
|
||||
Components used in this sample:
|
||||
- FoundryChatClient to create agents bound to a shared Foundry deployment.
|
||||
- OpenAIChatCompletionClient configured for Azure OpenAI.
|
||||
- AgentFunctionApp to register multiple agents and expose dedicated HTTP endpoints.
|
||||
- Custom tool functions to demonstrate tool invocation from different agents.
|
||||
|
||||
Prerequisites: set `FOUNDRY_PROJECT_ENDPOINT`, `FOUNDRY_MODEL`, and sign in with Azure CLI before starting the Functions host."""
|
||||
Prerequisites: set `AZURE_OPENAI_ENDPOINT`, `AZURE_OPENAI_DEPLOYMENT_NAME`, and sign in with Azure CLI before starting the Functions host."""
|
||||
|
||||
import logging
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.azure import AgentFunctionApp
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from agent_framework.openai import OpenAIChatCompletionClient
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
@@ -60,9 +59,7 @@ def calculate_tip(bill_amount: float, tip_percentage: float = 15.0) -> dict[str,
|
||||
|
||||
|
||||
# 1. Create multiple agents, each with its own instruction set and tools.
|
||||
client = FoundryChatClient(
|
||||
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
|
||||
model=os.environ["FOUNDRY_MODEL"],
|
||||
client = OpenAIChatCompletionClient(
|
||||
credential=AzureCliCredential(),
|
||||
)
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ each with their own specialized capabilities and tools.
|
||||
|
||||
Prerequisites:
|
||||
- The worker must be running with both agents registered
|
||||
- Set FOUNDRY_PROJECT_ENDPOINT and FOUNDRY_MODEL
|
||||
- Set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_DEPLOYMENT_NAME when running the worker
|
||||
- Sign in with Azure CLI for AzureCliCredential authentication
|
||||
- Durable Task Scheduler must be running
|
||||
"""
|
||||
|
||||
@@ -5,7 +5,7 @@ This sample demonstrates running both the worker and client in a single process
|
||||
for multiple agents with different tools. The worker registers two agents
|
||||
(WeatherAgent and MathAgent), each with their own specialized capabilities.
|
||||
Prerequisites:
|
||||
- Set FOUNDRY_PROJECT_ENDPOINT and FOUNDRY_MODEL
|
||||
- Set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_DEPLOYMENT_NAME
|
||||
- Sign in with Azure CLI for AzureCliCredential authentication
|
||||
- Durable Task Scheduler must be running (e.g., using Docker)
|
||||
To run this sample:
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
"""Worker process for hosting multiple agents with different tools using Durable Task.
|
||||
"""Worker process for hosting multiple Azure OpenAI agents with different tools using Durable Task.
|
||||
|
||||
This worker registers two agents - a weather assistant and a math assistant - each
|
||||
with their own specialized tools. This demonstrates how to host multiple agents
|
||||
with different capabilities in a single worker process.
|
||||
|
||||
Prerequisites:
|
||||
- Set FOUNDRY_PROJECT_ENDPOINT and FOUNDRY_MODEL
|
||||
- Set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_DEPLOYMENT_NAME
|
||||
- Sign in with Azure CLI for AzureCliCredential authentication
|
||||
- Start a Durable Task Scheduler (e.g., using Docker)
|
||||
"""
|
||||
@@ -19,7 +19,7 @@ from typing import Any
|
||||
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.azure import DurableAIAgentWorker
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from agent_framework.openai import OpenAIChatCompletionClient
|
||||
from azure.identity import AzureCliCredential
|
||||
from azure.identity.aio import AzureCliCredential as AsyncAzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
@@ -73,13 +73,10 @@ def create_weather_agent():
|
||||
Returns:
|
||||
Agent: The configured Weather agent with weather tool
|
||||
"""
|
||||
_client = FoundryChatClient(
|
||||
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
|
||||
model=os.environ["FOUNDRY_MODEL"],
|
||||
credential=AsyncAzureCliCredential(),
|
||||
)
|
||||
return Agent(
|
||||
client=_client,
|
||||
client=OpenAIChatCompletionClient(
|
||||
credential=AsyncAzureCliCredential(),
|
||||
),
|
||||
name=WEATHER_AGENT_NAME,
|
||||
instructions="You are a helpful weather assistant. Provide current weather information.",
|
||||
tools=[get_weather],
|
||||
@@ -92,13 +89,10 @@ def create_math_agent():
|
||||
Returns:
|
||||
Agent: The configured Math agent with calculation tools
|
||||
"""
|
||||
_client = FoundryChatClient(
|
||||
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
|
||||
model=os.environ["FOUNDRY_MODEL"],
|
||||
credential=AsyncAzureCliCredential(),
|
||||
)
|
||||
return Agent(
|
||||
client=_client,
|
||||
client=OpenAIChatCompletionClient(
|
||||
credential=AsyncAzureCliCredential(),
|
||||
),
|
||||
name=MATH_AGENT_NAME,
|
||||
instructions="You are a helpful math assistant. Help users with calculations like tip calculations.",
|
||||
tools=[calculate_tip],
|
||||
|
||||
+5
-3
@@ -35,9 +35,9 @@ The backend uses Azure OpenAI responses and supports intent-driven, non-linear h
|
||||
From the Python repo root:
|
||||
|
||||
```bash
|
||||
cd /Users/evmattso/git/agent-framework/python
|
||||
cd python
|
||||
uv sync
|
||||
uv run python samples/demos/ag_ui_workflow_handoff/backend/server.py
|
||||
uv run python samples/05-end-to-end/ag_ui_workflow_handoff/backend/server.py
|
||||
```
|
||||
|
||||
Backend default URL:
|
||||
@@ -47,8 +47,10 @@ Backend default URL:
|
||||
|
||||
## 2) Install Frontend Packages (npm)
|
||||
|
||||
From the `python/` directory (where Step 1 left you):
|
||||
|
||||
```bash
|
||||
cd /Users/evmattso/git/agent-framework/python/samples/demos/ag_ui_workflow_handoff/frontend
|
||||
cd samples/05-end-to-end/ag_ui_workflow_handoff/frontend
|
||||
npm install
|
||||
```
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# dependencies
|
||||
/node_modules
|
||||
|
||||
# build artifacts
|
||||
*.tsbuildinfo
|
||||
vite.config.js
|
||||
vite.config.d.ts
|
||||
@@ -174,7 +174,7 @@ Overall Attack Success Rate: 7.2%
|
||||
- [Azure AI Evaluation SDK](https://learn.microsoft.com/azure/ai-foundry/how-to/develop/evaluate-sdk)
|
||||
- [Risk and Safety Evaluations](https://learn.microsoft.com/azure/ai-foundry/concepts/evaluation-metrics-built-in#risk-and-safety-evaluators)
|
||||
- [Azure AI Red Teaming Notebook](https://github.com/Azure-Samples/azureai-samples/blob/main/scenarios/evaluate/AI_RedTeaming/AI_RedTeaming.ipynb)
|
||||
- [PyRIT - Python Risk Identification Toolkit](https://github.com/Azure/PyRIT)
|
||||
- [PyRIT - Python Risk Identification Toolkit](https://github.com/microsoft/PyRIT)
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# OpenAI Configuration
|
||||
OPENAI_API_KEY=
|
||||
OPENAI_CHAT_MODEL_ID=
|
||||
OPENAI_CHAT_MODEL=
|
||||
|
||||
# Agent 365 Agentic Authentication Configuration
|
||||
USE_ANONYMOUS_MODE=
|
||||
|
||||
@@ -21,7 +21,7 @@ export USE_ANONYMOUS_MODE=True # set to false if using auth
|
||||
|
||||
# OpenAI
|
||||
export OPENAI_API_KEY="..."
|
||||
export OPENAI_CHAT_MODEL_ID="..."
|
||||
export OPENAI_CHAT_MODEL="..."
|
||||
```
|
||||
|
||||
## Installing Dependencies
|
||||
|
||||
@@ -61,6 +61,16 @@ client = OpenAIChatClient(env_file_path="path/to/custom.env")
|
||||
|
||||
This allows different clients to use different configuration files if needed.
|
||||
|
||||
For the generic OpenAI clients (`OpenAIChatClient` and `OpenAIChatCompletionClient`), routing
|
||||
precedence is:
|
||||
|
||||
1. Explicit Azure inputs such as `credential`, `azure_endpoint`, or `api_version`
|
||||
2. `OPENAI_API_KEY` / explicit OpenAI API-key parameters
|
||||
3. Azure environment fallback such as `AZURE_OPENAI_ENDPOINT` and `AZURE_OPENAI_API_KEY`
|
||||
|
||||
If you keep both OpenAI and Azure variables in your shell, the generic clients stay on OpenAI until
|
||||
you pass an explicit Azure input.
|
||||
|
||||
For the getting-started samples, you'll need at minimum:
|
||||
```bash
|
||||
FOUNDRY_PROJECT_ENDPOINT="your-foundry-project-endpoint"
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1 +0,0 @@
|
||||
{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts"],"version":"5.9.3"}
|
||||
@@ -1,2 +0,0 @@
|
||||
declare const _default: import("vite").UserConfig;
|
||||
export default _default;
|
||||
@@ -1,11 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
host: "127.0.0.1",
|
||||
port: 5173,
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user