mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
Python: [BREAKING] update to v1.0.0 (#5062)
* updates to final deprecated pieces and versions * fix mypy * fix readme links
This commit is contained in:
@@ -1,8 +1,9 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.anthropic import AnthropicChatOptions, AnthropicClient
|
||||
from agent_framework.anthropic import AnthropicClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
@@ -15,12 +16,20 @@ This sample demonstrates using Anthropic with:
|
||||
- Setting up an Anthropic-based agent with hosted tools.
|
||||
- Using the `thinking` feature.
|
||||
- Displaying both thinking and usage information during streaming responses.
|
||||
|
||||
Environment variables:
|
||||
ANTHROPIC_API_KEY — Your Anthropic API key
|
||||
ANTHROPIC_CHAT_MODEL — The Anthropic model to use (e.g., "claude-sonnet-4-6")
|
||||
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Example of streaming response (get results as they are generated)."""
|
||||
client = AnthropicClient[AnthropicChatOptions]()
|
||||
client = AnthropicClient(
|
||||
api_key=os.getenv("ANTHROPIC_API_KEY"),
|
||||
model=os.getenv("ANTHROPIC_CHAT_MODEL"),
|
||||
)
|
||||
|
||||
# Create MCP tool configuration using instance method
|
||||
mcp_tool = client.get_mcp_tool(
|
||||
|
||||
@@ -76,19 +76,19 @@ async def example_with_session_persistence_in_memory() -> None:
|
||||
# First conversation
|
||||
query1 = "What's the weather like in Tokyo?"
|
||||
print(f"User: {query1}")
|
||||
result1 = await agent.run(query1, session=session, store=False)
|
||||
result1 = await agent.run(query1, session=session, options={"store": False})
|
||||
print(f"Agent: {result1.text}")
|
||||
|
||||
# Second conversation using the same session - maintains context
|
||||
query2 = "How about London?"
|
||||
print(f"\nUser: {query2}")
|
||||
result2 = await agent.run(query2, session=session, store=False)
|
||||
result2 = await agent.run(query2, session=session, options={"store": False})
|
||||
print(f"Agent: {result2.text}")
|
||||
|
||||
# Third conversation - agent should remember both previous cities
|
||||
query3 = "Which of the cities I asked about has better weather?"
|
||||
print(f"\nUser: {query3}")
|
||||
result3 = await agent.run(query3, session=session, store=False)
|
||||
result3 = await agent.run(query3, session=session, options={"store": False})
|
||||
print(f"Agent: {result3.text}")
|
||||
print("Note: The agent remembers context from previous messages in the same session.\n")
|
||||
|
||||
@@ -114,7 +114,7 @@ async def example_with_existing_session_id() -> None:
|
||||
|
||||
query1 = "What's the weather in Paris?"
|
||||
print(f"User: {query1}")
|
||||
result1 = await agent.run(query1, session=session)
|
||||
result1 = await agent.run(query1, session=session, options={"store": False})
|
||||
print(f"Agent: {result1.text}")
|
||||
|
||||
# The session ID is set after the first response
|
||||
|
||||
@@ -9,7 +9,6 @@ This folder contains Azure AI Foundry and Foundry Local samples for Agent Framew
|
||||
| [`foundry_agent_basic.py`](foundry_agent_basic.py) | Foundry Agent basic example |
|
||||
| [`foundry_agent_custom_client.py`](foundry_agent_custom_client.py) | Foundry Agent custom client configuration |
|
||||
| [`foundry_agent_hosted.py`](foundry_agent_hosted.py) | Foundry Agent for hosted agents |
|
||||
| [`foundry_agent_with_env_vars.py`](foundry_agent_with_env_vars.py) | Foundry Agent using environment variables |
|
||||
| [`foundry_agent_with_function_tools.py`](foundry_agent_with_function_tools.py) | Foundry Agent with local function tools |
|
||||
|
||||
## FoundryChatClient Samples
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.foundry import FoundryAgent, RawFoundryAgentChatClient
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
"""
|
||||
Foundry Agent — Custom client configuration
|
||||
|
||||
@@ -25,9 +27,9 @@ Environment variables:
|
||||
async def main() -> None:
|
||||
# Option 1: Default — full middleware on both agent and client
|
||||
agent = FoundryAgent(
|
||||
project_endpoint="https://your-project.services.ai.azure.com",
|
||||
agent_name="my-agent",
|
||||
agent_version="1.0",
|
||||
project_endpoint=os.getenv("FOUNDRY_PROJECT_ENDPOINT"),
|
||||
agent_name=os.getenv("FOUNDRY_AGENT_NAME"),
|
||||
agent_version=os.getenv("FOUNDRY_AGENT_VERSION"),
|
||||
credential=AzureCliCredential(),
|
||||
)
|
||||
result = await agent.run("Hello from the default setup!")
|
||||
@@ -35,9 +37,9 @@ async def main() -> None:
|
||||
|
||||
# Option 2: Raw client — no client-level middleware (agent middleware still active)
|
||||
agent_raw_client = FoundryAgent(
|
||||
project_endpoint="https://your-project.services.ai.azure.com",
|
||||
agent_name="my-agent",
|
||||
agent_version="1.0",
|
||||
project_endpoint=os.getenv("FOUNDRY_PROJECT_ENDPOINT"),
|
||||
agent_name=os.getenv("FOUNDRY_AGENT_NAME"),
|
||||
agent_version=os.getenv("FOUNDRY_AGENT_VERSION"),
|
||||
credential=AzureCliCredential(),
|
||||
client_type=RawFoundryAgentChatClient,
|
||||
)
|
||||
@@ -47,9 +49,9 @@ async def main() -> None:
|
||||
# Option 3: Composition — use Agent(client=...) directly
|
||||
# this will not run the checks that the `FoundryAgent` does on things like tools.
|
||||
client = RawFoundryAgentChatClient(
|
||||
project_endpoint="https://your-project.services.ai.azure.com",
|
||||
agent_name="my-agent",
|
||||
agent_version="1.0",
|
||||
project_endpoint=os.getenv("FOUNDRY_PROJECT_ENDPOINT"),
|
||||
agent_name=os.getenv("FOUNDRY_AGENT_NAME"),
|
||||
agent_version=os.getenv("FOUNDRY_AGENT_VERSION"),
|
||||
credential=AzureCliCredential(),
|
||||
)
|
||||
agent_composed = Agent(client=client)
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.foundry import FoundryAgent
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Foundry Agent — Connect to a HostedAgent (no version needed)
|
||||
@@ -20,8 +24,8 @@ Environment variables:
|
||||
async def main() -> None:
|
||||
# HostedAgents don't need agent_version
|
||||
agent = FoundryAgent(
|
||||
project_endpoint="https://your-project.services.ai.azure.com",
|
||||
agent_name="my-hosted-agent",
|
||||
project_endpoint=os.getenv("FOUNDRY_PROJECT_ENDPOINT"),
|
||||
agent_name=os.getenv("FOUNDRY_AGENT_NAME"),
|
||||
credential=AzureCliCredential(),
|
||||
)
|
||||
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.foundry import FoundryAgent
|
||||
from azure.identity import AzureCliCredential
|
||||
|
||||
"""
|
||||
Foundry Agent with Environment Variables
|
||||
|
||||
This sample shows the recommended pattern for advanced samples that use
|
||||
environment variables for configuration.
|
||||
|
||||
Environment variables:
|
||||
FOUNDRY_PROJECT_ENDPOINT — Azure AI Foundry project endpoint
|
||||
FOUNDRY_AGENT_NAME — Name of the agent in Foundry
|
||||
FOUNDRY_AGENT_VERSION — Version of the agent (optional, for PromptAgents)
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
agent = FoundryAgent(
|
||||
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
|
||||
agent_name=os.environ["FOUNDRY_AGENT_NAME"],
|
||||
agent_version=os.environ.get("FOUNDRY_AGENT_VERSION"),
|
||||
credential=AzureCliCredential(),
|
||||
)
|
||||
|
||||
session = agent.create_session()
|
||||
|
||||
result = await agent.run("Hello! My name is Alice.", session=session)
|
||||
print(f"Agent: {result}\n")
|
||||
|
||||
result = await agent.run("What's my name?", session=session)
|
||||
print(f"Agent: {result}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,13 +1,14 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import tool
|
||||
from agent_framework.foundry import FoundryAgent
|
||||
from azure.identity import AzureCliCredential
|
||||
from pydantic import Field
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
"""
|
||||
Foundry Agent with Local Function Tools
|
||||
|
||||
@@ -25,9 +26,8 @@ Environment variables:
|
||||
"""
|
||||
|
||||
|
||||
@tool(approval_mode="never_require")
|
||||
def get_weather(
|
||||
location: Annotated[str, Field(description="The city to get weather for.")],
|
||||
location: Annotated[str, "The city to get weather for."],
|
||||
) -> str:
|
||||
"""Get the current weather for a location."""
|
||||
return f"The weather in {location} is sunny, 22°C."
|
||||
@@ -35,11 +35,11 @@ def get_weather(
|
||||
|
||||
async def main() -> None:
|
||||
agent = FoundryAgent(
|
||||
project_endpoint="https://your-project.services.ai.azure.com",
|
||||
agent_name="my-weather-agent",
|
||||
agent_version="1.0",
|
||||
project_endpoint=os.getenv("FOUNDRY_PROJECT_ENDPOINT"),
|
||||
agent_name=os.getenv("FOUNDRY_AGENT_NAME"),
|
||||
agent_version=os.getenv("FOUNDRY_AGENT_VERSION"),
|
||||
credential=AzureCliCredential(),
|
||||
tools=[get_weather],
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
result = await agent.run("What's the weather in Paris?")
|
||||
|
||||
+24
-31
@@ -8,9 +8,8 @@ from agent_framework import Agent
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from openai import AsyncAzureOpenAI
|
||||
from openai import AsyncOpenAI
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
@@ -18,12 +17,16 @@ Foundry Chat Client with Code Interpreter and Files Example
|
||||
|
||||
This sample demonstrates using get_code_interpreter_tool() with Responses on Foundry
|
||||
for Python code execution and data analysis with uploaded files.
|
||||
|
||||
Environment variables:
|
||||
FOUNDRY_PROJECT_ENDPOINT — Foundry project endpoint
|
||||
FOUNDRY_MODEL — Foundry model to use (e.g. "gpt-4o-mini")
|
||||
"""
|
||||
|
||||
# Helper functions
|
||||
|
||||
|
||||
async def create_sample_file_and_upload(openai_client: AsyncAzureOpenAI) -> tuple[str, str]:
|
||||
async def create_sample_file_and_upload(openai_client: AsyncOpenAI) -> tuple[str, str]:
|
||||
"""Create a sample CSV file and upload it for Foundry code interpreter use."""
|
||||
csv_data = """name,department,salary,years_experience
|
||||
Alice Johnson,Engineering,95000,5
|
||||
@@ -51,7 +54,7 @@ Frank Wilson,Engineering,88000,6
|
||||
return temp_file_path, uploaded_file.id
|
||||
|
||||
|
||||
async def cleanup_files(openai_client: AsyncAzureOpenAI, temp_file_path: str, file_id: str) -> None:
|
||||
async def cleanup_files(openai_client: AsyncOpenAI, temp_file_path: str, file_id: str) -> None:
|
||||
"""Clean up both local temporary file and uploaded file."""
|
||||
# Clean up: delete the uploaded file
|
||||
await openai_client.files.delete(file_id)
|
||||
@@ -65,39 +68,29 @@ async def cleanup_files(openai_client: AsyncAzureOpenAI, temp_file_path: str, fi
|
||||
async def main() -> None:
|
||||
print("=== Foundry Chat Client with Code Interpreter and File Upload ===")
|
||||
|
||||
# Initialize the underlying OpenAI client for file operations
|
||||
credential = AzureCliCredential()
|
||||
|
||||
async def get_token():
|
||||
token = credential.get_token("https://cognitiveservices.azure.com/.default")
|
||||
return token.token
|
||||
|
||||
openai_client = AsyncAzureOpenAI(
|
||||
azure_ad_token_provider=get_token,
|
||||
api_version="2024-05-01-preview",
|
||||
# Create the FoundryChatClient
|
||||
client = FoundryChatClient(
|
||||
project_endpoint=os.getenv("FOUNDRY_PROJECT_ENDPOINT"),
|
||||
model=os.getenv("FOUNDRY_MODEL"),
|
||||
credential=AzureCliCredential(),
|
||||
)
|
||||
|
||||
# use the openai client from the foundry client to upload files for the code interpreter tool
|
||||
openai_client = client.project_client.get_openai_client()
|
||||
temp_file_path, file_id = await create_sample_file_and_upload(openai_client)
|
||||
|
||||
# Create agent using FoundryChatClient
|
||||
client = FoundryChatClient(credential=credential)
|
||||
|
||||
# Create code interpreter tool with file access
|
||||
code_interpreter_tool = client.get_code_interpreter_tool(file_ids=[file_id])
|
||||
|
||||
# Create agent with code interpreter tool with file access
|
||||
agent = Agent(
|
||||
client=client,
|
||||
instructions="You are a helpful assistant that can analyze data files using Python code.",
|
||||
tools=[code_interpreter_tool],
|
||||
tools=FoundryChatClient.get_code_interpreter_tool(file_ids=[file_id]),
|
||||
)
|
||||
|
||||
# Test the code interpreter with the uploaded file
|
||||
query = "Analyze the employee data in the uploaded CSV file. Calculate average salary by department."
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result.text}")
|
||||
|
||||
await cleanup_files(openai_client, temp_file_path, file_id)
|
||||
try:
|
||||
# Test the code interpreter with the uploaded file
|
||||
query = "Analyze the employee data in the uploaded CSV file. Calculate average salary by department."
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result.text}")
|
||||
finally:
|
||||
await cleanup_files(openai_client, temp_file_path, file_id)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -35,7 +35,7 @@ def get_time():
|
||||
async def main() -> None:
|
||||
client = OllamaChatClient()
|
||||
message = "What time is it? Use a tool call"
|
||||
messages = [Message(role="user", text=message)]
|
||||
messages = [Message(role="user", contents=[message])]
|
||||
stream = False
|
||||
print(f"User: {message}")
|
||||
if stream:
|
||||
|
||||
Reference in New Issue
Block a user