mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
Python: [BREAKING] Python: Provider-leading client design & OpenAI package extraction (#4818)
* Python: Provider-leading client design & OpenAI package extraction Major refactoring of the Python Agent Framework client architecture: - Extract OpenAI clients into new `agent-framework-openai` package - Core package no longer depends on openai, azure-identity, azure-ai-projects - Rename clients for discoverability: OpenAIResponsesClient → OpenAIChatClient, OpenAIChatClient → OpenAIChatCompletionClient - Unify `model_id`/`deployment_name`/`model_deployment_name` → `model` param - New FoundryChatClient for Azure AI Foundry Responses API - New FoundryAgent/FoundryAgentClient for connecting to pre-configured Foundry agents - Remove OpenAIBase/OpenAIConfigMixin from non-deprecated client MRO - Deprecate AzureOpenAI* clients, AzureAIClient, OpenAIAssistantsClient - Reorganize samples: azure_openai+azure_ai+azure_ai_agent → azure/ - ADR-0020: Provider-Leading Client Design Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix: missing Agent imports in samples, .model_id → .model in foundry_local sample Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix: CI failures — mypy errors, coverage targets, sample imports - azure-ai mypy: add type ignores for TypedDict total=, model arg, forward ref - Coverage: replace core.azure/openai targets with openai package target - project_provider: add type annotation for opts dict Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix: populate openai .pyi stub, fix broken README links, coverage targets Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fixes * updated observabilitty * reset azure init.pyi * fix errors * updated adr number * fix foundry local * fixed not renamed docstrings and comments, and added deprecated markers to old classes * fix tests and pyprojects * fix test vars * updated function tests * update durable * updated test setup for functions * Fix Foundry auth in workflow samples Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Stabilize Python integration workflows Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Update hosting samples for Foundry Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Trigger full CI rerun Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Trigger CI rerun again Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * trigger rerun * trigger rerun * fix for litellm * undo durabletask changes * Move Foundry APIs into foundry namespace Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Fix Foundry pyproject formatting Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Split provider samples by Foundry surface Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Restore hosting sample requirements Also fix the Foundry Local sample link after the provider sample move. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * updated tests * udpated foundry integration tests * removed dist from azurefunctions tests * Use separate Foundry clients for concurrent agents Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix client setup in azfunc and durable * disabled two tests * updated setup for some function and durable tests * improved azure openai setup with new clients * ignore deprecated * fixes * skip 11 * remove openai assistants int tests --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
committed by
GitHub
Unverified
parent
4b533608b6
commit
5e056b672e
@@ -1,39 +1,31 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.azure import AzureOpenAIResponsesClient
|
||||
from agent_framework import Agent
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Hello Agent — Simplest possible agent
|
||||
|
||||
This sample creates a minimal agent using AzureOpenAIResponsesClient via an
|
||||
This sample creates a minimal agent using FoundryChatClient via an
|
||||
Azure AI Foundry project endpoint, and runs it in both non-streaming and streaming modes.
|
||||
|
||||
There are XML tags in all of the get started samples, those are used to display the same code in the docs repo.
|
||||
|
||||
Environment variables:
|
||||
AZURE_AI_PROJECT_ENDPOINT — Your Azure AI Foundry project endpoint
|
||||
AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME — Model deployment name (e.g. gpt-4o)
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# <create_agent>
|
||||
credential = AzureCliCredential()
|
||||
client = AzureOpenAIResponsesClient(
|
||||
project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
|
||||
deployment_name=os.environ["AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME"],
|
||||
credential=credential,
|
||||
client = FoundryChatClient(
|
||||
project_endpoint="https://your-project.services.ai.azure.com",
|
||||
model="gpt-4o",
|
||||
credential=AzureCliCredential(),
|
||||
)
|
||||
|
||||
agent = client.as_agent(
|
||||
agent = Agent(
|
||||
client=client,
|
||||
name="HelloAgent",
|
||||
instructions="You are a friendly assistant. Keep your answers brief.",
|
||||
)
|
||||
|
||||
@@ -1,28 +1,19 @@
|
||||
# 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.azure import AzureOpenAIResponsesClient
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Add Tools — Give your agent a function tool
|
||||
|
||||
This sample shows how to define a function tool with the @tool decorator
|
||||
and wire it into an agent so the model can call it.
|
||||
|
||||
Environment variables:
|
||||
AZURE_AI_PROJECT_ENDPOINT — Your Azure AI Foundry project endpoint
|
||||
AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME — Model deployment name (e.g. gpt-4o)
|
||||
"""
|
||||
|
||||
|
||||
@@ -36,22 +27,24 @@ def get_weather(
|
||||
"""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."
|
||||
|
||||
|
||||
# </define_tool>
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
credential = AzureCliCredential()
|
||||
client = AzureOpenAIResponsesClient(
|
||||
project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
|
||||
deployment_name=os.environ["AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME"],
|
||||
credential=credential,
|
||||
client = FoundryChatClient(
|
||||
project_endpoint="https://your-project.services.ai.azure.com",
|
||||
model="gpt-4o",
|
||||
credential=AzureCliCredential(),
|
||||
)
|
||||
|
||||
# <create_agent_with_tools>
|
||||
agent = client.as_agent(
|
||||
agent = Agent(
|
||||
client=client,
|
||||
name="WeatherAgent",
|
||||
instructions="You are a helpful weather agent. Use the get_weather tool to answer questions.",
|
||||
tools=get_weather,
|
||||
tools=[get_weather],
|
||||
)
|
||||
# </create_agent_with_tools>
|
||||
|
||||
|
||||
@@ -1,37 +1,29 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.azure import AzureOpenAIResponsesClient
|
||||
from agent_framework import Agent
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Multi-Turn Conversations — Use AgentSession to maintain context
|
||||
|
||||
This sample shows how to keep conversation history across multiple calls
|
||||
by reusing the same session object.
|
||||
|
||||
Environment variables:
|
||||
AZURE_AI_PROJECT_ENDPOINT — Your Azure AI Foundry project endpoint
|
||||
AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME — Model deployment name (e.g. gpt-4o)
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# <create_agent>
|
||||
credential = AzureCliCredential()
|
||||
client = AzureOpenAIResponsesClient(
|
||||
project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
|
||||
deployment_name=os.environ["AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME"],
|
||||
credential=credential,
|
||||
client = FoundryChatClient(
|
||||
project_endpoint="https://your-project.services.ai.azure.com",
|
||||
model="gpt-4o",
|
||||
credential=AzureCliCredential(),
|
||||
)
|
||||
|
||||
agent = client.as_agent(
|
||||
agent = Agent(
|
||||
client=client,
|
||||
name="ConversationAgent",
|
||||
instructions="You are a friendly assistant. Keep your answers brief.",
|
||||
)
|
||||
|
||||
@@ -1,16 +1,11 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
from agent_framework import AgentSession, BaseContextProvider, SessionContext
|
||||
from agent_framework.azure import AzureOpenAIResponsesClient
|
||||
from agent_framework import Agent, AgentSession, BaseContextProvider, SessionContext
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Agent Memory with Context Providers and Session State
|
||||
@@ -18,10 +13,6 @@ Agent Memory with Context Providers and Session State
|
||||
Context providers inject dynamic context into each agent call. This sample
|
||||
shows a provider that stores the user's name in session state and personalizes
|
||||
responses — the name persists across turns via the session.
|
||||
|
||||
Environment variables:
|
||||
AZURE_AI_PROJECT_ENDPOINT — Your Azure AI Foundry project endpoint
|
||||
AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME — Model deployment name (e.g. gpt-4o)
|
||||
"""
|
||||
|
||||
|
||||
@@ -68,19 +59,21 @@ class UserMemoryProvider(BaseContextProvider):
|
||||
text = msg.text if hasattr(msg, "text") else ""
|
||||
if isinstance(text, str) and "my name is" in text.lower():
|
||||
state["user_name"] = text.lower().split("my name is")[-1].strip().split()[0].capitalize()
|
||||
|
||||
|
||||
# </context_provider>
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# <create_agent>
|
||||
credential = AzureCliCredential()
|
||||
client = AzureOpenAIResponsesClient(
|
||||
project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
|
||||
deployment_name=os.environ["AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME"],
|
||||
credential=credential,
|
||||
client = FoundryChatClient(
|
||||
project_endpoint="https://your-project.services.ai.azure.com",
|
||||
model="gpt-4o",
|
||||
credential=AzureCliCredential(),
|
||||
)
|
||||
|
||||
agent = client.as_agent(
|
||||
agent = Agent(
|
||||
client=client,
|
||||
name="MemoryAgent",
|
||||
instructions="You are a friendly assistant.",
|
||||
context_providers=[UserMemoryProvider()],
|
||||
|
||||
@@ -45,6 +45,8 @@ def create_workflow():
|
||||
"""Build the workflow: UpperCase → reverse_text."""
|
||||
upper = UpperCase(id="upper_case")
|
||||
return WorkflowBuilder(start_executor=upper).add_edge(upper, reverse_text).build()
|
||||
|
||||
|
||||
# </create_workflow>
|
||||
|
||||
|
||||
|
||||
@@ -4,45 +4,37 @@
|
||||
# fmt: off
|
||||
from typing import Any
|
||||
|
||||
from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient
|
||||
from agent_framework import Agent
|
||||
from agent_framework.azure import AgentFunctionApp
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""Host your agent with Azure Functions.
|
||||
|
||||
This sample shows the Python hosting pattern used in docs:
|
||||
- Create an agent with `AzureOpenAIChatClient`
|
||||
- Create an agent with `FoundryChatClient`
|
||||
- Register it with `AgentFunctionApp`
|
||||
- Run with Azure Functions Core Tools (`func start`)
|
||||
|
||||
Prerequisites:
|
||||
pip install agent-framework-azurefunctions --pre
|
||||
|
||||
Environment variables:
|
||||
AZURE_OPENAI_ENDPOINT
|
||||
AZURE_OPENAI_CHAT_DEPLOYMENT_NAME
|
||||
"""
|
||||
|
||||
|
||||
# <create_agent>
|
||||
def _create_agent() -> Any:
|
||||
"""Create a hosted agent backed by Azure OpenAI."""
|
||||
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
|
||||
return Agent(
|
||||
client=FoundryChatClient(
|
||||
project_endpoint="https://your-project.services.ai.azure.com",
|
||||
model="gpt-4o",
|
||||
credential=AzureCliCredential(),
|
||||
),
|
||||
name="HostedAgent",
|
||||
instructions="You are a helpful assistant hosted in Azure Functions.",
|
||||
)
|
||||
|
||||
|
||||
# </create_agent>
|
||||
|
||||
# <host_agent>
|
||||
app = AgentFunctionApp(agents=[_create_agent()], enable_health_check=True, max_poll_retries=50)
|
||||
# </host_agent>
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("Start the Functions host with: func start")
|
||||
print("Then call: POST /api/agents/HostedAgent/run")
|
||||
|
||||
@@ -15,8 +15,8 @@ import logging
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import Any, TypeVar, cast
|
||||
|
||||
from agent_framework import ChatContext, ChatMiddleware, SupportsChatGetResponse, chat_middleware
|
||||
from agent_framework.azure import AzureOpenAIChatClient
|
||||
from agent_framework import Agent, ChatContext, ChatMiddleware, SupportsChatGetResponse, chat_middleware
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from openai import RateLimitError
|
||||
@@ -104,7 +104,7 @@ def with_rate_limit_retry(*, retry_attempts: int = RETRY_ATTEMPTS) -> Callable[[
|
||||
|
||||
|
||||
@with_rate_limit_retry()
|
||||
class RetryingAzureOpenAIChatClient(AzureOpenAIChatClient):
|
||||
class RetryingFoundryChatClient(FoundryChatClient):
|
||||
"""Azure OpenAI Chat client with class-decorator-based retry behavior."""
|
||||
|
||||
|
||||
@@ -186,7 +186,8 @@ async def class_decorator_example() -> None:
|
||||
|
||||
# For authentication, run `az login` command in terminal or replace
|
||||
# AzureCliCredential with your preferred authentication option.
|
||||
agent = RetryingAzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
|
||||
agent = Agent(
|
||||
client=RetryingFoundryChatClient(credential=AzureCliCredential()),
|
||||
instructions="You are a helpful assistant.",
|
||||
)
|
||||
|
||||
@@ -204,7 +205,8 @@ async def class_based_middleware_example() -> None:
|
||||
|
||||
# For authentication, run `az login` command in terminal or replace
|
||||
# AzureCliCredential with your preferred authentication option.
|
||||
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
|
||||
agent = Agent(
|
||||
client=FoundryChatClient(credential=AzureCliCredential()),
|
||||
instructions="You are a helpful assistant.",
|
||||
middleware=[RateLimitRetryMiddleware(max_attempts=3)],
|
||||
)
|
||||
@@ -223,7 +225,8 @@ async def function_based_middleware_example() -> None:
|
||||
|
||||
# For authentication, run `az login` command in terminal or replace
|
||||
# AzureCliCredential with your preferred authentication option.
|
||||
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
|
||||
agent = Agent(
|
||||
client=FoundryChatClient(credential=AzureCliCredential()),
|
||||
instructions="You are a helpful assistant.",
|
||||
middleware=[rate_limit_retry_middleware],
|
||||
)
|
||||
@@ -239,7 +242,7 @@ async def main() -> None:
|
||||
print("=== Auto-Retry Rate Limiting Sample ===")
|
||||
print(
|
||||
"Demonstrates two approaches for automatic retry on rate limit (429) errors.\n"
|
||||
"Set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_CHAT_DEPLOYMENT_NAME (and optionally\n"
|
||||
"Set AZURE_OPENAI_ENDPOINT and FOUNDRY_MODEL (and optionally\n"
|
||||
"AZURE_OPENAI_API_KEY) before running, or populate a .env file."
|
||||
)
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ Prerequisites:
|
||||
agent = Agent(
|
||||
name="researcher",
|
||||
instructions="You are a helpful research assistant. Be concise.",
|
||||
client=OpenAIResponsesClient(model_id="o3"),
|
||||
client=OpenAIResponsesClient(model="o3"),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -7,9 +7,9 @@ from typing import Annotated, Any, Literal
|
||||
|
||||
from agent_framework import Message, SupportsChatGetResponse, tool
|
||||
from agent_framework.azure import (
|
||||
AzureAIAgentClient,
|
||||
AzureOpenAIAssistantsClient,
|
||||
)
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from agent_framework.openai import OpenAIAssistantsClient
|
||||
from azure.identity import AzureCliCredential
|
||||
from azure.identity.aio import AzureCliCredential as AsyncAzureCliCredential
|
||||
@@ -70,16 +70,12 @@ def get_client(client_name: ClientName) -> SupportsChatGetResponse[Any]:
|
||||
"""Create a built-in chat client from a name."""
|
||||
from agent_framework.amazon import BedrockChatClient
|
||||
from agent_framework.anthropic import AnthropicClient
|
||||
from agent_framework.azure import (
|
||||
AzureOpenAIChatClient,
|
||||
AzureOpenAIResponsesClient,
|
||||
)
|
||||
from agent_framework.ollama import OllamaChatClient
|
||||
from agent_framework.openai import OpenAIChatClient, OpenAIResponsesClient
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
|
||||
# 1. Create OpenAI clients.
|
||||
if client_name == "openai_chat":
|
||||
return OpenAIChatClient()
|
||||
return FoundryChatClient()
|
||||
if client_name == "openai_responses":
|
||||
return OpenAIResponsesClient()
|
||||
if client_name == "openai_assistants":
|
||||
@@ -93,13 +89,13 @@ def get_client(client_name: ClientName) -> SupportsChatGetResponse[Any]:
|
||||
|
||||
# 2. Create Azure OpenAI clients.
|
||||
if client_name == "azure_openai_chat":
|
||||
return AzureOpenAIChatClient(credential=AzureCliCredential())
|
||||
return FoundryChatClient(credential=AzureCliCredential())
|
||||
if client_name == "azure_openai_responses":
|
||||
return AzureOpenAIResponsesClient(credential=AzureCliCredential(), api_version="preview")
|
||||
return FoundryChatClient(credential=AzureCliCredential(), api_version="preview")
|
||||
if client_name == "azure_openai_responses_foundry":
|
||||
return AzureOpenAIResponsesClient(
|
||||
project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
|
||||
deployment_name=os.environ["AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME"],
|
||||
return FoundryChatClient(
|
||||
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
|
||||
model=os.environ["FOUNDRY_MODEL"],
|
||||
credential=AzureCliCredential(),
|
||||
)
|
||||
if client_name == "azure_openai_assistants":
|
||||
@@ -107,7 +103,7 @@ def get_client(client_name: ClientName) -> SupportsChatGetResponse[Any]:
|
||||
|
||||
# 3. Create Azure AI client.
|
||||
if client_name == "azure_ai_agent":
|
||||
return AzureAIAgentClient(credential=AsyncAzureCliCredential())
|
||||
return FoundryChatClient(credential=AsyncAzureCliCredential())
|
||||
|
||||
raise ValueError(f"Unsupported client name: {client_name}")
|
||||
|
||||
@@ -123,7 +119,7 @@ async def main(client_name: ClientName = "openai_chat") -> None:
|
||||
print(f"User: {message.text}")
|
||||
|
||||
# 2. Run with context-managed clients.
|
||||
if isinstance(client, OpenAIAssistantsClient | AzureOpenAIAssistantsClient | AzureAIAgentClient):
|
||||
if isinstance(client, OpenAIAssistantsClient | AzureOpenAIAssistantsClient | FoundryChatClient):
|
||||
async with client:
|
||||
if stream:
|
||||
response_stream = client.get_response([message], stream=True, options={"tools": get_weather})
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Message
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
@@ -23,10 +23,10 @@ async def main() -> None:
|
||||
Creates a task for the chat request, waits briefly, then cancels it to show proper cleanup.
|
||||
|
||||
Configuration:
|
||||
- OpenAI model ID: Use "model_id" parameter or "OPENAI_CHAT_MODEL_ID" environment variable
|
||||
- OpenAI model ID: Use "model_id" parameter or "OPENAI_MODEL" environment variable
|
||||
- OpenAI API key: Use "api_key" parameter or "OPENAI_API_KEY" environment variable
|
||||
"""
|
||||
client = OpenAIChatClient()
|
||||
client = FoundryChatClient()
|
||||
|
||||
try:
|
||||
task = asyncio.create_task(
|
||||
|
||||
@@ -7,6 +7,7 @@ from collections.abc import AsyncIterable, Awaitable, Mapping, Sequence
|
||||
from typing import Any, ClassVar, TypeAlias, TypedDict
|
||||
|
||||
from agent_framework import (
|
||||
Agent,
|
||||
BaseChatClient,
|
||||
ChatMiddlewareLayer,
|
||||
ChatResponse,
|
||||
@@ -159,7 +160,8 @@ async def main() -> None:
|
||||
print(f"Direct response: {direct_response.messages[0].text}")
|
||||
|
||||
# Create an agent using the custom chat client
|
||||
echo_agent = echo_client.as_agent(
|
||||
echo_agent = Agent(
|
||||
client=echo_client,
|
||||
name="EchoAgent",
|
||||
instructions="You are a helpful assistant that echoes back what users say.",
|
||||
)
|
||||
|
||||
@@ -4,7 +4,7 @@ import os
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from agent_framework import Agent, InMemoryHistoryProvider
|
||||
from agent_framework.azure import AzureOpenAIResponsesClient, FoundryMemoryProvider
|
||||
from agent_framework.foundry import FoundryChatClient, FoundryMemoryProvider
|
||||
from azure.ai.projects.aio import AIProjectClient
|
||||
from azure.ai.projects.models import (
|
||||
MemoryStoreDefaultDefinition,
|
||||
@@ -31,8 +31,8 @@ so that follow-up responses demonstrate the agent relying solely on Foundry Memo
|
||||
rather than chat history. The memory store is deleted at the end of the run.
|
||||
|
||||
Prerequisites:
|
||||
1. Set AZURE_AI_PROJECT_ENDPOINT environment variable
|
||||
2. Set AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME for the chat/responses model
|
||||
1. Set FOUNDRY_PROJECT_ENDPOINT environment variable
|
||||
2. Set FOUNDRY_MODEL for the chat/responses model
|
||||
3. Set AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME for the embedding model
|
||||
4. Deploy both a chat model (e.g. gpt-4) and an embedding model (e.g. text-embedding-3-small)
|
||||
"""
|
||||
@@ -40,7 +40,7 @@ load_dotenv()
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
endpoint = os.environ["AZURE_AI_PROJECT_ENDPOINT"]
|
||||
endpoint = os.environ["FOUNDRY_PROJECT_ENDPOINT"]
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AIProjectClient(endpoint=endpoint, credential=credential) as project_client,
|
||||
@@ -54,7 +54,7 @@ async def main() -> None:
|
||||
user_profile_details="Avoid irrelevant or sensitive data, such as age, financials, precise location, and credentials",
|
||||
)
|
||||
memory_store_definition = MemoryStoreDefaultDefinition(
|
||||
chat_model=os.environ["AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME"],
|
||||
chat_model=os.environ["FOUNDRY_MODEL"],
|
||||
embedding_model=os.environ["AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME"],
|
||||
options=options,
|
||||
)
|
||||
@@ -75,7 +75,7 @@ async def main() -> None:
|
||||
print("==========================================")
|
||||
|
||||
# Create the chat client
|
||||
client = AzureOpenAIResponsesClient(project_client=project_client)
|
||||
client = FoundryChatClient(project_client=project_client)
|
||||
# Create the Foundry Memory context provider
|
||||
memory_provider = FoundryMemoryProvider(
|
||||
project_client=project_client,
|
||||
|
||||
@@ -8,13 +8,13 @@ This folder contains examples demonstrating how to use the Azure AI Search conte
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| [`azure_ai_with_search_context_agentic.py`](azure_ai_with_search_context_agentic.py) | **Agentic mode** (recommended for most scenarios): Uses Knowledge Bases in Azure AI Search for query planning and multi-hop reasoning. Provides more accurate results through intelligent retrieval with automatic query reformulation. Slightly slower with more token consumption for query planning. [Learn more](https://techcommunity.microsoft.com/blog/azure-ai-foundry-blog/foundry-iq-boost-response-relevance-by-36-with-agentic-retrieval/4470720) |
|
||||
| [`azure_ai_with_search_context_semantic.py`](azure_ai_with_search_context_semantic.py) | **Semantic mode** (fast queries): Fast hybrid search combining vector and keyword search with semantic ranking. Returns raw search results as context. Best for scenarios where speed is critical and simple retrieval is sufficient. |
|
||||
| [`search_context_agentic.py`](search_context_agentic.py) | **Agentic mode** (recommended for most scenarios): Uses Knowledge Bases in Azure AI Search for query planning and multi-hop reasoning. Provides more accurate results through intelligent retrieval with automatic query reformulation. Slightly slower with more token consumption for query planning. [Learn more](https://techcommunity.microsoft.com/blog/azure-ai-foundry-blog/foundry-iq-boost-response-relevance-by-36-with-agentic-retrieval/4470720) |
|
||||
| [`search_context_semantic.py`](search_context_semantic.py) | **Semantic mode** (fast queries): Fast hybrid search combining vector and keyword search with semantic ranking. Returns raw search results as context. Best for scenarios where speed is critical and simple retrieval is sufficient. |
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
pip install agent-framework-azure-ai-search agent-framework-azure-ai
|
||||
pip install agent-framework-foundry-search agent-framework-foundry
|
||||
```
|
||||
|
||||
## Prerequisites
|
||||
|
||||
+8
-7
@@ -4,7 +4,8 @@ import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.azure import AzureAIAgentClient, AzureAISearchContextProvider
|
||||
from agent_framework.azure import AzureAISearchContextProvider
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
@@ -31,8 +32,8 @@ Prerequisites:
|
||||
|
||||
Environment variables:
|
||||
- AZURE_SEARCH_ENDPOINT: Your Azure AI Search endpoint
|
||||
- AZURE_SEARCH_API_KEY: (Optional) API key - if not provided, uses DefaultAzureCredential
|
||||
- AZURE_AI_PROJECT_ENDPOINT: Your Azure AI Foundry project endpoint
|
||||
- AZURE_SEARCH_API_KEY: (Optional) API key - if not provided, uses AzureCliCredential
|
||||
- FOUNDRY_PROJECT_ENDPOINT: Your Azure AI Foundry project endpoint
|
||||
- AZURE_AI_MODEL_DEPLOYMENT_NAME: Your model deployment name (e.g., "gpt-4o")
|
||||
|
||||
For using an existing Knowledge Base (recommended):
|
||||
@@ -57,7 +58,7 @@ async def main() -> None:
|
||||
# Get configuration from environment
|
||||
search_endpoint = os.environ["AZURE_SEARCH_ENDPOINT"]
|
||||
search_key = os.environ.get("AZURE_SEARCH_API_KEY")
|
||||
project_endpoint = os.environ["AZURE_AI_PROJECT_ENDPOINT"]
|
||||
project_endpoint = os.environ["FOUNDRY_PROJECT_ENDPOINT"]
|
||||
model_deployment = os.environ.get("AZURE_AI_MODEL_DEPLOYMENT_NAME", "gpt-4o")
|
||||
|
||||
# Agentic mode requires exactly ONE of: knowledge_base_name OR index_name
|
||||
@@ -99,7 +100,7 @@ async def main() -> None:
|
||||
credential=AzureCliCredential() if not search_key else None,
|
||||
mode="agentic",
|
||||
azure_openai_resource_url=azure_openai_resource_url,
|
||||
model_deployment_name=model_deployment,
|
||||
model_model=model_deployment,
|
||||
# Optional: Configure retrieval behavior
|
||||
knowledge_base_output_mode="extractive_data", # or "answer_synthesis"
|
||||
retrieval_reasoning_effort="minimal", # or "medium", "low"
|
||||
@@ -109,9 +110,9 @@ async def main() -> None:
|
||||
# Create agent with search context provider
|
||||
async with (
|
||||
search_provider,
|
||||
AzureAIAgentClient(
|
||||
FoundryChatClient(
|
||||
project_endpoint=project_endpoint,
|
||||
model_deployment_name=model_deployment,
|
||||
model_model=model_deployment,
|
||||
credential=AzureCliCredential(),
|
||||
) as client,
|
||||
Agent(
|
||||
+8
-7
@@ -4,7 +4,8 @@ import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.azure import AzureAIAgentClient, AzureAISearchContextProvider, AzureOpenAIEmbeddingClient
|
||||
from agent_framework.azure import AzureAISearchContextProvider, AzureOpenAIEmbeddingClient
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
@@ -26,9 +27,9 @@ Prerequisites:
|
||||
2. An Azure AI Foundry project with a model deployment
|
||||
3. Set the following environment variables:
|
||||
- AZURE_SEARCH_ENDPOINT: Your Azure AI Search endpoint
|
||||
- AZURE_SEARCH_API_KEY: (Optional) Your search API key - if not provided, uses DefaultAzureCredential for Entra ID
|
||||
- AZURE_SEARCH_API_KEY: (Optional) Your search API key - if not provided, uses AzureCliCredential for Entra ID
|
||||
- AZURE_SEARCH_INDEX_NAME: Your search index name
|
||||
- AZURE_AI_PROJECT_ENDPOINT: Your Azure AI Foundry project endpoint
|
||||
- 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
|
||||
@@ -51,7 +52,7 @@ async def main() -> None:
|
||||
search_endpoint = os.environ["AZURE_SEARCH_ENDPOINT"]
|
||||
search_key = os.environ.get("AZURE_SEARCH_API_KEY")
|
||||
index_name = os.environ["AZURE_SEARCH_INDEX_NAME"]
|
||||
project_endpoint = os.environ["AZURE_AI_PROJECT_ENDPOINT"]
|
||||
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")
|
||||
@@ -60,7 +61,7 @@ async def main() -> None:
|
||||
if openai_endpoint and embedding_model:
|
||||
embedding_client = AzureOpenAIEmbeddingClient(
|
||||
endpoint=openai_endpoint,
|
||||
deployment_name=embedding_model,
|
||||
model=embedding_model,
|
||||
credential=credential,
|
||||
)
|
||||
|
||||
@@ -83,9 +84,9 @@ async def main() -> None:
|
||||
# Create agent with search context provider
|
||||
async with (
|
||||
search_provider,
|
||||
AzureAIAgentClient(
|
||||
FoundryChatClient(
|
||||
project_endpoint=project_endpoint,
|
||||
model_deployment_name=model_deployment,
|
||||
model_model=model_deployment,
|
||||
credential=credential,
|
||||
) as client,
|
||||
Agent(
|
||||
@@ -3,8 +3,8 @@
|
||||
import asyncio
|
||||
import uuid
|
||||
|
||||
from agent_framework import tool
|
||||
from agent_framework.azure import AzureAIAgentClient
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from agent_framework.mem0 import Mem0ContextProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
@@ -30,19 +30,17 @@ def retrieve_company_report(company_code: str, detailed: bool) -> str:
|
||||
|
||||
async def main() -> None:
|
||||
"""Example of memory usage with Mem0 context provider."""
|
||||
|
||||
print("=== Mem0 Context Provider Example ===")
|
||||
|
||||
# Each record in Mem0 should be associated with agent_id or user_id or application_id or thread_id.
|
||||
# In this example, we associate Mem0 records with user_id.
|
||||
user_id = str(uuid.uuid4())
|
||||
|
||||
# For Azure authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
# For Mem0 authentication, set Mem0 API key via "api_key" parameter or MEM0_API_KEY environment variable.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIAgentClient(credential=credential).as_agent(
|
||||
Agent(
|
||||
client=FoundryChatClient(credential=credential),
|
||||
name="FriendlyAssistant",
|
||||
instructions="You are a friendly assistant.",
|
||||
tools=retrieve_company_report,
|
||||
@@ -56,33 +54,23 @@ async def main() -> None:
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
|
||||
# Now tell the agent the company code and the report format that you want to use
|
||||
# and it should be able to invoke the tool and return the report.
|
||||
query = "I always work with CNTS and I always want a detailed report format. Please remember and retrieve it."
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
|
||||
# Mem0 processes and indexes memories asynchronously.
|
||||
# Wait for memories to be indexed before querying in a new thread.
|
||||
# In production, consider implementing retry logic or using Mem0's
|
||||
# eventual consistency handling instead of a fixed delay.
|
||||
print("Waiting for memories to be processed...")
|
||||
await asyncio.sleep(12) # Empirically determined delay for Mem0 indexing
|
||||
|
||||
print("\nRequest within a new session:")
|
||||
# Create a new session for the agent.
|
||||
# The new session has no context of the previous conversation.
|
||||
session = agent.create_session()
|
||||
|
||||
# Since we have the mem0 component in the session, the agent should be able to
|
||||
# retrieve the company report without asking for clarification, as it will
|
||||
# be able to remember the user preferences from Mem0 component.
|
||||
query = "Please retrieve my company report"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query, session=session)
|
||||
print(f"Agent: {result}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
import asyncio
|
||||
import uuid
|
||||
|
||||
from agent_framework import tool
|
||||
from agent_framework.azure import AzureAIAgentClient
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from agent_framework.mem0 import Mem0ContextProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
@@ -31,13 +31,10 @@ def retrieve_company_report(company_code: str, detailed: bool) -> str:
|
||||
|
||||
async def main() -> None:
|
||||
"""Example of memory usage with local Mem0 OSS context provider."""
|
||||
|
||||
print("=== Mem0 Context Provider Example ===")
|
||||
|
||||
# Each record in Mem0 should be associated with agent_id or user_id or application_id or thread_id.
|
||||
# In this example, we associate Mem0 records with user_id.
|
||||
user_id = str(uuid.uuid4())
|
||||
|
||||
# For Azure authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
# By default, local Mem0 authenticates to your OpenAI using the OPENAI_API_KEY environment variable.
|
||||
@@ -45,7 +42,8 @@ async def main() -> None:
|
||||
local_mem0_client = AsyncMemory()
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIAgentClient(credential=credential).as_agent(
|
||||
Agent(
|
||||
client=FoundryChatClient(credential=credential),
|
||||
name="FriendlyAssistant",
|
||||
instructions="You are a friendly assistant.",
|
||||
tools=retrieve_company_report,
|
||||
@@ -59,27 +57,17 @@ async def main() -> None:
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
|
||||
# Now tell the agent the company code and the report format that you want to use
|
||||
# and it should be able to invoke the tool and return the report.
|
||||
query = "I always work with CNTS and I always want a detailed report format. Please remember and retrieve it."
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
|
||||
print("\nRequest within a new session:")
|
||||
|
||||
# Create a new session for the agent.
|
||||
# The new session has no context of the previous conversation.
|
||||
session = agent.create_session()
|
||||
|
||||
# Since we have the mem0 component in the session, the agent should be able to
|
||||
# retrieve the company report without asking for clarification, as it will
|
||||
# be able to remember the user preferences from Mem0 component.
|
||||
query = "Please retrieve my company report"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query, session=session)
|
||||
print(f"Agent: {result}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
import asyncio
|
||||
import uuid
|
||||
|
||||
from agent_framework import tool
|
||||
from agent_framework.azure import AzureAIAgentClient
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from agent_framework.mem0 import Mem0ContextProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
@@ -37,7 +37,8 @@ async def example_global_thread_scope() -> None:
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIAgentClient(credential=credential).as_agent(
|
||||
Agent(
|
||||
client=FoundryChatClient(credential=credential),
|
||||
name="GlobalMemoryAssistant",
|
||||
instructions="You are an assistant that remembers user preferences across conversations.",
|
||||
tools=get_user_preferences,
|
||||
@@ -78,7 +79,8 @@ async def example_per_operation_thread_scope() -> None:
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIAgentClient(credential=credential).as_agent(
|
||||
Agent(
|
||||
client=FoundryChatClient(credential=credential),
|
||||
name="ScopedMemoryAssistant",
|
||||
instructions="You are an assistant with thread-scoped memory.",
|
||||
tools=get_user_preferences,
|
||||
@@ -129,7 +131,8 @@ async def example_multiple_agents() -> None:
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIAgentClient(credential=credential).as_agent(
|
||||
Agent(
|
||||
client=FoundryChatClient(credential=credential),
|
||||
name="PersonalAssistant",
|
||||
instructions="You are a personal assistant that helps with personal tasks.",
|
||||
context_providers=[
|
||||
@@ -139,7 +142,8 @@ async def example_multiple_agents() -> None:
|
||||
)
|
||||
],
|
||||
) as personal_agent,
|
||||
AzureAIAgentClient(credential=credential).as_agent(
|
||||
Agent(
|
||||
client=FoundryChatClient(credential=credential),
|
||||
name="WorkAssistant",
|
||||
instructions="You are a work assistant that helps with professional tasks.",
|
||||
context_providers=[
|
||||
|
||||
@@ -17,23 +17,22 @@ Requirements:
|
||||
|
||||
Environment Variables:
|
||||
- AZURE_REDIS_HOST: Your Azure Managed Redis host (e.g., myredis.redis.cache.windows.net)
|
||||
- AZURE_AI_PROJECT_ENDPOINT: Your Azure AI Foundry project endpoint
|
||||
- AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME: Azure OpenAI Responses deployment name
|
||||
- FOUNDRY_PROJECT_ENDPOINT: Your Azure AI Foundry project endpoint
|
||||
- FOUNDRY_MODEL: Azure OpenAI Responses deployment name
|
||||
- AZURE_USER_OBJECT_ID: Your Azure AD User Object ID for authentication
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.azure import AzureOpenAIResponsesClient
|
||||
from agent_framework import Agent
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from agent_framework.redis import RedisHistoryProvider
|
||||
from azure.identity import AzureCliCredential
|
||||
from azure.identity.aio import AzureCliCredential as AsyncAzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from redis.credentials import CredentialProvider
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
|
||||
class AzureCredentialProvider(CredentialProvider):
|
||||
@@ -81,14 +80,15 @@ async def main() -> None:
|
||||
)
|
||||
|
||||
# 3. Create chat client
|
||||
client = AzureOpenAIResponsesClient(
|
||||
project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
|
||||
deployment_name=os.environ["AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME"],
|
||||
client = FoundryChatClient(
|
||||
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
|
||||
model=os.environ["FOUNDRY_MODEL"],
|
||||
credential=AzureCliCredential(),
|
||||
)
|
||||
|
||||
# 4. Create agent with Azure Redis history provider
|
||||
agent = client.as_agent(
|
||||
agent = Agent(
|
||||
client=client,
|
||||
name="AzureRedisAssistant",
|
||||
instructions="You are a helpful assistant.",
|
||||
context_providers=[history_provider],
|
||||
|
||||
@@ -30,8 +30,8 @@ Run:
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework import Message, tool
|
||||
from agent_framework.azure import AzureOpenAIResponsesClient
|
||||
from agent_framework import Agent, Message, tool
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from agent_framework.redis import RedisContextProvider
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
@@ -99,11 +99,11 @@ def search_flights(origin_airport_code: str, destination_airport_code: str, deta
|
||||
)
|
||||
|
||||
|
||||
def create_chat_client() -> AzureOpenAIResponsesClient:
|
||||
def create_chat_client() -> FoundryChatClient:
|
||||
"""Create an Azure OpenAI Responses client using a Foundry project endpoint."""
|
||||
return AzureOpenAIResponsesClient(
|
||||
project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
|
||||
deployment_name=os.environ["AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME"],
|
||||
return FoundryChatClient(
|
||||
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
|
||||
model=os.environ["FOUNDRY_MODEL"],
|
||||
credential=AzureCliCredential(),
|
||||
)
|
||||
|
||||
@@ -121,7 +121,7 @@ async def main() -> None:
|
||||
# Create a provider with partition scope and OpenAI embeddings
|
||||
|
||||
# Please set OPENAI_API_KEY to use the OpenAI vectorizer.
|
||||
# For chat responses, also set AZURE_AI_PROJECT_ENDPOINT and AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME.
|
||||
# For chat responses, also set FOUNDRY_PROJECT_ENDPOINT and FOUNDRY_MODEL.
|
||||
|
||||
# We attach an embedding vectorizer so the provider can perform hybrid (text + vector)
|
||||
# retrieval. If you prefer text-only retrieval, instantiate RedisContextProvider without the
|
||||
@@ -206,7 +206,8 @@ async def main() -> None:
|
||||
client = create_chat_client()
|
||||
# Create agent wired to the Redis context provider. The provider automatically
|
||||
# persists conversational details and surfaces relevant context on each turn.
|
||||
agent = client.as_agent(
|
||||
agent = Agent(
|
||||
client=client,
|
||||
name="MemoryEnhancedAssistant",
|
||||
instructions=(
|
||||
"You are a helpful assistant. Personalize replies using provided context. "
|
||||
@@ -249,7 +250,8 @@ async def main() -> None:
|
||||
# Create agent exposing the flight search tool. Tool outputs are captured by the
|
||||
# provider and become retrievable context for later turns.
|
||||
client = create_chat_client()
|
||||
agent = client.as_agent(
|
||||
agent = Agent(
|
||||
client=client,
|
||||
name="MemoryEnhancedAssistant",
|
||||
instructions=(
|
||||
"You are a helpful assistant. Personalize replies using provided context. "
|
||||
|
||||
@@ -21,15 +21,15 @@ Run:
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.azure import AzureOpenAIResponsesClient
|
||||
from agent_framework import Agent
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from agent_framework.redis import RedisContextProvider
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from redisvl.extensions.cache.embeddings import EmbeddingsCache
|
||||
from redisvl.utils.vectorize import OpenAITextVectorizer
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
|
||||
# Default Redis URL for local Redis Stack.
|
||||
# Override via the REDIS_URL environment variable for remote or authenticated instances.
|
||||
@@ -64,14 +64,15 @@ async def main() -> None:
|
||||
)
|
||||
|
||||
# Create chat client for the agent
|
||||
client = AzureOpenAIResponsesClient(
|
||||
project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
|
||||
deployment_name=os.environ["AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME"],
|
||||
client = FoundryChatClient(
|
||||
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
|
||||
model=os.environ["FOUNDRY_MODEL"],
|
||||
credential=AzureCliCredential(),
|
||||
)
|
||||
# Create agent wired to the Redis context provider. The provider automatically
|
||||
# persists conversational details and surfaces relevant context on each turn.
|
||||
agent = client.as_agent(
|
||||
agent = Agent(
|
||||
client=client,
|
||||
name="MemoryEnhancedAssistant",
|
||||
instructions=(
|
||||
"You are a helpful assistant. Personalize replies using provided context. "
|
||||
|
||||
@@ -29,15 +29,15 @@ Run:
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.azure import AzureOpenAIResponsesClient
|
||||
from agent_framework import Agent
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from agent_framework.redis import RedisContextProvider
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from redisvl.extensions.cache.embeddings import EmbeddingsCache
|
||||
from redisvl.utils.vectorize import OpenAITextVectorizer
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
|
||||
# Default Redis URL for local Redis Stack.
|
||||
# Override via the REDIS_URL environment variable for remote or authenticated instances.
|
||||
@@ -45,12 +45,12 @@ REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379")
|
||||
|
||||
|
||||
# Please set OPENAI_API_KEY to use the OpenAI vectorizer.
|
||||
# For chat responses, also set AZURE_AI_PROJECT_ENDPOINT and AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME.
|
||||
def create_chat_client() -> AzureOpenAIResponsesClient:
|
||||
# For chat responses, also set FOUNDRY_PROJECT_ENDPOINT and FOUNDRY_MODEL.
|
||||
def create_chat_client() -> FoundryChatClient:
|
||||
"""Create an Azure OpenAI Responses client using a Foundry project endpoint."""
|
||||
return AzureOpenAIResponsesClient(
|
||||
project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
|
||||
deployment_name=os.environ["AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME"],
|
||||
return FoundryChatClient(
|
||||
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
|
||||
model=os.environ["FOUNDRY_MODEL"],
|
||||
credential=AzureCliCredential(),
|
||||
)
|
||||
|
||||
@@ -71,7 +71,8 @@ async def example_global_thread_scope() -> None:
|
||||
user_id="threads_demo_user",
|
||||
)
|
||||
|
||||
agent = client.as_agent(
|
||||
agent = Agent(
|
||||
client=client,
|
||||
name="GlobalMemoryAssistant",
|
||||
instructions=(
|
||||
"You are a helpful assistant. Personalize replies using provided context. "
|
||||
@@ -128,7 +129,8 @@ async def example_per_operation_thread_scope() -> None:
|
||||
vector_distance_metric="cosine",
|
||||
)
|
||||
|
||||
agent = client.as_agent(
|
||||
agent = Agent(
|
||||
client=client,
|
||||
name="ScopedMemoryAssistant",
|
||||
instructions="You are an assistant with thread-scoped memory.",
|
||||
context_providers=[provider],
|
||||
@@ -191,7 +193,8 @@ async def example_multiple_agents() -> None:
|
||||
vector_distance_metric="cosine",
|
||||
)
|
||||
|
||||
personal_agent = client.as_agent(
|
||||
personal_agent = Agent(
|
||||
client=client,
|
||||
name="PersonalAssistant",
|
||||
instructions="You are a personal assistant that helps with personal tasks.",
|
||||
context_providers=[personal_provider],
|
||||
@@ -210,7 +213,8 @@ async def example_multiple_agents() -> None:
|
||||
vector_distance_metric="cosine",
|
||||
)
|
||||
|
||||
work_agent = client.as_agent(
|
||||
work_agent = Agent(
|
||||
client=client,
|
||||
name="WorkAssistant",
|
||||
instructions="You are a work assistant that helps with professional tasks.",
|
||||
context_providers=[work_provider],
|
||||
|
||||
@@ -6,7 +6,7 @@ from contextlib import suppress
|
||||
from typing import Any
|
||||
|
||||
from agent_framework import Agent, AgentSession, BaseContextProvider, SessionContext, SupportsChatGetResponse
|
||||
from agent_framework.azure import AzureOpenAIResponsesClient
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import BaseModel
|
||||
@@ -89,9 +89,9 @@ class UserInfoMemory(BaseContextProvider):
|
||||
|
||||
|
||||
async def main():
|
||||
client = AzureOpenAIResponsesClient(
|
||||
project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
|
||||
deployment_name=os.environ["AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME"],
|
||||
client = FoundryChatClient(
|
||||
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
|
||||
model=os.environ["FOUNDRY_MODEL"],
|
||||
credential=AzureCliCredential(),
|
||||
)
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import asyncio
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
from agent_framework import AgentSession, BaseHistoryProvider, Message
|
||||
from agent_framework import Agent, AgentSession, BaseHistoryProvider, Message
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
@@ -54,7 +54,8 @@ async def main() -> None:
|
||||
|
||||
# OpenAI Chat Client is used as an example here,
|
||||
# other chat clients can be used as well.
|
||||
agent = OpenAIChatClient().as_agent(
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
name="CustomBot",
|
||||
instructions="You are a helpful assistant that remembers our conversation.",
|
||||
# Use custom history provider.
|
||||
|
||||
@@ -4,7 +4,7 @@ import asyncio
|
||||
import os
|
||||
from uuid import uuid4
|
||||
|
||||
from agent_framework import AgentSession
|
||||
from agent_framework import Agent, AgentSession
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from agent_framework.redis import RedisHistoryProvider
|
||||
from dotenv import load_dotenv
|
||||
@@ -36,7 +36,8 @@ async def example_manual_memory_store() -> None:
|
||||
)
|
||||
|
||||
# Create agent with Redis history provider
|
||||
agent = OpenAIChatClient().as_agent(
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
name="RedisBot",
|
||||
instructions="You are a helpful assistant that remembers our conversation using Redis.",
|
||||
context_providers=[redis_provider],
|
||||
@@ -75,7 +76,8 @@ async def example_user_session_management() -> None:
|
||||
)
|
||||
|
||||
# Create agent with history provider
|
||||
agent = OpenAIChatClient().as_agent(
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
name="SessionBot",
|
||||
instructions="You are a helpful assistant. Keep track of user preferences.",
|
||||
context_providers=[redis_provider],
|
||||
@@ -114,7 +116,8 @@ async def example_conversation_persistence() -> None:
|
||||
redis_url=REDIS_URL,
|
||||
)
|
||||
|
||||
agent = OpenAIChatClient().as_agent(
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
name="PersistentBot",
|
||||
instructions="You are a helpful assistant. Remember our conversation history.",
|
||||
context_providers=[redis_provider],
|
||||
@@ -163,7 +166,8 @@ async def example_session_serialization() -> None:
|
||||
redis_url=REDIS_URL,
|
||||
)
|
||||
|
||||
agent = OpenAIChatClient().as_agent(
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
name="SerializationBot",
|
||||
instructions="You are a helpful assistant.",
|
||||
context_providers=[redis_provider],
|
||||
@@ -206,7 +210,8 @@ async def example_message_limits() -> None:
|
||||
max_messages=3, # Keep only 3 most recent messages
|
||||
)
|
||||
|
||||
agent = OpenAIChatClient().as_agent(
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
name="LimitBot",
|
||||
instructions="You are a helpful assistant with limited memory.",
|
||||
context_providers=[redis_provider],
|
||||
|
||||
@@ -2,9 +2,8 @@
|
||||
|
||||
import asyncio
|
||||
|
||||
from agent_framework import AgentSession
|
||||
from agent_framework.azure import AzureAIAgentClient
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from agent_framework import Agent, AgentSession
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
@@ -24,11 +23,13 @@ async def suspend_resume_service_managed_session() -> None:
|
||||
"""Demonstrates how to suspend and resume a service-managed session."""
|
||||
print("=== Suspend-Resume Service-Managed Session ===")
|
||||
|
||||
# AzureAIAgentClient supports service-managed sessions.
|
||||
# FoundryChatClient supports service-managed sessions.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIAgentClient(credential=credential).as_agent(
|
||||
name="MemoryBot", instructions="You are a helpful assistant that remembers our conversation."
|
||||
Agent(
|
||||
client=FoundryChatClient(credential=credential),
|
||||
name="MemoryBot",
|
||||
instructions="You are a helpful assistant that remembers our conversation.",
|
||||
) as agent,
|
||||
):
|
||||
# Start a new session for the agent conversation.
|
||||
@@ -60,8 +61,10 @@ async def suspend_resume_in_memory_session() -> None:
|
||||
|
||||
# OpenAI Chat Client is used as an example here,
|
||||
# other chat clients can be used as well.
|
||||
agent = OpenAIChatClient().as_agent(
|
||||
name="MemoryBot", instructions="You are a helpful assistant that remembers our conversation."
|
||||
agent = Agent(
|
||||
client=FoundryChatClient(),
|
||||
name="MemoryBot",
|
||||
instructions="You are a helpful assistant that remembers our conversation.",
|
||||
)
|
||||
|
||||
# Start a new session for the agent conversation.
|
||||
|
||||
@@ -43,7 +43,7 @@ Shows how to create an agent that can search and retrieve information from Micro
|
||||
- Uses Azure CLI credentials for authentication
|
||||
- Leverages MCP to access Microsoft documentation tools
|
||||
|
||||
**Requirements**: `pip install agent-framework-azure-ai --pre`
|
||||
**Requirements**: `pip install agent-framework-foundry --pre`
|
||||
|
||||
**Key concepts**: Azure AI Foundry integration, MCP server usage, async patterns, resource management
|
||||
|
||||
@@ -53,7 +53,7 @@ Shows how to create an agent using an inline YAML string rather than a file.
|
||||
|
||||
- Uses Azure AI Foundry v2 Client with instructions.
|
||||
|
||||
**Requirements**: `pip install agent-framework-azure-ai --pre`
|
||||
**Requirements**: `pip install agent-framework-foundry --pre`
|
||||
|
||||
**Key concepts**: Inline YAML definition.
|
||||
|
||||
|
||||
@@ -15,11 +15,9 @@ async def main():
|
||||
# get the path
|
||||
current_path = Path(__file__).parent
|
||||
yaml_path = current_path.parent.parent.parent.parent / "agent-samples" / "azure" / "AzureOpenAIResponses.yaml"
|
||||
|
||||
# load the yaml from the path
|
||||
with yaml_path.open("r") as f:
|
||||
yaml_str = f.read()
|
||||
|
||||
# create the agent from the yaml
|
||||
agent = AgentFactory(client_kwargs={"credential": AzureCliCredential()}).create_agent_from_yaml(yaml_str)
|
||||
# use the agent
|
||||
|
||||
@@ -4,8 +4,8 @@ from pathlib import Path
|
||||
from random import randint
|
||||
from typing import Literal
|
||||
|
||||
from agent_framework.azure import AzureOpenAIResponsesClient
|
||||
from agent_framework.declarative import AgentFactory
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
@@ -15,7 +15,6 @@ load_dotenv()
|
||||
|
||||
def get_weather(location: str, unit: Literal["celsius", "fahrenheit"] = "celsius") -> str:
|
||||
"""A simple function tool to get weather information."""
|
||||
|
||||
return f"The weather in {location} is {randint(-10, 30) if unit == 'celsius' else randint(30, 100)} degrees {unit}."
|
||||
|
||||
|
||||
@@ -24,14 +23,12 @@ async def main():
|
||||
# get the path
|
||||
current_path = Path(__file__).parent
|
||||
yaml_path = current_path.parent.parent.parent.parent / "agent-samples" / "chatclient" / "GetWeather.yaml"
|
||||
|
||||
# load the yaml from the path
|
||||
with yaml_path.open("r") as f:
|
||||
yaml_str = f.read()
|
||||
|
||||
# create the AgentFactory with a chat client and bindings
|
||||
agent_factory = AgentFactory(
|
||||
client=AzureOpenAIResponsesClient(credential=AzureCliCredential()),
|
||||
client=FoundryChatClient(credential=AzureCliCredential()),
|
||||
bindings={"get_weather": get_weather},
|
||||
)
|
||||
# create the agent from the yaml
|
||||
|
||||
@@ -14,9 +14,9 @@ This sample shows how to create an agent using an inline YAML string rather than
|
||||
It uses a Azure AI Client so it needs the credential to be passed into the AgentFactory.
|
||||
|
||||
Prerequisites:
|
||||
- `pip install agent-framework-azure-ai agent-framework-declarative --pre`
|
||||
- `pip install agent-framework-foundry agent-framework-declarative --pre`
|
||||
- Set the following environment variables in a .env file or your environment:
|
||||
- AZURE_AI_PROJECT_ENDPOINT
|
||||
- FOUNDRY_PROJECT_ENDPOINT
|
||||
- AZURE_OPENAI_MODEL
|
||||
"""
|
||||
|
||||
@@ -33,7 +33,7 @@ model:
|
||||
id: =Env.AZURE_OPENAI_MODEL
|
||||
connection:
|
||||
kind: remote
|
||||
endpoint: =Env.AZURE_AI_PROJECT_ENDPOINT
|
||||
endpoint: =Env.FOUNDRY_PROJECT_ENDPOINT
|
||||
"""
|
||||
# create the agent from the yaml
|
||||
async with (
|
||||
|
||||
@@ -132,9 +132,9 @@ async def run_azure_ai_example():
|
||||
print("Example 2: Azure AI with Foundry Connection Reference")
|
||||
print("=" * 60)
|
||||
|
||||
from azure.identity import DefaultAzureCredential
|
||||
from azure.identity import AzureCliCredential
|
||||
|
||||
factory = AgentFactory(client_kwargs={"credential": DefaultAzureCredential()})
|
||||
factory = AgentFactory(client_kwargs={"credential": AzureCliCredential()})
|
||||
|
||||
print("\nCreating agent from YAML definition...")
|
||||
# Use async method for provider-based agent creation
|
||||
|
||||
@@ -12,11 +12,9 @@ load_dotenv()
|
||||
|
||||
async def main():
|
||||
"""Create an agent from a declarative yaml specification and run it."""
|
||||
|
||||
# get the path
|
||||
current_path = Path(__file__).parent
|
||||
yaml_path = current_path.parent.parent.parent.parent / "agent-samples" / "foundry" / "MicrosoftLearnAgent.yaml"
|
||||
|
||||
# create the agent from the yaml
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
|
||||
@@ -11,15 +11,12 @@ load_dotenv()
|
||||
|
||||
async def main():
|
||||
"""Create an agent from a declarative yaml specification and run it."""
|
||||
|
||||
# get the path
|
||||
current_path = Path(__file__).parent
|
||||
yaml_path = current_path.parent.parent.parent.parent / "agent-samples" / "openai" / "OpenAIResponses.yaml"
|
||||
|
||||
# load the yaml from the path
|
||||
with yaml_path.open("r") as f:
|
||||
yaml_str = f.read()
|
||||
|
||||
# create the agent from the yaml
|
||||
agent = AgentFactory(safe_mode=False).create_agent_from_yaml(yaml_str)
|
||||
# use the agent
|
||||
|
||||
@@ -7,13 +7,13 @@ This agent uses the Responses API which supports:
|
||||
- Audio inputs
|
||||
- And other multimodal content
|
||||
|
||||
The Chat Completions API (AzureOpenAIChatClient) does NOT support PDF uploads.
|
||||
The Chat Completions API (FoundryChatClient) does NOT support PDF uploads.
|
||||
Use this agent when you need to process documents or other file types.
|
||||
|
||||
Required environment variables:
|
||||
- AZURE_OPENAI_ENDPOINT: Your Azure OpenAI endpoint
|
||||
- AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME: Deployment name for Responses API
|
||||
(falls back to AZURE_OPENAI_CHAT_DEPLOYMENT_NAME if not set)
|
||||
- FOUNDRY_MODEL: Deployment name for Responses API
|
||||
(falls back to FOUNDRY_MODEL if not set)
|
||||
- AZURE_OPENAI_API_KEY: Your API key (or use Azure CLI auth)
|
||||
"""
|
||||
|
||||
@@ -22,7 +22,7 @@ import os
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.azure import AzureOpenAIResponsesClient
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
@@ -32,8 +32,8 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
# Get deployment name - try responses-specific env var first, fall back to chat deployment
|
||||
_deployment_name = os.environ.get(
|
||||
"AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME",
|
||||
os.environ.get("AZURE_OPENAI_CHAT_DEPLOYMENT_NAME", ""),
|
||||
"FOUNDRY_MODEL",
|
||||
os.environ.get("FOUNDRY_MODEL", ""),
|
||||
)
|
||||
|
||||
# Get endpoint - try responses-specific env var first, fall back to default
|
||||
@@ -89,8 +89,8 @@ agent = Agent(
|
||||
For PDFs, you can read and understand the text, tables, and structure.
|
||||
For images, you can describe what you see and extract any text.
|
||||
""",
|
||||
client=AzureOpenAIResponsesClient(
|
||||
deployment_name=_deployment_name,
|
||||
client=FoundryChatClient(
|
||||
model=_deployment_name,
|
||||
endpoint=_endpoint,
|
||||
api_version="2025-03-01-preview", # Required for Responses API
|
||||
),
|
||||
@@ -117,7 +117,7 @@ def main():
|
||||
logger.info("")
|
||||
logger.info("Required environment variables:")
|
||||
logger.info(" - AZURE_OPENAI_ENDPOINT")
|
||||
logger.info(" - AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME")
|
||||
logger.info(" - FOUNDRY_MODEL")
|
||||
logger.info(" - AZURE_OPENAI_API_KEY (or use Azure CLI auth)")
|
||||
logger.info("")
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import os
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.azure import AzureAIAgentClient
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
@@ -51,9 +51,9 @@ def get_forecast(
|
||||
# Agent instance following Agent Framework conventions
|
||||
agent = Agent(
|
||||
name="FoundryWeatherAgent",
|
||||
client=AzureAIAgentClient(
|
||||
project_endpoint=os.environ.get("AZURE_AI_PROJECT_ENDPOINT"),
|
||||
model_deployment_name=os.environ.get("FOUNDRY_MODEL_DEPLOYMENT_NAME"),
|
||||
client=FoundryChatClient(
|
||||
project_endpoint=os.environ.get("FOUNDRY_PROJECT_ENDPOINT"),
|
||||
model_model=os.environ.get("FOUNDRY_MODEL_DEPLOYMENT_NAME"),
|
||||
credential=AzureCliCredential(),
|
||||
),
|
||||
instructions="""
|
||||
|
||||
@@ -18,8 +18,8 @@ from agent_framework import (
|
||||
handler,
|
||||
tool,
|
||||
)
|
||||
from agent_framework.azure import AzureOpenAIChatClient
|
||||
from agent_framework.devui import serve
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from dotenv import load_dotenv
|
||||
from typing_extensions import Never
|
||||
|
||||
@@ -79,9 +79,9 @@ def main():
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Create Azure OpenAI chat client
|
||||
client = AzureOpenAIChatClient(
|
||||
client = FoundryChatClient(
|
||||
api_key=os.environ.get("AZURE_OPENAI_API_KEY"),
|
||||
deployment_name=os.environ["AZURE_OPENAI_CHAT_DEPLOYMENT_NAME"],
|
||||
model=os.environ["FOUNDRY_MODEL"],
|
||||
endpoint=os.environ.get("AZURE_OPENAI_ENDPOINT"),
|
||||
api_version=os.environ.get("AZURE_OPENAI_API_VERSION", "2024-10-21"),
|
||||
)
|
||||
|
||||
@@ -20,7 +20,7 @@ from agent_framework import (
|
||||
function_middleware,
|
||||
tool,
|
||||
)
|
||||
from agent_framework.azure import AzureOpenAIChatClient
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from agent_framework_devui import register_cleanup
|
||||
from dotenv import load_dotenv
|
||||
|
||||
@@ -152,7 +152,7 @@ agent = Agent(
|
||||
and forecasts for any location. Always be helpful and provide detailed
|
||||
weather information when asked.
|
||||
""",
|
||||
client=AzureOpenAIChatClient(
|
||||
client=FoundryChatClient(
|
||||
api_key=os.environ.get("AZURE_OPENAI_API_KEY", ""),
|
||||
),
|
||||
tools=[get_weather, get_forecast, send_email],
|
||||
|
||||
@@ -17,8 +17,8 @@ Both paths converge at Summarizer for final report.
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
from agent_framework import AgentExecutorResponse, WorkflowBuilder
|
||||
from agent_framework.azure import AzureOpenAIChatClient
|
||||
from agent_framework import Agent, AgentExecutorResponse, WorkflowBuilder
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import BaseModel
|
||||
|
||||
@@ -63,10 +63,11 @@ def is_approved(message: Any) -> bool:
|
||||
|
||||
|
||||
# Create Azure OpenAI chat client
|
||||
client = AzureOpenAIChatClient(api_key=os.environ.get("AZURE_OPENAI_API_KEY", ""))
|
||||
client = FoundryChatClient(api_key=os.environ.get("AZURE_OPENAI_API_KEY", ""))
|
||||
|
||||
# Create Writer agent - generates content
|
||||
writer = client.as_agent(
|
||||
writer = Agent(
|
||||
client=client,
|
||||
name="Writer",
|
||||
instructions=(
|
||||
"You are an excellent content writer. "
|
||||
@@ -76,7 +77,8 @@ writer = client.as_agent(
|
||||
)
|
||||
|
||||
# Create Reviewer agent - evaluates and provides structured feedback
|
||||
reviewer = client.as_agent(
|
||||
reviewer = Agent(
|
||||
client=client,
|
||||
name="Reviewer",
|
||||
instructions=(
|
||||
"You are an expert content reviewer. "
|
||||
@@ -94,7 +96,8 @@ reviewer = client.as_agent(
|
||||
)
|
||||
|
||||
# Create Editor agent - improves content based on feedback
|
||||
editor = client.as_agent(
|
||||
editor = Agent(
|
||||
client=client,
|
||||
name="Editor",
|
||||
instructions=(
|
||||
"You are a skilled editor. "
|
||||
@@ -105,7 +108,8 @@ editor = client.as_agent(
|
||||
)
|
||||
|
||||
# Create Publisher agent - formats content for publication
|
||||
publisher = client.as_agent(
|
||||
publisher = Agent(
|
||||
client=client,
|
||||
name="Publisher",
|
||||
instructions=(
|
||||
"You are a publishing agent. "
|
||||
@@ -115,7 +119,8 @@ publisher = client.as_agent(
|
||||
)
|
||||
|
||||
# Create Summarizer agent - creates final publication report
|
||||
summarizer = client.as_agent(
|
||||
summarizer = Agent(
|
||||
client=client,
|
||||
name="Summarizer",
|
||||
instructions=(
|
||||
"You are a summarizer agent. "
|
||||
|
||||
@@ -21,7 +21,7 @@ Prerequisites:
|
||||
|
||||
async def main() -> None:
|
||||
"""Generate embeddings with OpenAI."""
|
||||
client = OpenAIEmbeddingClient(model_id="text-embedding-3-small")
|
||||
client = OpenAIEmbeddingClient(model="text-embedding-3-small")
|
||||
|
||||
# 1. Generate a single embedding.
|
||||
result = await client.get_embeddings(["Hello, world!"])
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from typing import Annotated, Any
|
||||
|
||||
import anyio
|
||||
from agent_framework import tool
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
@@ -27,7 +27,7 @@ with the following configuration:
|
||||
],
|
||||
"env": {
|
||||
"OPENAI_API_KEY": "<OpenAI API key>",
|
||||
"OPENAI_RESPONSES_MODEL_ID": "<OpenAI Responses model ID>",
|
||||
"OPENAI_MODEL": "<OpenAI Responses model ID>",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -56,7 +56,8 @@ def get_item_price(
|
||||
async def run() -> None:
|
||||
# Define an agent
|
||||
# Agent's name and description provide better context for AI model
|
||||
agent = OpenAIResponsesClient().as_agent(
|
||||
agent = Agent(
|
||||
client=OpenAIResponsesClient(),
|
||||
name="RestaurantAgent",
|
||||
description="Answer questions about the menu.",
|
||||
tools=[get_specials, get_item_price],
|
||||
|
||||
@@ -21,7 +21,7 @@ Prerequisites:
|
||||
2. Environment variables:
|
||||
- GITHUB_PAT: Your GitHub Personal Access Token (required)
|
||||
- OPENAI_API_KEY: Your OpenAI API key (required)
|
||||
- OPENAI_RESPONSES_MODEL_ID: Your OpenAI model ID (required)
|
||||
- OPENAI_MODEL: Your OpenAI model ID (required)
|
||||
"""
|
||||
|
||||
|
||||
|
||||
@@ -7,13 +7,14 @@ from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import (
|
||||
Agent,
|
||||
AgentContext,
|
||||
AgentMiddleware,
|
||||
AgentResponse,
|
||||
FunctionInvocationContext,
|
||||
tool,
|
||||
)
|
||||
from agent_framework.azure import AzureAIAgentClient
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
@@ -194,7 +195,8 @@ async def main() -> None:
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIAgentClient(credential=credential).as_agent(
|
||||
Agent(
|
||||
client=FoundryChatClient(credential=credential),
|
||||
name="WeatherAgent",
|
||||
instructions="You are a helpful weather assistant.",
|
||||
tools=get_weather,
|
||||
|
||||
@@ -6,6 +6,7 @@ from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import (
|
||||
Agent,
|
||||
ChatContext,
|
||||
ChatMiddleware,
|
||||
ChatResponse,
|
||||
@@ -14,7 +15,7 @@ from agent_framework import (
|
||||
chat_middleware,
|
||||
tool,
|
||||
)
|
||||
from agent_framework.azure import AzureAIAgentClient
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
@@ -150,7 +151,8 @@ async def class_based_chat_middleware() -> None:
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIAgentClient(credential=credential).as_agent(
|
||||
Agent(
|
||||
client=FoundryChatClient(credential=credential),
|
||||
name="EnhancedChatAgent",
|
||||
instructions="You are a helpful AI assistant.",
|
||||
# Register class-based middleware at agent level (applies to all runs)
|
||||
@@ -172,7 +174,8 @@ async def function_based_chat_middleware() -> None:
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIAgentClient(credential=credential).as_agent(
|
||||
Agent(
|
||||
client=FoundryChatClient(credential=credential),
|
||||
name="FunctionMiddlewareAgent",
|
||||
instructions="You are a helpful AI assistant.",
|
||||
# Register function-based middleware at agent level
|
||||
@@ -202,7 +205,8 @@ async def run_level_middleware() -> None:
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIAgentClient(credential=credential).as_agent(
|
||||
Agent(
|
||||
client=FoundryChatClient(credential=credential),
|
||||
name="RunLevelAgent",
|
||||
instructions="You are a helpful AI assistant.",
|
||||
tools=get_weather,
|
||||
|
||||
@@ -7,6 +7,7 @@ from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import (
|
||||
Agent,
|
||||
AgentContext,
|
||||
AgentMiddleware,
|
||||
AgentResponse,
|
||||
@@ -15,7 +16,7 @@ from agent_framework import (
|
||||
Message,
|
||||
tool,
|
||||
)
|
||||
from agent_framework.azure import AzureAIAgentClient
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
@@ -105,7 +106,8 @@ async def main() -> None:
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIAgentClient(credential=credential).as_agent(
|
||||
Agent(
|
||||
client=FoundryChatClient(credential=credential),
|
||||
name="WeatherAgent",
|
||||
instructions="You are a helpful weather assistant.",
|
||||
tools=get_weather,
|
||||
|
||||
@@ -4,11 +4,12 @@ import asyncio
|
||||
import datetime
|
||||
|
||||
from agent_framework import (
|
||||
Agent,
|
||||
agent_middleware,
|
||||
function_middleware,
|
||||
tool,
|
||||
)
|
||||
from agent_framework.azure import AzureAIAgentClient
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
@@ -79,7 +80,8 @@ async def main() -> None:
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIAgentClient(credential=credential).as_agent(
|
||||
Agent(
|
||||
client=FoundryChatClient(credential=credential),
|
||||
name="TimeAgent",
|
||||
instructions="You are a helpful time assistant. Call get_current_time when asked about time.",
|
||||
tools=get_current_time,
|
||||
|
||||
@@ -4,8 +4,8 @@ import asyncio
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import FunctionInvocationContext, tool
|
||||
from agent_framework.azure import AzureAIAgentClient
|
||||
from agent_framework import Agent, FunctionInvocationContext, tool
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
@@ -66,7 +66,8 @@ async def main() -> None:
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIAgentClient(credential=credential).as_agent(
|
||||
Agent(
|
||||
client=FoundryChatClient(credential=credential),
|
||||
name="DataAgent",
|
||||
instructions="You are a helpful data assistant. Use the data service tool to fetch information for users.",
|
||||
tools=unstable_data_service,
|
||||
|
||||
@@ -7,11 +7,12 @@ from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import (
|
||||
Agent,
|
||||
AgentContext,
|
||||
FunctionInvocationContext,
|
||||
tool,
|
||||
)
|
||||
from agent_framework.azure import AzureAIAgentClient
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
@@ -92,7 +93,8 @@ async def main() -> None:
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIAgentClient(credential=credential).as_agent(
|
||||
Agent(
|
||||
client=FoundryChatClient(credential=credential),
|
||||
name="WeatherAgent",
|
||||
instructions="You are a helpful weather assistant.",
|
||||
tools=get_weather,
|
||||
|
||||
@@ -6,6 +6,7 @@ from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import (
|
||||
Agent,
|
||||
AgentContext,
|
||||
AgentMiddleware,
|
||||
AgentResponse,
|
||||
@@ -13,7 +14,7 @@ from agent_framework import (
|
||||
MiddlewareTermination,
|
||||
tool,
|
||||
)
|
||||
from agent_framework.azure import AzureAIAgentClient
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
@@ -118,7 +119,8 @@ async def pre_termination_middleware() -> None:
|
||||
print("\n--- Example 1: Pre-termination MiddlewareTypes ---")
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIAgentClient(credential=credential).as_agent(
|
||||
Agent(
|
||||
client=FoundryChatClient(credential=credential),
|
||||
name="WeatherAgent",
|
||||
instructions="You are a helpful weather assistant.",
|
||||
tools=get_weather,
|
||||
@@ -145,7 +147,8 @@ async def post_termination_middleware() -> None:
|
||||
print("\n--- Example 2: Post-termination MiddlewareTypes ---")
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIAgentClient(credential=credential).as_agent(
|
||||
Agent(
|
||||
client=FoundryChatClient(credential=credential),
|
||||
name="WeatherAgent",
|
||||
instructions="You are a helpful weather assistant.",
|
||||
tools=get_weather,
|
||||
|
||||
@@ -7,6 +7,7 @@ from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import (
|
||||
Agent,
|
||||
AgentContext,
|
||||
AgentResponse,
|
||||
AgentResponseUpdate,
|
||||
@@ -188,9 +189,10 @@ async def main() -> None:
|
||||
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
agent = OpenAIResponsesClient(
|
||||
middleware=[validate_weather_middleware, weather_override_middleware],
|
||||
).as_agent(
|
||||
agent = Agent(
|
||||
client=OpenAIResponsesClient(
|
||||
middleware=[validate_weather_middleware, weather_override_middleware],
|
||||
),
|
||||
name="WeatherAgent",
|
||||
instructions="You are a helpful weather assistant. Use the weather tool to get current conditions.",
|
||||
tools=get_weather,
|
||||
|
||||
@@ -4,8 +4,8 @@ import asyncio
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import FunctionInvocationContext, function_middleware, tool
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from agent_framework import Agent, FunctionInvocationContext, function_middleware, tool
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
@@ -149,10 +149,11 @@ async def pattern_1_single_agent_with_closure() -> None:
|
||||
print("Use case: Single agent with multiple tools sharing runtime context")
|
||||
print()
|
||||
|
||||
client = OpenAIChatClient(model_id="gpt-4o-mini")
|
||||
client = FoundryChatClient(model="gpt-4o-mini")
|
||||
|
||||
# Create agent with both tools and shared context via middleware
|
||||
communication_agent = client.as_agent(
|
||||
communication_agent = Agent(
|
||||
client=client,
|
||||
name="communication_agent",
|
||||
instructions=(
|
||||
"You are a communication assistant that can send emails and notifications. "
|
||||
@@ -294,17 +295,19 @@ async def pattern_2_hierarchical_with_kwargs_propagation() -> None:
|
||||
print(f"[SMSAgent] Received runtime context: {list(context.kwargs.keys())}")
|
||||
await call_next()
|
||||
|
||||
client = OpenAIChatClient(model_id="gpt-4o-mini")
|
||||
client = FoundryChatClient(model="gpt-4o-mini")
|
||||
|
||||
# Create specialized sub-agents
|
||||
email_agent = client.as_agent(
|
||||
email_agent = Agent(
|
||||
client=client,
|
||||
name="email_agent",
|
||||
instructions="You send emails using the send_email_v2 tool.",
|
||||
tools=[send_email_v2],
|
||||
middleware=[email_kwargs_tracker],
|
||||
)
|
||||
|
||||
sms_agent = client.as_agent(
|
||||
sms_agent = Agent(
|
||||
client=client,
|
||||
name="sms_agent",
|
||||
instructions="You send SMS messages using the send_sms tool.",
|
||||
tools=[send_sms],
|
||||
@@ -312,7 +315,8 @@ async def pattern_2_hierarchical_with_kwargs_propagation() -> None:
|
||||
)
|
||||
|
||||
# Create coordinator that delegates to sub-agents
|
||||
coordinator = client.as_agent(
|
||||
coordinator = Agent(
|
||||
client=client,
|
||||
name="coordinator",
|
||||
instructions=(
|
||||
"You coordinate communication tasks. "
|
||||
@@ -396,10 +400,11 @@ async def pattern_3_hierarchical_with_middleware() -> None:
|
||||
|
||||
auth_middleware = AuthContextMiddleware()
|
||||
|
||||
client = OpenAIChatClient(model_id="gpt-4o-mini")
|
||||
client = FoundryChatClient(model="gpt-4o-mini")
|
||||
|
||||
# Sub-agent with validation middleware
|
||||
protected_agent = client.as_agent(
|
||||
protected_agent = Agent(
|
||||
client=client,
|
||||
name="protected_agent",
|
||||
instructions="You perform protected operations that require authentication.",
|
||||
tools=[protected_operation],
|
||||
@@ -407,7 +412,8 @@ async def pattern_3_hierarchical_with_middleware() -> None:
|
||||
)
|
||||
|
||||
# Coordinator delegates to protected agent
|
||||
coordinator = client.as_agent(
|
||||
coordinator = Agent(
|
||||
client=client,
|
||||
name="coordinator",
|
||||
instructions="You coordinate protected operations. Delegate to protected_executor.",
|
||||
tools=[
|
||||
|
||||
@@ -5,11 +5,12 @@ from collections.abc import Awaitable, Callable
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import (
|
||||
Agent,
|
||||
AgentContext,
|
||||
InMemoryHistoryProvider,
|
||||
tool,
|
||||
)
|
||||
from agent_framework.azure import AzureOpenAIChatClient
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
@@ -81,7 +82,8 @@ async def main() -> None:
|
||||
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
|
||||
agent = Agent(
|
||||
client=FoundryChatClient(credential=AzureCliCredential()),
|
||||
name="WeatherAgent",
|
||||
instructions="You are a helpful weather assistant.",
|
||||
tools=get_weather,
|
||||
|
||||
@@ -6,10 +6,11 @@ from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import (
|
||||
Agent,
|
||||
FunctionInvocationContext,
|
||||
tool,
|
||||
)
|
||||
from agent_framework.azure import AzureAIAgentClient
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
@@ -103,7 +104,8 @@ async def main() -> None:
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIAgentClient(credential=credential).as_agent(
|
||||
Agent(
|
||||
client=FoundryChatClient(credential=credential),
|
||||
name="UtilityAgent",
|
||||
instructions="You are a helpful assistant that can provide weather information and current time.",
|
||||
tools=[get_weather, get_time],
|
||||
|
||||
@@ -50,8 +50,7 @@ def _reset_usage_counters() -> None:
|
||||
STREAMING_CALL_COUNT = 0
|
||||
|
||||
|
||||
def _create_agent(
|
||||
) -> Agent:
|
||||
def _create_agent() -> Agent:
|
||||
"""Create the shared agent used by both demonstrations."""
|
||||
return Agent(
|
||||
client=OpenAIResponsesClient(),
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Content, Message
|
||||
from agent_framework.azure import AzureOpenAIChatClient
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
@@ -21,12 +21,11 @@ def create_sample_image() -> str:
|
||||
async def test_image() -> None:
|
||||
"""Test image analysis with Azure OpenAI."""
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option. Requires AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_CHAT_DEPLOYMENT_NAME
|
||||
# authentication option. Requires AZURE_OPENAI_ENDPOINT and FOUNDRY_MODEL
|
||||
# environment variables to be set.
|
||||
# Alternatively, you can pass deployment_name explicitly:
|
||||
# client = AzureOpenAIChatClient(credential=AzureCliCredential(), deployment_name="your-deployment-name")
|
||||
client = AzureOpenAIChatClient(credential=AzureCliCredential())
|
||||
|
||||
# client = FoundryChatClient(credential=AzureCliCredential(), model="your-deployment-name")
|
||||
client = FoundryChatClient(credential=AzureCliCredential())
|
||||
image_uri = create_sample_image()
|
||||
message = Message(
|
||||
role="user",
|
||||
@@ -35,7 +34,6 @@ async def test_image() -> None:
|
||||
Content.from_uri(uri=image_uri, media_type="image/png"),
|
||||
],
|
||||
)
|
||||
|
||||
response = await client.get_response([message])
|
||||
print(f"Image Response: {response}")
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import asyncio
|
||||
from pathlib import Path
|
||||
|
||||
from agent_framework import Content, Message
|
||||
from agent_framework.azure import AzureOpenAIResponsesClient
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
@@ -30,11 +30,11 @@ def create_sample_image() -> str:
|
||||
async def test_image() -> None:
|
||||
"""Test image analysis with Azure OpenAI Responses API."""
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option. Requires AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME
|
||||
# authentication option. Requires AZURE_OPENAI_ENDPOINT and FOUNDRY_MODEL
|
||||
# environment variables to be set.
|
||||
# Alternatively, you can pass deployment_name explicitly:
|
||||
# client = AzureOpenAIResponsesClient(credential=AzureCliCredential(), deployment_name="your-deployment-name")
|
||||
client = AzureOpenAIResponsesClient(credential=AzureCliCredential())
|
||||
# client = FoundryChatClient(credential=AzureCliCredential(), model="your-deployment-name")
|
||||
client = FoundryChatClient(credential=AzureCliCredential())
|
||||
|
||||
image_uri = create_sample_image()
|
||||
message = Message(
|
||||
@@ -51,7 +51,7 @@ async def test_image() -> None:
|
||||
|
||||
async def test_pdf() -> None:
|
||||
"""Test PDF document analysis with Azure OpenAI Responses API."""
|
||||
client = AzureOpenAIResponsesClient(credential=AzureCliCredential())
|
||||
client = FoundryChatClient(credential=AzureCliCredential())
|
||||
|
||||
pdf_bytes = load_sample_pdf()
|
||||
message = Message(
|
||||
|
||||
@@ -6,7 +6,7 @@ import struct
|
||||
from pathlib import Path
|
||||
|
||||
from agent_framework import Content, Message
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
@@ -46,7 +46,7 @@ def create_sample_audio() -> str:
|
||||
|
||||
async def test_image() -> None:
|
||||
"""Test image analysis with OpenAI."""
|
||||
client = OpenAIChatClient(model_id="gpt-4o")
|
||||
client = FoundryChatClient(model="gpt-4o")
|
||||
|
||||
image_uri = create_sample_image()
|
||||
message = Message(
|
||||
@@ -63,7 +63,7 @@ async def test_image() -> None:
|
||||
|
||||
async def test_audio() -> None:
|
||||
"""Test audio analysis with OpenAI."""
|
||||
client = OpenAIChatClient(model_id="gpt-4o-audio-preview")
|
||||
client = FoundryChatClient(model="gpt-4o-audio-preview")
|
||||
|
||||
audio_uri = create_sample_audio()
|
||||
message = Message(
|
||||
@@ -80,7 +80,7 @@ async def test_audio() -> None:
|
||||
|
||||
async def test_pdf() -> None:
|
||||
"""Test PDF document analysis with OpenAI."""
|
||||
client = OpenAIChatClient(model_id="gpt-4o")
|
||||
client = FoundryChatClient(model="gpt-4o")
|
||||
|
||||
pdf_bytes = load_sample_pdf()
|
||||
message = Message(
|
||||
|
||||
@@ -88,18 +88,20 @@ configure_azure_monitor(
|
||||
# This is optional if ENABLE_INSTRUMENTATION and or ENABLE_SENSITIVE_DATA are set in env vars
|
||||
enable_instrumentation(enable_sensitive_data=False)
|
||||
```
|
||||
For Azure AI projects, use the `client.configure_azure_monitor()` method which wraps the calls to `configure_azure_monitor()` and `enable_instrumentation()`:
|
||||
For Microsoft Foundry projects, use `client.configure_azure_monitor()` which retrieves the connection string from the project and configures everything:
|
||||
|
||||
```python
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from azure.ai.projects.aio import AIProjectClient
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity import AzureCliCredential
|
||||
|
||||
async with (
|
||||
AIProjectClient(...) as project_client,
|
||||
AzureAIClient(project_client=project_client) as client,
|
||||
):
|
||||
# Automatically configures Azure Monitor with connection string from project
|
||||
await client.configure_azure_monitor(enable_live_metrics=True)
|
||||
client = FoundryChatClient(
|
||||
project_endpoint="https://your-project.services.ai.azure.com",
|
||||
model="gpt-4o",
|
||||
credential=AzureCliCredential(),
|
||||
)
|
||||
|
||||
# Automatically configures Azure Monitor with connection string from project
|
||||
await client.configure_azure_monitor(enable_sensitive_data=True)
|
||||
```
|
||||
|
||||
Or with [Langfuse](https://langfuse.com/integrations/frameworks/microsoft-agent-framework):
|
||||
@@ -227,8 +229,7 @@ This folder contains different samples demonstrating how to use telemetry in var
|
||||
| [configure_otel_providers_with_parameters.py](./configure_otel_providers_with_parameters.py) | **Recommended starting point**: Shows how to create custom exporters with specific configuration and pass them to `configure_otel_providers()`. Useful for advanced scenarios. |
|
||||
| [configure_otel_providers_with_env_var.py](./configure_otel_providers_with_env_var.py) | Shows how to setup telemetry using standard OpenTelemetry environment variables (`OTEL_EXPORTER_OTLP_*`). |
|
||||
| [agent_observability.py](./agent_observability.py) | Shows telemetry collection for an agentic application with tool calls using environment variables. |
|
||||
| [agent_with_foundry_tracing.py](./agent_with_foundry_tracing.py) | Shows Azure Monitor integration with Foundry for any chat client. |
|
||||
| [azure_ai_agent_observability.py](./azure_ai_agent_observability.py) | Shows Azure Monitor integration for a AzureAIClient. |
|
||||
| [foundry_tracing.py](./foundry_tracing.py) | Shows Azure Monitor integration with Foundry for any chat client. |
|
||||
| [advanced_manual_setup_console_output.py](./advanced_manual_setup_console_output.py) | Advanced: Shows manual setup of exporters and providers with console output. Useful for understanding how observability works under the hood. |
|
||||
| [advanced_zero_code.py](./advanced_zero_code.py) | Advanced: Shows zero-code telemetry setup using the `opentelemetry-enable_instrumentation` CLI tool. |
|
||||
| [workflow_observability.py](./workflow_observability.py) | Shows telemetry collection for a workflow with multiple executors and message passing. |
|
||||
@@ -347,15 +348,16 @@ setup_observability(
|
||||
|
||||
**After (Current):**
|
||||
```python
|
||||
# For Azure AI projects
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from azure.ai.projects.aio import AIProjectClient
|
||||
# For Microsoft Foundry projects
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from azure.identity import AzureCliCredential
|
||||
|
||||
async with (
|
||||
AIProjectClient(...) as project_client,
|
||||
AzureAIClient(project_client=project_client) as client,
|
||||
):
|
||||
await client.configure_azure_monitor(enable_live_metrics=True)
|
||||
client = FoundryChatClient(
|
||||
project_endpoint="https://your-project.services.ai.azure.com",
|
||||
model="gpt-4o",
|
||||
credential=AzureCliCredential(),
|
||||
)
|
||||
await client.configure_azure_monitor(enable_live_metrics=True)
|
||||
|
||||
# For non-Azure AI projects
|
||||
from azure.monitor.opentelemetry import configure_azure_monitor
|
||||
|
||||
@@ -6,8 +6,8 @@ from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import Message, tool
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from agent_framework.observability import enable_instrumentation
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
from opentelemetry._logs import set_logger_provider
|
||||
from opentelemetry.metrics import set_meter_provider
|
||||
@@ -115,7 +115,7 @@ async def run_chat_client() -> None:
|
||||
2 spans with gen_ai.operation.name=execute_tool
|
||||
|
||||
"""
|
||||
client = OpenAIChatClient()
|
||||
client = FoundryChatClient()
|
||||
message = "What's the weather in Amsterdam and in Paris?"
|
||||
print(f"User: {message}")
|
||||
print("Assistant: ", end="")
|
||||
|
||||
@@ -5,8 +5,8 @@ from random import randint
|
||||
from typing import TYPE_CHECKING, Annotated
|
||||
|
||||
from agent_framework import Message, tool
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from agent_framework.observability import get_tracer
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from dotenv import load_dotenv
|
||||
from opentelemetry.trace import SpanKind
|
||||
from opentelemetry.trace.span import format_trace_id
|
||||
@@ -103,7 +103,7 @@ async def main() -> None:
|
||||
with get_tracer().start_as_current_span("Zero Code", kind=SpanKind.CLIENT) as current_span:
|
||||
print(f"Trace ID: {format_trace_id(current_span.get_span_context().trace_id)}")
|
||||
|
||||
client = OpenAIResponsesClient()
|
||||
client = FoundryChatClient()
|
||||
|
||||
await run_chat_client(client, stream=True)
|
||||
await run_chat_client(client, stream=False)
|
||||
|
||||
@@ -5,8 +5,8 @@ from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from agent_framework.observability import configure_otel_providers, get_tracer
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from dotenv import load_dotenv
|
||||
from opentelemetry.trace import SpanKind
|
||||
from opentelemetry.trace.span import format_trace_id
|
||||
@@ -47,7 +47,7 @@ async def main():
|
||||
print(f"Trace ID: {format_trace_id(current_span.get_span_context().trace_id)}")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIChatClient(),
|
||||
client=FoundryChatClient(),
|
||||
tools=get_weather,
|
||||
name="WeatherAgent",
|
||||
instructions="You are a weather assistant.",
|
||||
|
||||
@@ -1,107 +0,0 @@
|
||||
# /// script
|
||||
# requires-python = ">=3.10"
|
||||
# dependencies = [
|
||||
# "azure-monitor-opentelemetry",
|
||||
# ]
|
||||
# ///
|
||||
# Run with any PEP 723 compatible runner, e.g.:
|
||||
# uv run python/samples/02-agents/observability/agent_with_foundry_tracing.py
|
||||
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.observability import create_resource, enable_instrumentation, get_tracer
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from azure.ai.projects.aio import AIProjectClient
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from azure.monitor.opentelemetry import configure_azure_monitor
|
||||
from dotenv import load_dotenv
|
||||
from opentelemetry.trace import SpanKind
|
||||
from opentelemetry.trace.span import format_trace_id
|
||||
from pydantic import Field
|
||||
|
||||
"""
|
||||
This sample shows you can can setup telemetry in Microsoft Foundry for a custom agent.
|
||||
First ensure you have a Foundry workspace with Application Insights enabled.
|
||||
And use the Operate tab to Register an Agent.
|
||||
Set the OpenTelemetry agent ID to the value used below in the Agent creation: `weather-agent` (or change both).
|
||||
The sample uses the Azure Monitor OpenTelemetry exporter to send traces to Application Insights.
|
||||
So ensure you have the `azure-monitor-opentelemetry` package installed.
|
||||
"""
|
||||
|
||||
# For loading the `AZURE_AI_PROJECT_ENDPOINT` environment variable
|
||||
load_dotenv()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# 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")
|
||||
async def get_weather(
|
||||
location: Annotated[str, Field(description="The location to get the weather for.")],
|
||||
) -> str:
|
||||
"""Get the weather for a given location."""
|
||||
await asyncio.sleep(randint(0, 10) / 10.0) # Simulate a network call
|
||||
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():
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
|
||||
):
|
||||
# This will enable tracing and configure the application to send telemetry data to the
|
||||
# Application Insights instance attached to the Azure AI project.
|
||||
# This will override any existing configuration.
|
||||
try:
|
||||
conn_string = await project_client.telemetry.get_application_insights_connection_string()
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"No Application Insights connection string found for the Azure AI Project. "
|
||||
"Please ensure Application Insights is configured in your Azure AI project, "
|
||||
"or call configure_otel_providers() manually with custom exporters."
|
||||
)
|
||||
return
|
||||
configure_azure_monitor(
|
||||
connection_string=conn_string,
|
||||
enable_live_metrics=True,
|
||||
resource=create_resource(),
|
||||
enable_performance_counters=False,
|
||||
)
|
||||
# This call is not necessary if you have the environment variable ENABLE_INSTRUMENTATION=true set
|
||||
# If not or set to false, or if you want to enable or disable sensitive data collection, call this function.
|
||||
enable_instrumentation(enable_sensitive_data=True)
|
||||
print("Observability is set up. Starting Weather Agent...")
|
||||
|
||||
questions = ["What's the weather in Amsterdam?", "and in Paris, and which is better?", "Why is the sky blue?"]
|
||||
|
||||
with get_tracer().start_as_current_span("Weather Agent Chat", kind=SpanKind.CLIENT) as current_span:
|
||||
print(f"Trace ID: {format_trace_id(current_span.get_span_context().trace_id)}")
|
||||
|
||||
agent = Agent(
|
||||
client=OpenAIResponsesClient(),
|
||||
tools=get_weather,
|
||||
name="WeatherAgent",
|
||||
instructions="You are a weather assistant.",
|
||||
id="weather-agent",
|
||||
)
|
||||
session = agent.create_session()
|
||||
for question in questions:
|
||||
print(f"\nUser: {question}")
|
||||
print(f"{agent.name}: ", end="")
|
||||
async for update in agent.run(question, session=session, stream=True):
|
||||
if update.text:
|
||||
print(update.text, end="")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,78 +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.azure import AzureAIClient
|
||||
from agent_framework.observability import get_tracer
|
||||
from azure.ai.projects.aio import AIProjectClient
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from opentelemetry.trace import SpanKind
|
||||
from opentelemetry.trace.span import format_trace_id
|
||||
from pydantic import Field
|
||||
|
||||
"""
|
||||
This sample shows you can setup telemetry for an Azure AI agent.
|
||||
It uses the Azure AI client to setup the telemetry, this calls out to
|
||||
Azure AI for the connection string of the attached Application Insights
|
||||
instance.
|
||||
|
||||
You must add an Application Insights instance to your Azure AI project
|
||||
for this sample to work.
|
||||
"""
|
||||
|
||||
# For loading the `AZURE_AI_PROJECT_ENDPOINT` environment variable
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# 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")
|
||||
async def get_weather(
|
||||
location: Annotated[str, Field(description="The location to get the weather for.")],
|
||||
) -> str:
|
||||
"""Get the weather for a given location."""
|
||||
await asyncio.sleep(randint(0, 10) / 10.0) # Simulate a network call
|
||||
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():
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
|
||||
AzureAIClient(project_client=project_client) as client,
|
||||
):
|
||||
# This will enable tracing and configure the application to send telemetry data to the
|
||||
# Application Insights instance attached to the Azure AI project.
|
||||
# This will override any existing configuration.
|
||||
await client.configure_azure_monitor(enable_live_metrics=True)
|
||||
|
||||
questions = ["What's the weather in Amsterdam?", "and in Paris, and which is better?", "Why is the sky blue?"]
|
||||
|
||||
with get_tracer().start_as_current_span("Single Agent Chat", kind=SpanKind.CLIENT) as current_span:
|
||||
print(f"Trace ID: {format_trace_id(current_span.get_span_context().trace_id)}")
|
||||
|
||||
agent = Agent(
|
||||
client=client,
|
||||
tools=get_weather,
|
||||
name="WeatherAgent",
|
||||
instructions="You are a weather assistant.",
|
||||
id="edvan-weather-agent",
|
||||
)
|
||||
session = agent.create_session()
|
||||
for question in questions:
|
||||
print(f"\nUser: {question}")
|
||||
print(f"{agent.name}: ", end="")
|
||||
async for update in agent.run(question, session=session, stream=True):
|
||||
if update.text:
|
||||
print(update.text, end="")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -7,8 +7,8 @@ from random import randint
|
||||
from typing import TYPE_CHECKING, Annotated, Literal
|
||||
|
||||
from agent_framework import Message, tool
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from agent_framework.observability import configure_otel_providers, get_tracer
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from dotenv import load_dotenv
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.trace.span import format_trace_id
|
||||
@@ -114,7 +114,7 @@ async def main(scenario: Literal["client", "client_stream", "tool", "all"] = "al
|
||||
with get_tracer().start_as_current_span("Sample Scenarios", kind=trace.SpanKind.CLIENT) as current_span:
|
||||
print(f"Trace ID: {format_trace_id(current_span.get_span_context().trace_id)}")
|
||||
|
||||
client = OpenAIResponsesClient()
|
||||
client = FoundryChatClient()
|
||||
|
||||
# Scenarios where telemetry is collected in the SDK, from the most basic to the most complex.
|
||||
if scenario == "tool" or scenario == "all":
|
||||
|
||||
@@ -8,8 +8,8 @@ from random import randint
|
||||
from typing import TYPE_CHECKING, Annotated, Literal
|
||||
|
||||
from agent_framework import Message, tool
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from agent_framework.observability import configure_otel_providers, get_tracer
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from dotenv import load_dotenv
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.trace.span import format_trace_id
|
||||
@@ -153,7 +153,7 @@ async def main(scenario: Literal["client", "client_stream", "tool", "all"] = "al
|
||||
with get_tracer().start_as_current_span("Sample Scenarios", kind=trace.SpanKind.CLIENT) as current_span:
|
||||
print(f"Trace ID: {format_trace_id(current_span.get_span_context().trace_id)}")
|
||||
|
||||
client = OpenAIResponsesClient()
|
||||
client = FoundryChatClient()
|
||||
|
||||
# Scenarios where telemetry is collected in the SDK, from the most basic to the most complex.
|
||||
if scenario == "tool" or scenario == "all":
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
# /// script
|
||||
# requires-python = ">=3.10"
|
||||
# dependencies = [
|
||||
# "azure-monitor-opentelemetry",
|
||||
# ]
|
||||
# ///
|
||||
# Run with any PEP 723 compatible runner, e.g.:
|
||||
# uv run python/samples/02-agents/observability/foundry_tracing.py
|
||||
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.foundry import FoundryChatClient
|
||||
from agent_framework.observability import get_tracer
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from opentelemetry.trace import SpanKind
|
||||
from opentelemetry.trace.span import format_trace_id
|
||||
from pydantic import Field
|
||||
|
||||
"""
|
||||
This sample shows how to setup telemetry in Microsoft Foundry for a custom agent
|
||||
using ``FoundryChatClient.configure_azure_monitor()``.
|
||||
|
||||
First ensure you have a Foundry workspace with Application Insights enabled.
|
||||
And use the Operate tab to Register an Agent.
|
||||
Set the OpenTelemetry agent ID to the value used below in the Agent creation: ``weather-agent``
|
||||
(or change both).
|
||||
|
||||
Environment variables:
|
||||
FOUNDRY_PROJECT_ENDPOINT — Microsoft Foundry project endpoint
|
||||
FOUNDRY_MODEL — Model deployment name (e.g. gpt-4o)
|
||||
"""
|
||||
|
||||
load_dotenv()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# NOTE: approval_mode="never_require" is for sample brevity.
|
||||
@tool(approval_mode="never_require")
|
||||
async def get_weather(
|
||||
location: Annotated[str, Field(description="The location to get the weather for.")],
|
||||
) -> str:
|
||||
"""Get the weather for a given location."""
|
||||
await asyncio.sleep(randint(0, 10) / 10.0) # Simulate a network call
|
||||
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():
|
||||
client = FoundryChatClient(
|
||||
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
|
||||
model=os.environ["FOUNDRY_MODEL"],
|
||||
credential=AzureCliCredential(),
|
||||
)
|
||||
|
||||
# configure_azure_monitor() retrieves the Application Insights connection string
|
||||
# from the project client and sets up tracing automatically.
|
||||
await client.configure_azure_monitor(
|
||||
enable_sensitive_data=True,
|
||||
enable_live_metrics=True,
|
||||
)
|
||||
print("Observability is set up. Starting Weather Agent...")
|
||||
|
||||
questions = ["What's the weather in Amsterdam?", "and in Paris, and which is better?", "Why is the sky blue?"]
|
||||
|
||||
with get_tracer().start_as_current_span("Weather Agent Chat", kind=SpanKind.CLIENT) as current_span:
|
||||
print(f"Trace ID: {format_trace_id(current_span.get_span_context().trace_id)}")
|
||||
|
||||
agent = Agent(
|
||||
client=client,
|
||||
tools=[get_weather],
|
||||
name="WeatherAgent",
|
||||
instructions="You are a weather assistant.",
|
||||
id="weather-agent",
|
||||
)
|
||||
session = agent.create_session()
|
||||
for question in questions:
|
||||
print(f"\nUser: {question}")
|
||||
print(f"{agent.name}: ", end="")
|
||||
async for update in agent.run(question, session=session, stream=True):
|
||||
if update.text:
|
||||
print(update.text, end="")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -6,14 +6,12 @@ This directory groups provider-specific samples for Agent Framework.
|
||||
| --- | --- |
|
||||
| [`anthropic/`](anthropic/) | Anthropic Claude samples using both `AnthropicClient` and `ClaudeAgent`, including tools, MCP, sessions, and Foundry Anthropic integration. |
|
||||
| [`amazon/`](amazon/) | AWS Bedrock samples using `BedrockChatClient`, including tool-enabled agent usage. |
|
||||
| [`azure_ai/`](azure_ai/) | Azure AI Foundry V2 (`azure-ai-projects`) samples with `AzureAIClient`, from basic setup to advanced patterns like search, memory, A2A, MCP, and provider methods. |
|
||||
| [`azure_ai_agent/`](azure_ai_agent/) | Azure AI Foundry V1 (`azure-ai-agents`) samples with `AzureAIAgentsProvider`, including provider methods and common hosted tool integrations. |
|
||||
| [`azure_openai/`](azure_openai/) | Azure OpenAI samples for Assistants, Chat, and Responses clients, with examples for sessions, tools, MCP, file search, and code interpreter. |
|
||||
| [`azure/`](azure/) | Azure OpenAI chat completion samples using `OpenAIChatCompletionClient`, including basic usage, explicit configuration, tools, and sessions. |
|
||||
| [`copilotstudio/`](copilotstudio/) | Microsoft Copilot Studio agent samples, including required environment/app registration setup and explicit authentication patterns. |
|
||||
| [`custom/`](custom/) | Framework extensibility samples for building custom `BaseAgent` and `BaseChatClient` implementations, including layer-composition guidance. |
|
||||
| [`foundry_local/`](foundry_local/) | Foundry Local samples using `FoundryLocalClient` for local model inference with streaming, non-streaming, and tool-calling patterns. |
|
||||
| [`foundry/`](foundry/) | Microsoft Foundry and Foundry Local samples using `FoundryChatClient`, `FoundryAgent`, `RawFoundryAgentChatClient`, and `FoundryLocalClient` for hosted agents, Responses API, local inference, tools, MCP, and sessions. |
|
||||
| [`github_copilot/`](github_copilot/) | `GitHubCopilotAgent` samples showing basic usage, session handling, permission-scoped shell/file/url access, and MCP integration. |
|
||||
| [`ollama/`](ollama/) | Local Ollama samples using `OllamaChatClient` (recommended) plus OpenAI-compatible Ollama setup, including reasoning and multimodal examples. |
|
||||
| [`openai/`](openai/) | OpenAI provider samples for Assistants, Chat, and Responses clients, including tools, structured output, sessions, MCP, web search, and multimodal tasks. |
|
||||
| [`openai/`](openai/) | OpenAI provider samples for Chat and Chat Completion clients, including tools, structured output, sessions, MCP, web search, and multimodal tasks. |
|
||||
|
||||
Each folder has its own README with setup requirements and file-by-file details.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.anthropic import AnthropicChatOptions, AnthropicClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
@@ -31,7 +31,8 @@ async def main() -> None:
|
||||
# Create web search tool configuration using instance method
|
||||
web_search_tool = client.get_web_search_tool()
|
||||
|
||||
agent = client.as_agent(
|
||||
agent = Agent(
|
||||
client=client,
|
||||
name="DocsAgent",
|
||||
instructions="You are a helpful agent for both Microsoft docs questions and general questions.",
|
||||
tools=[mcp_tool, web_search_tool],
|
||||
|
||||
@@ -4,7 +4,7 @@ import asyncio
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import tool
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.anthropic import AnthropicClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
@@ -34,7 +34,8 @@ async def non_streaming_example() -> None:
|
||||
"""Example of non-streaming response (get the complete result at once)."""
|
||||
print("=== Non-streaming Response Example ===")
|
||||
|
||||
agent = AnthropicClient().as_agent(
|
||||
agent = Agent(
|
||||
client=AnthropicClient(),
|
||||
name="WeatherAgent",
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
@@ -50,7 +51,8 @@ async def streaming_example() -> None:
|
||||
"""Example of streaming response (get results as they are generated)."""
|
||||
print("=== Streaming Response Example ===")
|
||||
|
||||
agent = AnthropicClient().as_agent(
|
||||
agent = Agent(
|
||||
client=AnthropicClient(),
|
||||
name="WeatherAgent",
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.anthropic import AnthropicClient
|
||||
from anthropic import AsyncAnthropicFoundry
|
||||
from dotenv import load_dotenv
|
||||
@@ -42,7 +42,8 @@ async def main() -> None:
|
||||
# Create web search tool configuration using instance method
|
||||
web_search_tool = client.get_web_search_tool()
|
||||
|
||||
agent = client.as_agent(
|
||||
agent = Agent(
|
||||
client=client,
|
||||
name="DocsAgent",
|
||||
instructions="You are a helpful agent for both Microsoft docs questions and general questions.",
|
||||
tools=[mcp_tool, web_search_tool],
|
||||
|
||||
@@ -4,7 +4,7 @@ import asyncio
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from agent_framework import Content
|
||||
from agent_framework import Agent, Content
|
||||
from agent_framework.anthropic import AnthropicChatOptions, AnthropicClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
@@ -35,7 +35,8 @@ async def main() -> None:
|
||||
|
||||
# Create a agent with the pptx skill enabled
|
||||
# Skills also need the code interpreter tool to function
|
||||
agent = client.as_agent(
|
||||
agent = Agent(
|
||||
client=client,
|
||||
name="DocsAgent",
|
||||
instructions="You are a helpful agent for creating powerpoint presentations.",
|
||||
tools=client.get_code_interpreter_tool(),
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
# Azure Provider Samples
|
||||
|
||||
This folder contains Azure OpenAI chat completion samples for Agent Framework.
|
||||
|
||||
## Azure OpenAI ChatCompletionClient Samples
|
||||
|
||||
| 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 |
|
||||
+7
-5
@@ -4,8 +4,8 @@ import asyncio
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import tool
|
||||
from agent_framework.azure import AzureOpenAIChatClient
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.openai import OpenAIChatCompletionClient
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
@@ -16,7 +16,7 @@ load_dotenv()
|
||||
"""
|
||||
Azure OpenAI Chat Client Basic Example
|
||||
|
||||
This sample demonstrates basic usage of AzureOpenAIChatClient for direct chat-based
|
||||
This sample demonstrates basic usage of OpenAIChatCompletionClient for direct chat-based
|
||||
interactions, showing both streaming and non-streaming responses.
|
||||
"""
|
||||
|
||||
@@ -40,7 +40,8 @@ async def non_streaming_example() -> None:
|
||||
# Create agent with Azure Chat Client
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
|
||||
agent = Agent(
|
||||
client=OpenAIChatCompletionClient(credential=AzureCliCredential()),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
@@ -58,7 +59,8 @@ async def streaming_example() -> None:
|
||||
# Create agent with Azure Chat Client
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
|
||||
agent = Agent(
|
||||
client=OpenAIChatCompletionClient(credential=AzureCliCredential()),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
+8
-6
@@ -5,8 +5,8 @@ import os
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import tool
|
||||
from agent_framework.azure import AzureOpenAIChatClient
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.openai import OpenAIChatCompletionClient
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
@@ -39,13 +39,15 @@ async def main() -> None:
|
||||
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
agent = AzureOpenAIChatClient(
|
||||
deployment_name=os.environ["AZURE_OPENAI_CHAT_DEPLOYMENT_NAME"],
|
||||
_client = OpenAIChatCompletionClient(
|
||||
model=os.environ["AZURE_OPENAI_CHAT_DEPLOYMENT_NAME"],
|
||||
endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
|
||||
credential=AzureCliCredential(),
|
||||
).as_agent(
|
||||
)
|
||||
agent = Agent(
|
||||
client=_client,
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
tools=[get_weather],
|
||||
)
|
||||
|
||||
result = await agent.run("What's the weather like in New York?")
|
||||
+4
-4
@@ -6,7 +6,7 @@ from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import Agent, tool
|
||||
from agent_framework.azure import AzureOpenAIChatClient
|
||||
from agent_framework.openai import OpenAIChatCompletionClient
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
@@ -50,7 +50,7 @@ async def tools_on_agent_level() -> None:
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
agent = Agent(
|
||||
client=AzureOpenAIChatClient(credential=AzureCliCredential()),
|
||||
client=OpenAIChatCompletionClient(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
|
||||
)
|
||||
@@ -82,7 +82,7 @@ async def tools_on_run_level() -> None:
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
agent = Agent(
|
||||
client=AzureOpenAIChatClient(credential=AzureCliCredential()),
|
||||
client=OpenAIChatCompletionClient(credential=AzureCliCredential()),
|
||||
instructions="You are a helpful assistant.",
|
||||
# No tools defined here
|
||||
)
|
||||
@@ -114,7 +114,7 @@ async def mixed_tools_example() -> None:
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
agent = Agent(
|
||||
client=AzureOpenAIChatClient(credential=AzureCliCredential()),
|
||||
client=OpenAIChatCompletionClient(credential=AzureCliCredential()),
|
||||
instructions="You are a comprehensive assistant that can help with various information requests.",
|
||||
tools=[get_weather], # Base tool available for all queries
|
||||
)
|
||||
+5
-5
@@ -5,7 +5,7 @@ from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import Agent, AgentSession, InMemoryHistoryProvider, tool
|
||||
from agent_framework.azure import AzureOpenAIChatClient
|
||||
from agent_framework.openai import OpenAIChatCompletionClient
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
@@ -40,7 +40,7 @@ async def example_with_automatic_session_creation() -> None:
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
agent = Agent(
|
||||
client=AzureOpenAIChatClient(credential=AzureCliCredential()),
|
||||
client=OpenAIChatCompletionClient(credential=AzureCliCredential()),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
@@ -67,7 +67,7 @@ async def example_with_session_persistence() -> None:
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
agent = Agent(
|
||||
client=AzureOpenAIChatClient(credential=AzureCliCredential()),
|
||||
client=OpenAIChatCompletionClient(credential=AzureCliCredential()),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
@@ -102,7 +102,7 @@ async def example_with_existing_session_messages() -> None:
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
agent = Agent(
|
||||
client=AzureOpenAIChatClient(credential=AzureCliCredential()),
|
||||
client=OpenAIChatCompletionClient(credential=AzureCliCredential()),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
@@ -125,7 +125,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=AzureOpenAIChatClient(credential=AzureCliCredential()),
|
||||
client=OpenAIChatCompletionClient(credential=AzureCliCredential()),
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
@@ -1,95 +0,0 @@
|
||||
# Azure AI Agent Examples
|
||||
|
||||
This folder contains examples demonstrating different ways to create and use agents with the Azure AI client from the `agent_framework.azure` package. These examples use the `AzureAIClient` with the `azure-ai-projects` 2.x (V2) API surface (see [changelog](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-projects/CHANGELOG.md#200b1-2025-11-11)). For V1 (`azure-ai-agents` 1.x) samples using `AzureAIAgentClient`, see the [Azure AI V1 examples folder](../azure_ai_agent/). When using preview-only agent creation features on GA SDK versions, create `AIProjectClient` with `allow_preview=True`.
|
||||
|
||||
## Examples
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| [`azure_ai_basic.py`](azure_ai_basic.py) | The simplest way to create an agent using `AzureAIProjectAgentProvider`. Demonstrates both streaming and non-streaming responses with function tools. Shows automatic agent creation and basic weather functionality. |
|
||||
| [`azure_ai_provider_methods.py`](azure_ai_provider_methods.py) | Comprehensive guide to `AzureAIProjectAgentProvider` methods: `create_agent()` for creating new agents, `get_agent()` for retrieving existing agents (by name, reference, or details), and `as_agent()` for wrapping SDK objects without HTTP calls. |
|
||||
| [`azure_ai_use_latest_version.py`](azure_ai_use_latest_version.py) | Demonstrates how to reuse the latest version of an existing agent instead of creating a new agent version on each instantiation by using `provider.get_agent()` to retrieve the latest version. |
|
||||
| [`azure_ai_with_agent_as_tool.py`](azure_ai_with_agent_as_tool.py) | Shows how to use the agent-as-tool pattern with Azure AI agents, where one agent delegates work to specialized sub-agents wrapped as tools using `as_tool()`. Demonstrates hierarchical agent architectures. |
|
||||
| [`azure_ai_with_agent_to_agent.py`](azure_ai_with_agent_to_agent.py) | Shows how to use Agent-to-Agent (A2A) capabilities with Azure AI agents to enable communication with other agents using the A2A protocol. Requires an A2A connection configured in your Azure AI project. |
|
||||
| [`azure_ai_with_azure_ai_search.py`](azure_ai_with_azure_ai_search.py) | Shows how to use Azure AI Search with Azure AI agents to search through indexed data and answer user questions with proper citations. Requires an Azure AI Search connection and index configured in your Azure AI project. |
|
||||
| [`azure_ai_with_bing_grounding.py`](azure_ai_with_bing_grounding.py) | Shows how to use Bing Grounding search with Azure AI agents to search the web for current information and provide grounded responses with citations. Requires a Bing connection configured in your Azure AI project. |
|
||||
| [`azure_ai_with_bing_custom_search.py`](azure_ai_with_bing_custom_search.py) | Shows how to use Bing Custom Search with Azure AI agents to search custom search instances and provide responses with relevant results. Requires a Bing Custom Search connection and instance configured in your Azure AI project. |
|
||||
| [`azure_ai_with_browser_automation.py`](azure_ai_with_browser_automation.py) | Shows how to use Browser Automation with Azure AI agents to perform automated web browsing tasks and provide responses based on web interactions. Requires a Browser Automation connection configured in your Azure AI project. |
|
||||
| [`azure_ai_with_code_interpreter.py`](azure_ai_with_code_interpreter.py) | Shows how to use `AzureAIClient.get_code_interpreter_tool()` with Azure AI agents to write and execute Python code for mathematical problem solving and data analysis. |
|
||||
| [`azure_ai_with_code_interpreter_file_generation.py`](azure_ai_with_code_interpreter_file_generation.py) | Shows how to retrieve file IDs from code interpreter generated files using both streaming and non-streaming approaches. |
|
||||
| [`azure_ai_with_code_interpreter_file_download.py`](azure_ai_with_code_interpreter_file_download.py) | Shows how to download files generated by code interpreter using the OpenAI containers API. |
|
||||
| [`azure_ai_with_content_filtering.py`](azure_ai_with_content_filtering.py) | Shows how to enable content filtering (RAI policy) on Azure AI agents using `RaiConfig`. Requires creating an RAI policy in Azure AI Foundry portal first. |
|
||||
| [`azure_ai_with_existing_agent.py`](azure_ai_with_existing_agent.py) | Shows how to work with a pre-existing agent by providing the agent name and version to the Azure AI client. Demonstrates agent reuse patterns for production scenarios. |
|
||||
| [`azure_ai_with_existing_conversation.py`](azure_ai_with_existing_conversation.py) | Demonstrates how to use an existing conversation created on the service side with Azure AI agents. Shows two approaches: specifying conversation ID at the client level and using AgentSession with an existing conversation ID. |
|
||||
| [`azure_ai_with_application_endpoint.py`](azure_ai_with_application_endpoint.py) | Demonstrates calling the Azure AI application-scoped endpoint. |
|
||||
| [`azure_ai_with_explicit_settings.py`](azure_ai_with_explicit_settings.py) | Shows how to create an agent with explicitly configured `AzureAIClient` settings, including project endpoint, model deployment, and credentials rather than relying on environment variable defaults. |
|
||||
| [`azure_ai_with_file_search.py`](azure_ai_with_file_search.py) | Shows how to use `AzureAIClient.get_file_search_tool()` with Azure AI agents to upload files, create vector stores, and enable agents to search through uploaded documents to answer user questions. |
|
||||
| [`azure_ai_with_hosted_mcp.py`](azure_ai_with_hosted_mcp.py) | Shows how to integrate hosted Model Context Protocol (MCP) tools with Azure AI Agent using `AzureAIClient.get_mcp_tool()`. |
|
||||
| [`azure_ai_with_local_mcp.py`](azure_ai_with_local_mcp.py) | Shows how to integrate local Model Context Protocol (MCP) tools with Azure AI agents. |
|
||||
| [`azure_ai_with_response_format.py`](azure_ai_with_response_format.py) | Shows how to use structured outputs (response format) with Azure AI agents using Pydantic models to enforce specific response schemas. |
|
||||
| [`azure_ai_with_runtime_json_schema.py`](azure_ai_with_runtime_json_schema.py) | Shows how to use structured outputs (response format) with Azure AI agents using a JSON schema to enforce specific response schemas. |
|
||||
| [`azure_ai_with_search_context_agentic.py`](../../context_providers/azure_ai_search/azure_ai_with_search_context_agentic.py) | Shows how to use AzureAISearchContextProvider with agentic mode. Uses Knowledge Bases for multi-hop reasoning across documents with query planning. Recommended for most scenarios - slightly slower with more token consumption for query planning, but more accurate results. |
|
||||
| [`azure_ai_with_search_context_semantic.py`](../../context_providers/azure_ai_search/azure_ai_with_search_context_semantic.py) | Shows how to use AzureAISearchContextProvider with semantic mode. Fast hybrid search with vector + keyword search and semantic ranking for RAG. Best for simple queries where speed is critical. |
|
||||
| [`azure_ai_with_sharepoint.py`](azure_ai_with_sharepoint.py) | Shows how to use SharePoint grounding with Azure AI agents to search through SharePoint content and answer user questions with proper citations. Requires a SharePoint connection configured in your Azure AI project. |
|
||||
| [`azure_ai_with_session.py`](azure_ai_with_session.py) | Demonstrates session management with Azure AI agents, including automatic session creation for stateless conversations and explicit session management for maintaining conversation context across multiple interactions. |
|
||||
| [`azure_ai_with_image_generation.py`](azure_ai_with_image_generation.py) | Shows how to use `AzureAIClient.get_image_generation_tool()` with Azure AI agents to generate images based on text prompts. |
|
||||
| [`azure_ai_with_memory_search.py`](azure_ai_with_memory_search.py) | Shows how to use memory search functionality with Azure AI agents for conversation persistence. Demonstrates creating memory stores and enabling agents to search through conversation history. |
|
||||
| [`azure_ai_with_microsoft_fabric.py`](azure_ai_with_microsoft_fabric.py) | Shows how to use Microsoft Fabric with Azure AI agents to query Fabric data sources and provide responses based on data analysis. Requires a Microsoft Fabric connection configured in your Azure AI project. |
|
||||
| [`azure_ai_with_openapi.py`](azure_ai_with_openapi.py) | Shows how to integrate OpenAPI specifications with Azure AI agents using dictionary-based tool configuration. Demonstrates using external REST APIs for dynamic data lookup. |
|
||||
| [`azure_ai_with_reasoning.py`](azure_ai_with_reasoning.py) | Shows how to enable reasoning for a model that supports it. |
|
||||
| [`azure_ai_with_web_search.py`](azure_ai_with_web_search.py) | Shows how to use `AzureAIClient.get_web_search_tool()` with Azure AI agents to perform web searches and retrieve up-to-date information from the internet. |
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Before running the examples, you need to set up your environment variables. You can do this in one of two ways:
|
||||
|
||||
### Option 1: Using a .env file (Recommended)
|
||||
|
||||
1. Copy the `.env.example` file from the `python` directory to create a `.env` file:
|
||||
|
||||
```bash
|
||||
cp ../../../../.env.example ../../../../.env
|
||||
```
|
||||
|
||||
2. Edit the `.env` file and add your values:
|
||||
|
||||
```env
|
||||
AZURE_AI_PROJECT_ENDPOINT="your-project-endpoint"
|
||||
AZURE_AI_MODEL_DEPLOYMENT_NAME="your-model-deployment-name"
|
||||
```
|
||||
|
||||
### Option 2: Using environment variables directly
|
||||
|
||||
Set the environment variables in your shell:
|
||||
|
||||
```bash
|
||||
export AZURE_AI_PROJECT_ENDPOINT="your-project-endpoint"
|
||||
export AZURE_AI_MODEL_DEPLOYMENT_NAME="your-model-deployment-name"
|
||||
```
|
||||
|
||||
### Required Variables
|
||||
|
||||
- `AZURE_AI_PROJECT_ENDPOINT`: Your Azure AI project endpoint (required for all examples)
|
||||
- `AZURE_AI_MODEL_DEPLOYMENT_NAME`: The name of your model deployment (required for all examples)
|
||||
|
||||
## Authentication
|
||||
|
||||
All examples use `AzureCliCredential` for authentication by default. Before running the examples:
|
||||
|
||||
1. Install the Azure CLI
|
||||
2. Run `az login` to authenticate with your Azure account
|
||||
3. Ensure you have appropriate permissions to the Azure AI project
|
||||
|
||||
Alternatively, you can replace `AzureCliCredential` with other authentication options like `DefaultAzureCredential` or environment-based credentials.
|
||||
|
||||
## Running the Examples
|
||||
|
||||
Each example can be run independently. Navigate to this directory and run any example:
|
||||
|
||||
```bash
|
||||
python azure_ai_basic.py
|
||||
python azure_ai_with_code_interpreter.py
|
||||
# ... etc
|
||||
```
|
||||
|
||||
The examples demonstrate various patterns for working with Azure AI agents, from basic usage to advanced scenarios like session management and structured outputs.
|
||||
@@ -1,91 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import tool
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI Agent Basic Example
|
||||
|
||||
This sample demonstrates basic usage of AzureAIProjectAgentProvider.
|
||||
Shows both streaming and non-streaming responses with function tools.
|
||||
"""
|
||||
|
||||
|
||||
# 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 ===")
|
||||
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="BasicWeatherAgent",
|
||||
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"Agent: {result}\n")
|
||||
|
||||
|
||||
async def streaming_example() -> None:
|
||||
"""Example of streaming response (get results as they are generated)."""
|
||||
print("=== Streaming Response Example ===")
|
||||
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="BasicWeatherAgent",
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
query = "What's the weather like in Tokyo?"
|
||||
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 AI Chat Client Agent Example ===")
|
||||
|
||||
await non_streaming_example()
|
||||
await streaming_example()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,258 +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.azure import AzureAIProjectAgentProvider
|
||||
from azure.ai.projects.aio import AIProjectClient
|
||||
from azure.ai.projects.models import PromptAgentDefinition
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI Project Agent Provider Methods Example
|
||||
|
||||
This sample demonstrates the three main methods of AzureAIProjectAgentProvider:
|
||||
1. create_agent() - Create a new agent on the Azure AI service
|
||||
2. get_agent() - Retrieve an existing agent from the service
|
||||
3. as_agent() - Wrap an SDK agent version object without making HTTP calls
|
||||
|
||||
It also shows how to use a single provider instance to spawn multiple agents
|
||||
with different configurations, which is efficient for multi-agent scenarios.
|
||||
|
||||
Each method returns a Agent that can be used for conversations.
|
||||
"""
|
||||
|
||||
|
||||
# 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:
|
||||
"""Example of using provider.create_agent() to create a new agent.
|
||||
|
||||
This method creates a new agent version on the Azure AI service and returns
|
||||
a Agent. Use this when you want to create a fresh agent with
|
||||
specific configuration.
|
||||
"""
|
||||
print("=== provider.create_agent() Example ===")
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
# Create a new agent with custom configuration
|
||||
agent = await provider.create_agent(
|
||||
name="WeatherAssistant",
|
||||
instructions="You are a helpful weather assistant. Always be concise.",
|
||||
description="An agent that provides weather information.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
print(f"Created agent: {agent.name}")
|
||||
print(f"Agent ID: {agent.id}")
|
||||
|
||||
query = "What's the weather in Paris?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
|
||||
|
||||
async def get_agent_by_name_example() -> None:
|
||||
"""Example of using provider.get_agent(name=...) to retrieve an agent by name.
|
||||
|
||||
This method fetches the latest version of an existing agent from the service.
|
||||
Use this when you know the agent name and want to use the most recent version.
|
||||
"""
|
||||
print("=== provider.get_agent(name=...) Example ===")
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
|
||||
):
|
||||
# First, create an agent using the SDK directly
|
||||
created_agent = await project_client.agents.create_version(
|
||||
agent_name="TestAgentByName",
|
||||
description="Test agent for get_agent by name example.",
|
||||
definition=PromptAgentDefinition(
|
||||
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
|
||||
instructions="You are a helpful assistant. End each response with '- Your Assistant'.",
|
||||
),
|
||||
)
|
||||
|
||||
try:
|
||||
# Get the agent using the provider by name (fetches latest version)
|
||||
provider = AzureAIProjectAgentProvider(project_client=project_client)
|
||||
agent = await provider.get_agent(name=created_agent.name)
|
||||
|
||||
print(f"Retrieved agent: {agent.name}")
|
||||
|
||||
query = "Hello!"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
finally:
|
||||
# Clean up the agent
|
||||
await project_client.agents.delete_version(
|
||||
agent_name=created_agent.name, agent_version=created_agent.version
|
||||
)
|
||||
|
||||
|
||||
async def get_agent_by_reference_example() -> None:
|
||||
"""Example of using provider.get_agent(reference=...) to retrieve a specific agent version.
|
||||
|
||||
This method fetches a specific version of an agent using a reference mapping.
|
||||
Use this when you need to use a particular version of an agent.
|
||||
"""
|
||||
print("=== provider.get_agent(reference=...) Example ===")
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
|
||||
):
|
||||
# First, create an agent using the SDK directly
|
||||
created_agent = await project_client.agents.create_version(
|
||||
agent_name="TestAgentByReference",
|
||||
description="Test agent for get_agent by reference example.",
|
||||
definition=PromptAgentDefinition(
|
||||
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
|
||||
instructions="You are a helpful assistant. Always respond in uppercase.",
|
||||
),
|
||||
)
|
||||
|
||||
try:
|
||||
# Get the agent using a reference mapping with specific version
|
||||
provider = AzureAIProjectAgentProvider(project_client=project_client)
|
||||
reference = {"name": created_agent.name, "version": created_agent.version}
|
||||
agent = await provider.get_agent(reference=reference)
|
||||
|
||||
print(f"Retrieved agent: {agent.name} (version via reference)")
|
||||
|
||||
query = "Say hello"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
finally:
|
||||
# Clean up the agent
|
||||
await project_client.agents.delete_version(
|
||||
agent_name=created_agent.name, agent_version=created_agent.version
|
||||
)
|
||||
|
||||
|
||||
async def multiple_agents_example() -> None:
|
||||
"""Example of using a single provider to spawn multiple agents.
|
||||
|
||||
A single provider instance can create multiple agents with different
|
||||
configurations.
|
||||
"""
|
||||
print("=== Multiple Agents from Single Provider Example ===")
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
# Create multiple specialized agents from the same provider
|
||||
weather_agent = await provider.create_agent(
|
||||
name="WeatherExpert",
|
||||
instructions="You are a weather expert. Provide brief weather information.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
translator_agent = await provider.create_agent(
|
||||
name="Translator",
|
||||
instructions="You are a translator. Translate any text to French. Only output the translation.",
|
||||
)
|
||||
|
||||
poet_agent = await provider.create_agent(
|
||||
name="Poet",
|
||||
instructions="You are a poet. Respond to everything with a short haiku.",
|
||||
)
|
||||
|
||||
print(f"Created agents: {weather_agent.name}, {translator_agent.name}, {poet_agent.name}\n")
|
||||
|
||||
# Use each agent for its specialty
|
||||
weather_query = "What's the weather in London?"
|
||||
print(f"User to WeatherExpert: {weather_query}")
|
||||
weather_result = await weather_agent.run(weather_query)
|
||||
print(f"WeatherExpert: {weather_result}\n")
|
||||
|
||||
translate_query = "Hello, how are you today?"
|
||||
print(f"User to Translator: {translate_query}")
|
||||
translate_result = await translator_agent.run(translate_query)
|
||||
print(f"Translator: {translate_result}\n")
|
||||
|
||||
poet_query = "Tell me about the morning sun"
|
||||
print(f"User to Poet: {poet_query}")
|
||||
poet_result = await poet_agent.run(poet_query)
|
||||
print(f"Poet: {poet_result}\n")
|
||||
|
||||
|
||||
async def as_agent_example() -> None:
|
||||
"""Example of using provider.as_agent() to wrap an SDK object without HTTP calls.
|
||||
|
||||
This method wraps an existing AgentVersionDetails into a Agent without
|
||||
making additional HTTP calls. Use this when you already have the full
|
||||
AgentVersionDetails from a previous SDK operation.
|
||||
"""
|
||||
print("=== provider.as_agent() Example ===")
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
|
||||
):
|
||||
# Create an agent using the SDK directly - this returns AgentVersionDetails
|
||||
agent_version_details = await project_client.agents.create_version(
|
||||
agent_name="TestAgentAsAgent",
|
||||
description="Test agent for as_agent example.",
|
||||
definition=PromptAgentDefinition(
|
||||
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
|
||||
instructions="You are a helpful assistant. Keep responses under 20 words.",
|
||||
),
|
||||
)
|
||||
|
||||
try:
|
||||
# Wrap the SDK object directly without any HTTP calls
|
||||
provider = AzureAIProjectAgentProvider(project_client=project_client)
|
||||
agent = provider.as_agent(agent_version_details)
|
||||
|
||||
print(f"Wrapped agent: {agent.name} (no HTTP call needed)")
|
||||
print(f"Agent version: {agent_version_details.version}")
|
||||
|
||||
query = "What can you do?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
finally:
|
||||
# Clean up the agent
|
||||
await project_client.agents.delete_version(
|
||||
agent_name=agent_version_details.name, agent_version=agent_version_details.version
|
||||
)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== Azure AI Project Agent Provider Methods Example ===\n")
|
||||
|
||||
await create_agent_example()
|
||||
await get_agent_by_name_example()
|
||||
await get_agent_by_reference_example()
|
||||
await as_agent_example()
|
||||
await multiple_agents_example()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,73 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
from random import randint
|
||||
from typing import Annotated
|
||||
|
||||
from agent_framework import tool
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI Agent Latest Version Example
|
||||
|
||||
This sample demonstrates how to reuse the latest version of an existing agent
|
||||
instead of creating a new agent version on each instantiation. The first call creates a new agent,
|
||||
while subsequent calls with `get_agent()` reuse the latest agent version.
|
||||
"""
|
||||
|
||||
|
||||
# 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:
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
# First call creates a new agent
|
||||
agent = await provider.create_agent(
|
||||
name="MyWeatherAgent",
|
||||
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"Agent: {result}\n")
|
||||
|
||||
# Second call retrieves the existing agent (latest version) instead of creating a new one
|
||||
# This is useful when you want to reuse an agent that was created earlier
|
||||
agent2 = await provider.get_agent(
|
||||
name="MyWeatherAgent",
|
||||
tools=get_weather, # Tools must be provided for function tools
|
||||
)
|
||||
|
||||
query = "What's the weather like in Tokyo?"
|
||||
print(f"User: {query}")
|
||||
result = await agent2.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
|
||||
print(f"First agent ID with version: {agent.id}")
|
||||
print(f"Second agent ID with version: {agent2.id}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,74 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Awaitable, Callable
|
||||
|
||||
from agent_framework import FunctionInvocationContext
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI Agent-as-Tool Example
|
||||
|
||||
Demonstrates hierarchical agent architectures where one agent delegates
|
||||
work to specialized sub-agents wrapped as tools using as_tool().
|
||||
|
||||
This pattern is useful when you want a coordinator agent to orchestrate
|
||||
multiple specialized agents, each focusing on specific tasks.
|
||||
"""
|
||||
|
||||
|
||||
async def logging_middleware(
|
||||
context: FunctionInvocationContext,
|
||||
call_next: Callable[[], Awaitable[None]],
|
||||
) -> None:
|
||||
"""MiddlewareTypes that logs tool invocations to show the delegation flow."""
|
||||
print(f"[Calling tool: {context.function.name}]")
|
||||
print(f"[Request: {context.arguments}]")
|
||||
|
||||
await call_next()
|
||||
|
||||
print(f"[Response: {context.result}]")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== Azure AI Agent-as-Tool Pattern ===")
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
# Create a specialized writer agent
|
||||
writer = await provider.create_agent(
|
||||
name="WriterAgent",
|
||||
instructions="You are a creative writer. Write short, engaging content.",
|
||||
)
|
||||
|
||||
# Convert writer agent to a tool using as_tool()
|
||||
writer_tool = writer.as_tool(
|
||||
name="creative_writer",
|
||||
description="Generate creative content like taglines, slogans, or short copy",
|
||||
arg_name="request",
|
||||
arg_description="What to write",
|
||||
)
|
||||
|
||||
# Create coordinator agent with writer as a tool
|
||||
coordinator = await provider.create_agent(
|
||||
name="CoordinatorAgent",
|
||||
instructions="You coordinate with specialized agents. Delegate writing tasks to the creative_writer tool.",
|
||||
tools=[writer_tool],
|
||||
middleware=[logging_middleware],
|
||||
)
|
||||
|
||||
query = "Create a tagline for a coffee shop"
|
||||
print(f"User: {query}")
|
||||
result = await coordinator.run(query)
|
||||
print(f"Coordinator: {result}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,57 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI Agent with Agent-to-Agent (A2A) Example
|
||||
|
||||
This sample demonstrates usage of AzureAIProjectAgentProvider with Agent-to-Agent (A2A) capabilities
|
||||
to enable communication with other agents using the A2A protocol.
|
||||
|
||||
Prerequisites:
|
||||
1. Set AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_MODEL_DEPLOYMENT_NAME environment variables.
|
||||
2. Ensure you have an A2A connection configured in your Azure AI project
|
||||
and set A2A_PROJECT_CONNECTION_ID environment variable.
|
||||
3. (Optional) A2A_ENDPOINT - If the connection is missing target (e.g., "Custom keys" type),
|
||||
set the A2A endpoint URL directly.
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Configure A2A tool with connection ID
|
||||
a2a_tool = {
|
||||
"type": "a2a_preview",
|
||||
"project_connection_id": os.environ["A2A_PROJECT_CONNECTION_ID"],
|
||||
}
|
||||
|
||||
# If the connection is missing a target, we need to set the A2A endpoint URL
|
||||
if os.environ.get("A2A_ENDPOINT"):
|
||||
a2a_tool["base_url"] = os.environ["A2A_ENDPOINT"]
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="MyA2AAgent",
|
||||
instructions="""You are a helpful assistant that can communicate with other agents.
|
||||
Use the A2A tool when you need to interact with other agents to complete tasks
|
||||
or gather information from specialized agents.""",
|
||||
tools=a2a_tool,
|
||||
)
|
||||
|
||||
query = "What can the secondary agent do?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Result: {result}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,44 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from azure.ai.projects.aio import AIProjectClient
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI Agent with Application Endpoint Example
|
||||
|
||||
This sample demonstrates working with pre-existing Azure AI Agents by providing
|
||||
application endpoint instead of project endpoint.
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Create the client
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
# Endpoint here should be application endpoint with format:
|
||||
# /api/projects/<project-name>/applications/<application-name>/protocols
|
||||
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
|
||||
Agent(
|
||||
name="ApplicationAgent",
|
||||
client=AzureAIClient(
|
||||
project_client=project_client,
|
||||
),
|
||||
) as agent,
|
||||
):
|
||||
query = "How are you?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,110 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework import Annotation
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI Agent with Azure AI Search Example
|
||||
|
||||
This sample demonstrates usage of AzureAIProjectAgentProvider with Azure AI Search
|
||||
to search through indexed data and answer user questions about it.
|
||||
|
||||
Citations from Azure AI Search are automatically enriched with document-specific
|
||||
URLs (get_url) that can be used to retrieve the original documents.
|
||||
|
||||
Prerequisites:
|
||||
1. Set AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_MODEL_DEPLOYMENT_NAME environment variables.
|
||||
2. Ensure you have an Azure AI Search connection configured in your Azure AI project
|
||||
and set AI_SEARCH_PROJECT_CONNECTION_ID and AI_SEARCH_INDEX_NAME environment variable.
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="MySearchAgent",
|
||||
instructions=(
|
||||
"You are a helpful agent that searches hotel information using Azure AI Search. "
|
||||
"Always use the search tool and index to find hotel data and provide accurate information."
|
||||
),
|
||||
tools={
|
||||
"type": "azure_ai_search",
|
||||
"azure_ai_search": {
|
||||
"indexes": [
|
||||
{
|
||||
"project_connection_id": os.environ["AI_SEARCH_PROJECT_CONNECTION_ID"],
|
||||
"index_name": os.environ["AI_SEARCH_INDEX_NAME"],
|
||||
# For query_type=vector, ensure your index has a field with vectorized data.
|
||||
"query_type": "simple",
|
||||
}
|
||||
]
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
query = (
|
||||
"Use Azure AI search knowledge tool to find detailed information about a winter hotel."
|
||||
" Use the search tool and index." # You can modify prompt to force tool usage
|
||||
)
|
||||
print(f"User: {query}")
|
||||
|
||||
# Non-streaming: get response with enriched citations
|
||||
result = await agent.run(query)
|
||||
print(f"Result: {result}\n")
|
||||
|
||||
# Display citations with document-specific URLs
|
||||
if result.messages:
|
||||
citations: list[Annotation] = []
|
||||
for msg in result.messages:
|
||||
for content in msg.contents:
|
||||
if hasattr(content, "annotations") and content.annotations:
|
||||
citations.extend(content.annotations)
|
||||
|
||||
if citations:
|
||||
print("Citations:")
|
||||
for i, citation in enumerate(citations, 1):
|
||||
url = citation.get("url", "N/A")
|
||||
# get_url contains the document-specific REST API URL from Azure AI Search
|
||||
get_url = (citation.get("additional_properties") or {}).get("get_url")
|
||||
print(f" [{i}] {citation.get('title', 'N/A')}")
|
||||
print(f" URL: {url}")
|
||||
if get_url:
|
||||
print(f" Document URL: {get_url}")
|
||||
|
||||
# Streaming: collect citations from streamed response
|
||||
print("\n--- Streaming ---")
|
||||
print(f"User: {query}")
|
||||
print("Agent: ", end="", flush=True)
|
||||
streaming_citations: list[Annotation] = []
|
||||
async for chunk in agent.run(query, stream=True):
|
||||
if chunk.text:
|
||||
print(chunk.text, end="", flush=True)
|
||||
for content in getattr(chunk, "contents", []):
|
||||
annotations = getattr(content, "annotations", [])
|
||||
if annotations:
|
||||
streaming_citations.extend(annotations)
|
||||
|
||||
print()
|
||||
if streaming_citations:
|
||||
print("\nStreaming Citations:")
|
||||
for i, citation in enumerate(streaming_citations, 1):
|
||||
url = citation.get("url", "N/A")
|
||||
get_url = (citation.get("additional_properties") or {}).get("get_url")
|
||||
print(f" [{i}] {citation.get('title', 'N/A')}")
|
||||
print(f" URL: {url}")
|
||||
if get_url:
|
||||
print(f" Document URL: {get_url}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,54 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI Agent with Bing Custom Search Example
|
||||
|
||||
This sample demonstrates usage of AzureAIProjectAgentProvider with Bing Custom Search
|
||||
to search custom search instances and provide responses with relevant results.
|
||||
|
||||
Prerequisites:
|
||||
1. Set AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_MODEL_DEPLOYMENT_NAME environment variables.
|
||||
2. Ensure you have a Bing Custom Search connection configured in your Azure AI project
|
||||
and set BING_CUSTOM_SEARCH_PROJECT_CONNECTION_ID and BING_CUSTOM_SEARCH_INSTANCE_NAME environment variables.
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="MyCustomSearchAgent",
|
||||
instructions="""You are a helpful agent that can use Bing Custom Search tools to assist users.
|
||||
Use the available Bing Custom Search tools to answer questions and perform tasks.""",
|
||||
tools={
|
||||
"type": "bing_custom_search_preview",
|
||||
"bing_custom_search_preview": {
|
||||
"search_configurations": [
|
||||
{
|
||||
"project_connection_id": os.environ["BING_CUSTOM_SEARCH_PROJECT_CONNECTION_ID"],
|
||||
"instance_name": os.environ["BING_CUSTOM_SEARCH_INSTANCE_NAME"],
|
||||
}
|
||||
]
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
query = "Tell me more about foundry agent service"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Result: {result}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,60 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI Agent with Bing Grounding Example
|
||||
|
||||
This sample demonstrates usage of AzureAIProjectAgentProvider with Bing Grounding
|
||||
to search the web for current information and provide grounded responses.
|
||||
|
||||
Prerequisites:
|
||||
1. Set AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_MODEL_DEPLOYMENT_NAME environment variables.
|
||||
2. Ensure you have a Bing connection configured in your Azure AI project
|
||||
and set BING_PROJECT_CONNECTION_ID environment variable.
|
||||
|
||||
To get your Bing connection ID:
|
||||
- Go to Azure AI Foundry portal (https://ai.azure.com)
|
||||
- Navigate to your project's "Connected resources" section
|
||||
- Add a new connection for "Grounding with Bing Search"
|
||||
- Copy the connection ID and set it as the BING_PROJECT_CONNECTION_ID environment variable
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="MyBingGroundingAgent",
|
||||
instructions="""You are a helpful assistant that can search the web for current information.
|
||||
Use the Bing search tool to find up-to-date information and provide accurate, well-sourced answers.
|
||||
Always cite your sources when possible.""",
|
||||
tools={
|
||||
"type": "bing_grounding",
|
||||
"bing_grounding": {
|
||||
"search_configurations": [
|
||||
{
|
||||
"project_connection_id": os.environ["BING_PROJECT_CONNECTION_ID"],
|
||||
}
|
||||
]
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
query = "What is today's date and weather in Seattle?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Result: {result}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,58 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI Agent with Browser Automation Example
|
||||
|
||||
This sample demonstrates usage of AzureAIProjectAgentProvider with Browser Automation
|
||||
to perform automated web browsing tasks and provide responses based on web interactions.
|
||||
|
||||
Prerequisites:
|
||||
1. Set AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_MODEL_DEPLOYMENT_NAME environment variables.
|
||||
2. Ensure you have a Browser Automation connection configured in your Azure AI project
|
||||
and set BROWSER_AUTOMATION_PROJECT_CONNECTION_ID environment variable.
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="MyBrowserAutomationAgent",
|
||||
instructions="""You are an Agent helping with browser automation tasks.
|
||||
You can answer questions, provide information, and assist with various tasks
|
||||
related to web browsing using the Browser Automation tool available to you.""",
|
||||
tools={
|
||||
"type": "browser_automation_preview",
|
||||
"browser_automation_preview": {
|
||||
"connection": {
|
||||
"project_connection_id": os.environ["BROWSER_AUTOMATION_PROJECT_CONNECTION_ID"],
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
query = """Your goal is to report the percent of Microsoft year-to-date stock price change.
|
||||
To do that, go to the website finance.yahoo.com.
|
||||
At the top of the page, you will find a search bar.
|
||||
Enter the value 'MSFT', to get information about the Microsoft stock price.
|
||||
At the top of the resulting page you will see a default chart of Microsoft stock price.
|
||||
Click on 'YTD' at the top of that chart, and report the percent value that shows up just below it."""
|
||||
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Result: {result}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,66 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
|
||||
from agent_framework import ChatResponse
|
||||
from agent_framework.azure import AzureAIClient, AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from openai.types.responses.response import Response as OpenAIResponse
|
||||
from openai.types.responses.response_code_interpreter_tool_call import ResponseCodeInterpreterToolCall
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI Agent Code Interpreter Example
|
||||
|
||||
This sample demonstrates using get_code_interpreter_tool() with AzureAIProjectAgentProvider
|
||||
for Python code execution and mathematical problem solving.
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Example showing how to use the code interpreter tool with AzureAIProjectAgentProvider."""
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
# Create a client to access hosted tool factory methods
|
||||
client = AzureAIClient(credential=credential)
|
||||
code_interpreter_tool = client.get_code_interpreter_tool()
|
||||
|
||||
agent = await provider.create_agent(
|
||||
name="MyCodeInterpreterAgent",
|
||||
instructions="You are a helpful assistant that can write and execute Python code to solve problems.",
|
||||
tools=[code_interpreter_tool],
|
||||
)
|
||||
|
||||
query = "Use code to get the factorial of 100?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Result: {result}\n")
|
||||
|
||||
if (
|
||||
isinstance(result.raw_representation, ChatResponse)
|
||||
and isinstance(result.raw_representation.raw_representation, OpenAIResponse)
|
||||
and len(result.raw_representation.raw_representation.output) > 0
|
||||
):
|
||||
# Find the first ResponseCodeInterpreterToolCall item
|
||||
code_interpreter_item = next(
|
||||
(
|
||||
item
|
||||
for item in result.raw_representation.raw_representation.output
|
||||
if isinstance(item, ResponseCodeInterpreterToolCall)
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
if code_interpreter_item is not None:
|
||||
generated_code = code_interpreter_item.code
|
||||
print(f"Generated code:\n{generated_code}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
-236
@@ -1,236 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from agent_framework import (
|
||||
Agent,
|
||||
AgentResponseUpdate,
|
||||
Annotation,
|
||||
Content,
|
||||
)
|
||||
from agent_framework.azure import AzureAIClient, AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI V2 Code Interpreter File Download Sample
|
||||
|
||||
This sample demonstrates how the AzureAIProjectAgentProvider handles file annotations
|
||||
when code interpreter generates text files. It shows:
|
||||
1. How to extract file IDs and container IDs from annotations
|
||||
2. How to download container files using the OpenAI containers API
|
||||
3. How to save downloaded files locally
|
||||
|
||||
Note: Code interpreter generates files in containers, which require both
|
||||
file_id and container_id to download via client.containers.files.content.retrieve().
|
||||
"""
|
||||
|
||||
QUERY = (
|
||||
"Write a simple Python script that creates a text file called 'sample.txt' containing "
|
||||
"'Hello from the code interpreter!' and save it to disk."
|
||||
)
|
||||
|
||||
|
||||
async def download_container_files(file_contents: list[Annotation | Content], agent: Agent) -> list[Path]:
|
||||
"""Download container files using the OpenAI containers API.
|
||||
|
||||
Code interpreter generates files in containers, which require both file_id
|
||||
and container_id to download. The container_id is stored in additional_properties.
|
||||
|
||||
This function works for both streaming (Content with type="hosted_file") and non-streaming
|
||||
(Annotation) responses.
|
||||
|
||||
Args:
|
||||
file_contents: List of Annotation or Content objects
|
||||
containing file_id and container_id.
|
||||
agent: The Agent instance with access to the AzureAIClient.
|
||||
|
||||
Returns:
|
||||
List of Path objects for successfully downloaded files.
|
||||
"""
|
||||
if not file_contents:
|
||||
return []
|
||||
|
||||
# Create output directory in system temp folder
|
||||
temp_dir = Path(tempfile.gettempdir())
|
||||
output_dir = temp_dir / "agent_framework_downloads"
|
||||
output_dir.mkdir(exist_ok=True)
|
||||
|
||||
print(f"\nDownloading {len(file_contents)} container file(s) to {output_dir.absolute()}...")
|
||||
|
||||
# Access the OpenAI client from AzureAIClient
|
||||
openai_client = agent.client.client # type: ignore[attr-defined]
|
||||
|
||||
downloaded_files: list[Path] = []
|
||||
|
||||
for content in file_contents:
|
||||
# Handle both Annotation (TypedDict) and Content objects
|
||||
if isinstance(content, dict): # Annotation TypedDict
|
||||
file_id = content.get("file_id")
|
||||
additional_props = content.get("additional_properties", {})
|
||||
url = content.get("url")
|
||||
else: # Content object
|
||||
file_id = content.file_id
|
||||
additional_props = content.additional_properties or {}
|
||||
url = content.uri
|
||||
|
||||
# Extract container_id from additional_properties
|
||||
if not additional_props or "container_id" not in additional_props:
|
||||
print(f" File {file_id}: ✗ Missing container_id")
|
||||
continue
|
||||
|
||||
container_id = additional_props["container_id"]
|
||||
|
||||
# Extract filename based on content type
|
||||
if isinstance(content, dict): # Annotation TypedDict
|
||||
filename = url or f"{file_id}.txt"
|
||||
# Extract filename from sandbox URL if present (e.g., sandbox:/mnt/data/sample.txt)
|
||||
if filename.startswith("sandbox:"):
|
||||
filename = filename.split("/")[-1]
|
||||
else: # Content
|
||||
filename = additional_props.get("filename") or f"{file_id}.txt"
|
||||
|
||||
output_path = output_dir / filename
|
||||
|
||||
try:
|
||||
# Download using containers API
|
||||
print(f" Downloading {filename}...", end="", flush=True)
|
||||
file_content = await openai_client.containers.files.content.retrieve(
|
||||
file_id=file_id,
|
||||
container_id=container_id,
|
||||
)
|
||||
|
||||
# file_content is HttpxBinaryResponseContent, read it
|
||||
content_bytes = file_content.read()
|
||||
|
||||
# Save to disk
|
||||
output_path.write_bytes(content_bytes)
|
||||
file_size = output_path.stat().st_size
|
||||
print(f"({file_size} bytes)")
|
||||
|
||||
downloaded_files.append(output_path)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Failed: {e}")
|
||||
|
||||
return downloaded_files
|
||||
|
||||
|
||||
async def non_streaming_example() -> None:
|
||||
"""Example of downloading files from non-streaming response using Annotation."""
|
||||
print("=== Non-Streaming Response Example ===")
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
# Create a client to access hosted tool factory methods
|
||||
client = AzureAIClient(credential=credential)
|
||||
code_interpreter_tool = client.get_code_interpreter_tool()
|
||||
|
||||
agent = await provider.create_agent(
|
||||
name="V2CodeInterpreterFileAgent",
|
||||
instructions="You are a helpful assistant that can write and execute Python code to create files.",
|
||||
tools=[code_interpreter_tool],
|
||||
)
|
||||
|
||||
print(f"User: {QUERY}\n")
|
||||
|
||||
result = await agent.run(QUERY)
|
||||
print(f"Agent: {result.text}\n")
|
||||
|
||||
# Check for annotations in the response
|
||||
annotations_found: list[Annotation] = []
|
||||
# AgentResponse has messages property, which contains Message objects
|
||||
for message in result.messages:
|
||||
for content in message.contents:
|
||||
if content.type == "text" and content.annotations:
|
||||
for annotation in content.annotations:
|
||||
if annotation.get("file_id"):
|
||||
annotations_found.append(annotation)
|
||||
print(f"Found file annotation: file_id={annotation['file_id']}")
|
||||
additional_props = annotation.get("additional_properties", {})
|
||||
if additional_props and "container_id" in additional_props:
|
||||
print(f" container_id={additional_props['container_id']}")
|
||||
|
||||
if annotations_found:
|
||||
print(f"SUCCESS: Found {len(annotations_found)} file annotation(s)")
|
||||
|
||||
# Download the container files (cast to Sequence for type compatibility)
|
||||
downloaded_paths = await download_container_files(list(annotations_found), agent)
|
||||
|
||||
if downloaded_paths:
|
||||
print("\nDownloaded files available at:")
|
||||
for path in downloaded_paths:
|
||||
print(f" - {path.absolute()}")
|
||||
else:
|
||||
print("WARNING: No file annotations found in non-streaming response")
|
||||
|
||||
|
||||
async def streaming_example() -> None:
|
||||
"""Example of downloading files from streaming response using Content with type='hosted_file'."""
|
||||
print("\n=== Streaming Response Example ===")
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
# Create a client to access hosted tool factory methods
|
||||
client = AzureAIClient(credential=credential)
|
||||
code_interpreter_tool = client.get_code_interpreter_tool()
|
||||
|
||||
agent = await provider.create_agent(
|
||||
name="V2CodeInterpreterFileAgentStreaming",
|
||||
instructions="You are a helpful assistant that can write and execute Python code to create files.",
|
||||
tools=[code_interpreter_tool],
|
||||
)
|
||||
|
||||
print(f"User: {QUERY}\n")
|
||||
file_contents_found: list[Content] = []
|
||||
text_chunks: list[str] = []
|
||||
|
||||
async for update in agent.run(QUERY, stream=True):
|
||||
if isinstance(update, AgentResponseUpdate):
|
||||
for content in update.contents:
|
||||
if content.type == "text":
|
||||
if content.text:
|
||||
text_chunks.append(content.text)
|
||||
if content.annotations:
|
||||
for annotation in content.annotations:
|
||||
if annotation.get("file_id"):
|
||||
print(f"Found streaming annotation: file_id={annotation['file_id']}")
|
||||
elif content.type == "hosted_file":
|
||||
file_contents_found.append(content)
|
||||
print(f"Found streaming hosted_file: file_id={content.file_id}")
|
||||
if content.additional_properties and "container_id" in content.additional_properties:
|
||||
print(f" container_id={content.additional_properties['container_id']}")
|
||||
|
||||
print(f"\nAgent response: {''.join(text_chunks)[:200]}...")
|
||||
|
||||
if file_contents_found:
|
||||
print(f"SUCCESS: Found {len(file_contents_found)} file reference(s) in streaming")
|
||||
|
||||
# Download the container files
|
||||
downloaded_paths = await download_container_files(file_contents_found, agent)
|
||||
|
||||
if downloaded_paths:
|
||||
print("\n✓ Downloaded files available at:")
|
||||
for path in downloaded_paths:
|
||||
print(f" - {path.absolute()}")
|
||||
else:
|
||||
print("WARNING: No file annotations found in streaming response")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("AzureAIClient Code Interpreter File Download Sample\n")
|
||||
await non_streaming_example()
|
||||
await streaming_example()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
-123
@@ -1,123 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
|
||||
from agent_framework import (
|
||||
AgentResponseUpdate,
|
||||
)
|
||||
from agent_framework.azure import AzureAIClient, AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI V2 Code Interpreter File Generation Sample
|
||||
|
||||
This sample demonstrates how the AzureAIProjectAgentProvider handles file annotations
|
||||
when code interpreter generates text files. It shows both non-streaming
|
||||
and streaming approaches to verify file ID extraction.
|
||||
"""
|
||||
|
||||
QUERY = (
|
||||
"Write a simple Python script that creates a text file called 'sample.txt' containing "
|
||||
"'Hello from the code interpreter!' and save it to disk."
|
||||
)
|
||||
|
||||
|
||||
async def non_streaming_example() -> None:
|
||||
"""Example of extracting file annotations from non-streaming response."""
|
||||
print("=== Non-Streaming Response Example ===")
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
# Create a client to access hosted tool factory methods
|
||||
client = AzureAIClient(credential=credential)
|
||||
code_interpreter_tool = client.get_code_interpreter_tool()
|
||||
|
||||
agent = await provider.create_agent(
|
||||
name="CodeInterpreterFileAgent",
|
||||
instructions="You are a helpful assistant that can write and execute Python code to create files.",
|
||||
tools=[code_interpreter_tool],
|
||||
)
|
||||
|
||||
print(f"User: {QUERY}\n")
|
||||
|
||||
result = await agent.run(QUERY)
|
||||
print(f"Agent: {result.text}\n")
|
||||
|
||||
# Check for annotations in the response
|
||||
annotations_found: list[str] = []
|
||||
# AgentResponse has messages property, which contains Message objects
|
||||
for message in result.messages:
|
||||
for content in message.contents:
|
||||
if content.type == "text" and content.annotations:
|
||||
for annotation in content.annotations:
|
||||
if annotation.get("file_id"):
|
||||
annotations_found.append(annotation["file_id"])
|
||||
print(f"Found file annotation: file_id={annotation['file_id']}")
|
||||
|
||||
if annotations_found:
|
||||
print(f"SUCCESS: Found {len(annotations_found)} file annotation(s)")
|
||||
else:
|
||||
print("WARNING: No file annotations found in non-streaming response")
|
||||
|
||||
|
||||
async def streaming_example() -> None:
|
||||
"""Example of extracting file annotations from streaming response."""
|
||||
print("\n=== Streaming Response Example ===")
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
# Create a client to access hosted tool factory methods
|
||||
client = AzureAIClient(credential=credential)
|
||||
code_interpreter_tool = client.get_code_interpreter_tool()
|
||||
|
||||
agent = await provider.create_agent(
|
||||
name="V2CodeInterpreterFileAgentStreaming",
|
||||
instructions="You are a helpful assistant that can write and execute Python code to create files.",
|
||||
tools=[code_interpreter_tool],
|
||||
)
|
||||
|
||||
print(f"User: {QUERY}\n")
|
||||
annotations_found: list[str] = []
|
||||
text_chunks: list[str] = []
|
||||
file_ids_found: list[str] = []
|
||||
|
||||
async for update in agent.run(QUERY, stream=True):
|
||||
if isinstance(update, AgentResponseUpdate):
|
||||
for content in update.contents:
|
||||
if content.type == "text":
|
||||
if content.text:
|
||||
text_chunks.append(content.text)
|
||||
if content.annotations:
|
||||
for annotation in content.annotations:
|
||||
if annotation.get("file_id"):
|
||||
annotations_found.append(annotation["file_id"])
|
||||
print(f"Found streaming annotation: file_id={annotation['file_id']}")
|
||||
elif content.type == "hosted_file":
|
||||
file_ids_found.append(content.file_id)
|
||||
print(f"Found streaming HostedFileContent: file_id={content.file_id}")
|
||||
|
||||
print(f"\nAgent response: {''.join(text_chunks)[:200]}...")
|
||||
|
||||
if annotations_found or file_ids_found:
|
||||
total = len(annotations_found) + len(file_ids_found)
|
||||
print(f"SUCCESS: Found {total} file reference(s) in streaming")
|
||||
else:
|
||||
print("WARNING: No file annotations found in streaming response")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("AzureAIClient Code Interpreter File Generation Sample\n")
|
||||
await non_streaming_example()
|
||||
await streaming_example()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,70 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.ai.projects.models import RaiConfig
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI Agent with Content Filtering (RAI Policy) Example
|
||||
|
||||
This sample demonstrates how to enable content filtering on Azure AI agents using RaiConfig.
|
||||
|
||||
Prerequisites:
|
||||
1. Create an RAI Policy in Azure AI Foundry portal:
|
||||
- Go to Azure AI Foundry > Your Project > Guardrails + Controls > Content Filters
|
||||
- Create a new content filter or use an existing one
|
||||
- Note the policy name
|
||||
|
||||
2. Set environment variables:
|
||||
- AZURE_AI_PROJECT_ENDPOINT: Your Azure AI Foundry project endpoint
|
||||
- AZURE_AI_MODEL_DEPLOYMENT_NAME: Your model deployment name
|
||||
|
||||
3. Run `az login` to authenticate
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== Azure AI Agent with Content Filtering ===\n")
|
||||
|
||||
# Replace with your RAI policy from Azure AI Foundry portal
|
||||
rai_policy_name = (
|
||||
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/"
|
||||
"Microsoft.CognitiveServices/accounts/{accountName}/raiPolicies/{policyName}"
|
||||
)
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
# Create agent with content filtering enabled via default_options
|
||||
agent = await provider.create_agent(
|
||||
name="ContentFilteredAgent",
|
||||
instructions="You are a helpful assistant.",
|
||||
default_options={"rai_config": RaiConfig(rai_policy_name=rai_policy_name)},
|
||||
)
|
||||
|
||||
# Test with a normal query
|
||||
query = "What is the capital of France?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
|
||||
# Test with a query that might trigger content filtering
|
||||
# (depending on your RAI policy configuration)
|
||||
query2 = "Tell me something inappropriate."
|
||||
print(f"User: {query2}")
|
||||
try:
|
||||
result2 = await agent.run(query2)
|
||||
print(f"Agent: {result2}\n")
|
||||
except Exception as e:
|
||||
print(f"Content filter triggered: {e}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,70 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.ai.projects.aio import AIProjectClient
|
||||
from azure.ai.projects.models import PromptAgentDefinition
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI Agent with Existing Agent Example
|
||||
|
||||
This sample demonstrates working with pre-existing Azure AI Agents by using provider.get_agent() method,
|
||||
showing agent reuse patterns for production scenarios.
|
||||
"""
|
||||
|
||||
|
||||
async def using_provider_get_agent() -> None:
|
||||
print("=== Get existing Azure AI agent with provider.get_agent() ===")
|
||||
|
||||
# Create the client
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
|
||||
):
|
||||
# Create remote agent using SDK directly
|
||||
azure_ai_agent = await project_client.agents.create_version(
|
||||
agent_name="MyNewTestAgent",
|
||||
description="Agent for testing purposes.",
|
||||
definition=PromptAgentDefinition(
|
||||
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
|
||||
# Setting specific requirements to verify that this agent is used.
|
||||
instructions="End each response with [END].",
|
||||
),
|
||||
)
|
||||
|
||||
try:
|
||||
# Get newly created agent as Agent by using provider.get_agent()
|
||||
provider = AzureAIProjectAgentProvider(project_client=project_client)
|
||||
agent = await provider.get_agent(name=azure_ai_agent.name)
|
||||
|
||||
# Verify agent properties
|
||||
print(f"Agent ID: {agent.id}")
|
||||
print(f"Agent name: {agent.name}")
|
||||
print(f"Agent description: {agent.description}")
|
||||
|
||||
query = "How are you?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
# Response that indicates that previously created agent was used:
|
||||
# "I'm here and ready to help you! How can I assist you today? [END]"
|
||||
print(f"Agent: {result}\n")
|
||||
finally:
|
||||
# Clean up the agent manually
|
||||
await project_client.agents.delete_version(
|
||||
agent_name=azure_ai_agent.name, agent_version=azure_ai_agent.version
|
||||
)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
await using_provider_get_agent()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,108 +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.azure import AzureAIProjectAgentProvider
|
||||
from azure.ai.projects.aio import AIProjectClient
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI Agent Existing Conversation Example
|
||||
|
||||
This sample demonstrates usage of AzureAIProjectAgentProvider with existing conversation created on service side.
|
||||
"""
|
||||
|
||||
|
||||
# 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_conversation_id() -> None:
|
||||
"""Example shows how to use existing conversation ID with the provider."""
|
||||
print("=== Azure AI Agent With Existing Conversation ===")
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
|
||||
):
|
||||
# Create a conversation using OpenAI client
|
||||
openai_client = project_client.get_openai_client()
|
||||
conversation = await openai_client.conversations.create()
|
||||
conversation_id = conversation.id
|
||||
print(f"Conversation ID: {conversation_id}")
|
||||
|
||||
provider = AzureAIProjectAgentProvider(project_client=project_client)
|
||||
agent = await provider.create_agent(
|
||||
name="BasicAgent",
|
||||
instructions="You are a helpful agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
# Pass conversation_id at run level
|
||||
query = "What's the weather like in Seattle?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query, conversation_id=conversation_id)
|
||||
print(f"Agent: {result.text}\n")
|
||||
|
||||
query = "What was my last question?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query, conversation_id=conversation_id)
|
||||
print(f"Agent: {result.text}\n")
|
||||
|
||||
|
||||
async def example_with_session() -> None:
|
||||
"""This example shows how to specify existing conversation ID with AgentSession."""
|
||||
print("=== Azure AI Agent With Existing Conversation and Session ===")
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
|
||||
):
|
||||
provider = AzureAIProjectAgentProvider(project_client=project_client)
|
||||
agent = await provider.create_agent(
|
||||
name="BasicAgent",
|
||||
instructions="You are a helpful agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
# Create a conversation using OpenAI client
|
||||
openai_client = project_client.get_openai_client()
|
||||
conversation = await openai_client.conversations.create()
|
||||
conversation_id = conversation.id
|
||||
print(f"Conversation ID: {conversation_id}")
|
||||
|
||||
# Create a session with the existing ID
|
||||
session = agent.create_session(service_session_id=conversation_id)
|
||||
|
||||
query = "What's the weather like in Seattle?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query, session=session)
|
||||
print(f"Agent: {result.text}\n")
|
||||
|
||||
query = "What was my last question?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query, session=session)
|
||||
print(f"Agent: {result.text}\n")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
await example_with_conversation_id()
|
||||
await example_with_session()
|
||||
|
||||
|
||||
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.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI Agent with Explicit Settings Example
|
||||
|
||||
This sample demonstrates creating Azure AI Agents 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:
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(
|
||||
project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
|
||||
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
|
||||
credential=credential,
|
||||
) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="WeatherAgent",
|
||||
instructions="You are a helpful weather agent.",
|
||||
tools=get_weather,
|
||||
)
|
||||
|
||||
query = "What's the weather like in New York?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,80 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from agent_framework.azure import AzureAIClient, AzureAIProjectAgentProvider
|
||||
from azure.ai.projects.aio import AIProjectClient
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
The following sample demonstrates how to create a simple, Azure AI agent that
|
||||
uses a file search tool to answer user questions.
|
||||
"""
|
||||
|
||||
|
||||
# Simulate a conversation with the agent
|
||||
USER_INPUTS = [
|
||||
"Who is the youngest employee?",
|
||||
"Who works in sales?",
|
||||
"I have a customer request, who can help me?",
|
||||
]
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Main function demonstrating Azure AI agent with file search capabilities."""
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AIProjectClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as project_client,
|
||||
AzureAIProjectAgentProvider(project_client=project_client) as provider,
|
||||
):
|
||||
openai_client = project_client.get_openai_client()
|
||||
|
||||
try:
|
||||
# 1. Upload file and create vector store via OpenAI client
|
||||
pdf_file_path = Path(__file__).parents[3] / "shared" / "resources" / "employees.pdf"
|
||||
print(f"Uploading file from: {pdf_file_path}")
|
||||
|
||||
vector_store = await openai_client.vector_stores.create(name="my_vectorstore")
|
||||
print(f"Created vector store, vector store ID: {vector_store.id}")
|
||||
|
||||
with open(pdf_file_path, "rb") as f:
|
||||
file = await openai_client.vector_stores.files.upload_and_poll(
|
||||
vector_store_id=vector_store.id,
|
||||
file=f,
|
||||
)
|
||||
print(f"Uploaded file, file ID: {file.id}")
|
||||
|
||||
# 2. Create a file search tool
|
||||
client = AzureAIClient(project_client=project_client)
|
||||
file_search_tool = client.get_file_search_tool(vector_store_ids=[vector_store.id])
|
||||
|
||||
# 3. Create an agent with file search capabilities using the provider
|
||||
agent = await provider.create_agent(
|
||||
name="EmployeeSearchAgent",
|
||||
instructions=(
|
||||
"You are a helpful assistant that can search through uploaded employee files "
|
||||
"to answer questions about employees."
|
||||
),
|
||||
tools=[file_search_tool],
|
||||
)
|
||||
|
||||
# 4. Simulate conversation with the agent
|
||||
for user_input in USER_INPUTS:
|
||||
print(f"# User: '{user_input}'")
|
||||
response = await agent.run(user_input)
|
||||
print(f"# Agent: {response.text}")
|
||||
finally:
|
||||
# 5. Cleanup: Delete the vector store (also deletes associated files)
|
||||
with contextlib.suppress(Exception):
|
||||
await openai_client.vector_stores.delete(vector_store.id)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,135 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
from typing import Any
|
||||
|
||||
from agent_framework import AgentResponse, AgentSession, Message, SupportsAgentRun
|
||||
from agent_framework.azure import AzureAIClient, AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI Agent with Hosted MCP Example
|
||||
|
||||
This sample demonstrates integrating hosted Model Context Protocol (MCP) tools with Azure AI Agent.
|
||||
"""
|
||||
|
||||
|
||||
async def handle_approvals_without_session(query: str, agent: "SupportsAgentRun") -> AgentResponse:
|
||||
"""When we don't have a session, we need to ensure we return with the input, approval request and approval."""
|
||||
|
||||
result = await agent.run(query, store=False)
|
||||
while len(result.user_input_requests) > 0:
|
||||
new_inputs: list[Any] = [query]
|
||||
for user_input_needed in result.user_input_requests:
|
||||
print(
|
||||
f"User Input Request for function from {agent.name}: {user_input_needed.function_call.name}"
|
||||
f" with arguments: {user_input_needed.function_call.arguments}"
|
||||
)
|
||||
new_inputs.append(Message("assistant", [user_input_needed]))
|
||||
user_approval = input("Approve function call? (y/n): ")
|
||||
new_inputs.append(
|
||||
Message("user", [user_input_needed.to_function_approval_response(user_approval.lower() == "y")])
|
||||
)
|
||||
|
||||
result = await agent.run(new_inputs, store=False)
|
||||
return result
|
||||
|
||||
|
||||
async def handle_approvals_with_session(
|
||||
query: str, agent: "SupportsAgentRun", session: "AgentSession"
|
||||
) -> AgentResponse:
|
||||
"""Here we let the session deal with the previous responses, and we just rerun with the approval."""
|
||||
|
||||
result = await agent.run(query, session=session)
|
||||
while len(result.user_input_requests) > 0:
|
||||
new_input: list[Any] = []
|
||||
for user_input_needed in result.user_input_requests:
|
||||
print(
|
||||
f"User Input Request for function from {agent.name}: {user_input_needed.function_call.name}"
|
||||
f" with arguments: {user_input_needed.function_call.arguments}"
|
||||
)
|
||||
user_approval = input("Approve function call? (y/n): ")
|
||||
new_input.append(
|
||||
Message(
|
||||
role="user",
|
||||
contents=[user_input_needed.to_function_approval_response(user_approval.lower() == "y")],
|
||||
)
|
||||
)
|
||||
result = await agent.run(new_input, session=session)
|
||||
return result
|
||||
|
||||
|
||||
async def run_hosted_mcp_without_approval() -> None:
|
||||
"""Example showing MCP Tools without approval."""
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
# Create a client to access hosted tool factory methods
|
||||
client = AzureAIClient(credential=credential)
|
||||
# Create MCP tool using instance method
|
||||
mcp_tool = client.get_mcp_tool(
|
||||
name="Microsoft Learn MCP",
|
||||
url="https://learn.microsoft.com/api/mcp",
|
||||
approval_mode="never_require",
|
||||
)
|
||||
|
||||
agent = await provider.create_agent(
|
||||
name="MyLearnDocsAgent",
|
||||
instructions="You are a helpful assistant that can help with Microsoft documentation questions.",
|
||||
tools=[mcp_tool],
|
||||
)
|
||||
|
||||
query = "How to create an Azure storage account using az cli?"
|
||||
print(f"User: {query}")
|
||||
result = await handle_approvals_without_session(query, agent)
|
||||
print(f"{agent.name}: {result}\n")
|
||||
|
||||
|
||||
async def run_hosted_mcp_with_approval_and_session() -> None:
|
||||
"""Example showing MCP Tools with approvals using a session."""
|
||||
print("=== MCP with approvals and with session ===")
|
||||
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
# Create a client to access hosted tool factory methods
|
||||
client = AzureAIClient(credential=credential)
|
||||
# Create MCP tool using instance method
|
||||
mcp_tool = client.get_mcp_tool(
|
||||
name="api-specs",
|
||||
url="https://gitmcp.io/Azure/azure-rest-api-specs",
|
||||
approval_mode="always_require",
|
||||
)
|
||||
|
||||
agent = await provider.create_agent(
|
||||
name="MyApiSpecsAgent",
|
||||
instructions="You are a helpful agent that can use MCP tools to assist users.",
|
||||
tools=[mcp_tool],
|
||||
)
|
||||
|
||||
session = agent.create_session()
|
||||
query = "Please summarize the Azure REST API specifications Readme"
|
||||
print(f"User: {query}")
|
||||
result = await handle_approvals_with_session(query, agent, session)
|
||||
print(f"{agent.name}: {result}\n")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=== Azure AI Agent with Hosted MCP Tools Example ===\n")
|
||||
|
||||
await run_hosted_mcp_without_approval()
|
||||
await run_hosted_mcp_with_approval_and_session()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,111 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
import asyncio
|
||||
import base64
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from urllib import request as urllib_request
|
||||
|
||||
from agent_framework.azure import AzureAIClient, AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI Agent with Image Generation Example
|
||||
|
||||
This sample demonstrates basic usage of AzureAIProjectAgentProvider to create an agent
|
||||
that can generate images based on user requirements.
|
||||
|
||||
Pre-requisites:
|
||||
- Make sure to set up the AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_MODEL_DEPLOYMENT_NAME
|
||||
environment variables before running this sample.
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
|
||||
# authentication option.
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
# Create a client to access hosted tool factory methods
|
||||
client = AzureAIClient(credential=credential)
|
||||
# Create image generation tool using instance method
|
||||
image_gen_tool = client.get_image_generation_tool(
|
||||
model="gpt-image-1",
|
||||
size="1024x1024",
|
||||
output_format="png",
|
||||
quality="low",
|
||||
background="opaque",
|
||||
)
|
||||
|
||||
agent = await provider.create_agent(
|
||||
name="ImageGenAgent",
|
||||
instructions="Generate images based on user requirements.",
|
||||
tools=[image_gen_tool],
|
||||
)
|
||||
|
||||
query = "Generate an image of Microsoft logo."
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(
|
||||
query,
|
||||
# These additional options are required for image generation
|
||||
options={
|
||||
"extra_headers": {"x-ms-oai-image-generation-deployment": "gpt-image-1-mini"},
|
||||
},
|
||||
)
|
||||
print(f"Agent: {result}\n")
|
||||
|
||||
# Save the image to a file
|
||||
print("Downloading generated image...")
|
||||
image_data = [
|
||||
content.outputs
|
||||
for content in result.messages[0].contents
|
||||
if content.type == "image_generation_tool_result" and content.outputs is not None
|
||||
]
|
||||
if image_data and image_data[0]:
|
||||
# Save to the OS temporary directory
|
||||
filename = "microsoft.png"
|
||||
file_path = Path(tempfile.gettempdir()) / filename
|
||||
# outputs can be a list of Content items (data/uri) or a single item
|
||||
out = image_data[0][0] if isinstance(image_data[0], list) else image_data[0]
|
||||
data_bytes: bytes | None = None
|
||||
uri = getattr(out, "uri", None)
|
||||
if isinstance(uri, str):
|
||||
if ";base64," in uri:
|
||||
try:
|
||||
b64 = uri.split(";base64,", 1)[1]
|
||||
data_bytes = base64.b64decode(b64)
|
||||
except Exception:
|
||||
data_bytes = None
|
||||
else:
|
||||
try:
|
||||
data_bytes = await asyncio.to_thread(lambda: urllib_request.urlopen(uri).read())
|
||||
except Exception:
|
||||
data_bytes = None
|
||||
|
||||
if data_bytes is None:
|
||||
raise RuntimeError("Image output present but could not retrieve bytes.")
|
||||
|
||||
with open(file_path, "wb") as f:
|
||||
f.write(data_bytes)
|
||||
|
||||
print(f"Image downloaded and saved to: {file_path}")
|
||||
else:
|
||||
print("No image data found in the agent response.")
|
||||
|
||||
"""
|
||||
Sample output:
|
||||
User: Generate an image of Microsoft logo.
|
||||
Agent: Here is the Microsoft logo image featuring its iconic four quadrants.
|
||||
|
||||
Downloading generated image...
|
||||
Image downloaded and saved to: .../microsoft.png
|
||||
"""
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,60 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
|
||||
from agent_framework import MCPStreamableHTTPTool
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI Agent with Local MCP Example
|
||||
|
||||
This sample demonstrates integration of Azure AI Agents with local Model Context Protocol (MCP)
|
||||
servers.
|
||||
|
||||
Pre-requisites:
|
||||
- Make sure to set up the AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_MODEL_DEPLOYMENT_NAME
|
||||
environment variables before running this sample.
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Example showing use of Local MCP Tool with AzureAIProjectAgentProvider."""
|
||||
print("=== Azure AI Agent with Local MCP Tools Example ===\n")
|
||||
|
||||
mcp_tool = MCPStreamableHTTPTool(
|
||||
name="Microsoft Learn MCP",
|
||||
url="https://learn.microsoft.com/api/mcp",
|
||||
)
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="DocsAgent",
|
||||
instructions="You are a helpful assistant that can help with Microsoft documentation questions.",
|
||||
tools=mcp_tool,
|
||||
)
|
||||
|
||||
# Use agent as context manager to ensure proper cleanup
|
||||
async with agent:
|
||||
# First query
|
||||
first_query = "How to create an Azure storage account using az cli?"
|
||||
print(f"User: {first_query}")
|
||||
first_result = await agent.run(first_query)
|
||||
print(f"Agent: {first_result}")
|
||||
print("\n=======================================\n")
|
||||
# Second query
|
||||
second_query = "What is Microsoft Agent Framework?"
|
||||
print(f"User: {second_query}")
|
||||
second_result = await agent.run(second_query)
|
||||
print(f"Agent: {second_result}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,92 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
import asyncio
|
||||
import os
|
||||
import uuid
|
||||
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.ai.projects.aio import AIProjectClient
|
||||
from azure.ai.projects.models import MemoryStoreDefaultDefinition, MemoryStoreDefaultOptions
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI Agent with Memory Search Example
|
||||
|
||||
This sample demonstrates usage of AzureAIProjectAgentProvider with memory search capabilities
|
||||
to retrieve relevant past user messages and maintain conversation context across sessions.
|
||||
It shows explicit memory store creation using Azure AI Projects client and agent creation
|
||||
using the Agent Framework.
|
||||
|
||||
Prerequisites:
|
||||
1. Set AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_MODEL_DEPLOYMENT_NAME environment variables.
|
||||
2. Set AZURE_AI_CHAT_MODEL_DEPLOYMENT_NAME for the memory chat model.
|
||||
3. Set AZURE_AI_EMBEDDING_MODEL_DEPLOYMENT_NAME for the memory embedding model.
|
||||
4. Deploy both a chat model (e.g. gpt-4.1) and an embedding model (e.g. text-embedding-3-small).
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
endpoint = os.environ["AZURE_AI_PROJECT_ENDPOINT"]
|
||||
# Generate a unique memory store name to avoid conflicts
|
||||
memory_store_name = f"agent_framework_memory_store_{uuid.uuid4().hex[:8]}"
|
||||
|
||||
async with AzureCliCredential() as credential:
|
||||
# Create the memory store using Azure AI Projects client
|
||||
async with AIProjectClient(endpoint=endpoint, credential=credential) as project_client:
|
||||
# Create a memory store using proper model classes
|
||||
memory_store_definition = MemoryStoreDefaultDefinition(
|
||||
chat_model=os.environ["AZURE_AI_CHAT_MODEL_DEPLOYMENT_NAME"],
|
||||
embedding_model=os.environ["AZURE_AI_EMBEDDING_MODEL_DEPLOYMENT_NAME"],
|
||||
options=MemoryStoreDefaultOptions(user_profile_enabled=True, chat_summary_enabled=True),
|
||||
)
|
||||
|
||||
memory_store = await project_client.beta.memory_stores.create(
|
||||
name=memory_store_name,
|
||||
description="Memory store for Agent Framework conversations",
|
||||
definition=memory_store_definition,
|
||||
)
|
||||
print(f"Created memory store: {memory_store.name} ({memory_store.id}): {memory_store.description}")
|
||||
|
||||
# Then, create the agent using Agent Framework provider
|
||||
async with AzureAIProjectAgentProvider(credential=credential) as provider:
|
||||
agent = await provider.create_agent(
|
||||
name="MyMemoryAgent",
|
||||
instructions="""You are a helpful assistant that remembers past conversations.
|
||||
Use the memory search tool to recall relevant information from previous interactions.""",
|
||||
tools={
|
||||
"type": "memory_search_preview",
|
||||
"memory_store_name": memory_store.name,
|
||||
"scope": "user_123",
|
||||
"update_delay": 1, # Wait 1 second before updating memories (use higher value in production)
|
||||
},
|
||||
)
|
||||
|
||||
# First interaction - establish some preferences
|
||||
print("=== First conversation ===")
|
||||
query1 = "I prefer dark roast coffee"
|
||||
print(f"User: {query1}")
|
||||
result1 = await agent.run(query1)
|
||||
print(f"Agent: {result1}\n")
|
||||
|
||||
# Wait for memories to be processed
|
||||
print("Waiting for memories to be stored...")
|
||||
await asyncio.sleep(5) # Reduced wait time for demo purposes
|
||||
|
||||
# Second interaction - test memory recall
|
||||
print("=== Second conversation ===")
|
||||
query2 = "Please order my usual coffee"
|
||||
print(f"User: {query2}")
|
||||
result2 = await agent.run(query2)
|
||||
print(f"Agent: {result2}\n")
|
||||
|
||||
# Clean up - delete the memory store
|
||||
async with AIProjectClient(endpoint=endpoint, credential=credential) as project_client:
|
||||
await project_client.beta.memory_stores.delete(memory_store_name)
|
||||
print("Memory store deleted")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,52 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI Agent with Microsoft Fabric Example
|
||||
|
||||
This sample demonstrates usage of AzureAIProjectAgentProvider with Microsoft Fabric
|
||||
to query Fabric data sources and provide responses based on data analysis.
|
||||
|
||||
Prerequisites:
|
||||
1. Set AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_MODEL_DEPLOYMENT_NAME environment variables.
|
||||
2. Ensure you have a Microsoft Fabric connection configured in your Azure AI project
|
||||
and set FABRIC_PROJECT_CONNECTION_ID environment variable.
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="MyFabricAgent",
|
||||
instructions="You are a helpful assistant.",
|
||||
tools={
|
||||
"type": "fabric_dataagent_preview",
|
||||
"fabric_dataagent_preview": {
|
||||
"project_connections": [
|
||||
{
|
||||
"project_connection_id": os.environ["FABRIC_PROJECT_CONNECTION_ID"],
|
||||
}
|
||||
]
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
query = "Tell me about sales records"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Result: {result}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,58 +0,0 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from agent_framework.azure import AzureAIProjectAgentProvider
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
"""
|
||||
Azure AI Agent with OpenAPI Tool Example
|
||||
|
||||
This sample demonstrates usage of AzureAIProjectAgentProvider with OpenAPI tools
|
||||
to call external APIs defined by OpenAPI specifications.
|
||||
|
||||
Prerequisites:
|
||||
1. Set AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_MODEL_DEPLOYMENT_NAME environment variables.
|
||||
2. The countries.json OpenAPI specification is included in the resources folder.
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Load the OpenAPI specification
|
||||
resources_path = Path(__file__).parents[3] / "shared" / "resources" / "countries.json"
|
||||
|
||||
with open(resources_path) as f:
|
||||
openapi_countries = json.load(f)
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIProjectAgentProvider(credential=credential) as provider,
|
||||
):
|
||||
agent = await provider.create_agent(
|
||||
name="MyOpenAPIAgent",
|
||||
instructions="""You are a helpful assistant that can use country APIs to provide information.
|
||||
Use the available OpenAPI tools to answer questions about countries, currencies, and demographics.""",
|
||||
tools={
|
||||
"type": "openapi",
|
||||
"openapi": {
|
||||
"name": "get_countries",
|
||||
"spec": openapi_countries,
|
||||
"description": "Retrieve information about countries by currency code",
|
||||
"auth": {"type": "anonymous"},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
query = "What is the name and population of the country that uses currency with abbreviation THB?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user