Python: [BREAKING] Renamed create_agent to as_agent (#3249)

* Renamed create_agent to as_agent

* Override for as_agent

* Added override
This commit is contained in:
Dmytro Struk
2026-01-16 11:21:52 -08:00
committed by GitHub
Unverified
parent a151f10cc2
commit 5687e13221
163 changed files with 498 additions and 358 deletions
@@ -4,18 +4,21 @@ import ast
import json
import re
import sys
from collections.abc import AsyncIterable, Mapping, MutableMapping, MutableSequence, Sequence
from collections.abc import AsyncIterable, Callable, Mapping, MutableMapping, MutableSequence, Sequence
from typing import Any, ClassVar, Generic, TypedDict
from agent_framework import (
AGENT_FRAMEWORK_USER_AGENT,
BaseChatClient,
ChatAgent,
ChatMessage,
ChatMessageStoreProtocol,
ChatOptions,
ChatResponse,
ChatResponseUpdate,
CitationAnnotation,
Contents,
ContextProvider,
DataContent,
FunctionApprovalRequestContent,
FunctionApprovalResponseContent,
@@ -23,6 +26,7 @@ from agent_framework import (
FunctionResultContent,
HostedFileContent,
HostedMCPTool,
Middleware,
Role,
TextContent,
TextSpanRegion,
@@ -1162,3 +1166,59 @@ class AzureAIAgentClient(BaseChatClient[TAzureAIAgentOptions], Generic[TAzureAIA
The service URL for the chat client, or None if not set.
"""
return self.agents_client._config.endpoint # type: ignore
@override
def as_agent(
self,
*,
id: str | None = None,
name: str | None = None,
description: str | None = None,
instructions: str | None = None,
tools: ToolProtocol
| Callable[..., Any]
| MutableMapping[str, Any]
| Sequence[ToolProtocol | Callable[..., Any] | MutableMapping[str, Any]]
| None = None,
default_options: TAzureAIAgentOptions | None = None,
chat_message_store_factory: Callable[[], ChatMessageStoreProtocol] | None = None,
context_provider: ContextProvider | None = None,
middleware: Sequence[Middleware] | None = None,
**kwargs: Any,
) -> ChatAgent[TAzureAIAgentOptions]:
"""Convert this chat client to a ChatAgent.
This method creates a ChatAgent instance with this client pre-configured.
It does NOT create an agent on the Azure AI service - the actual agent
will be created on the server during the first invocation (run).
For creating and managing persistent agents on the server, use
:class:`~agent_framework_azure_ai.AzureAIAgentsProvider` instead.
Keyword Args:
id: The unique identifier for the agent. Will be created automatically if not provided.
name: The name of the agent.
description: A brief description of the agent's purpose.
instructions: Optional instructions for the agent.
tools: The tools to use for the request.
default_options: A TypedDict containing chat options.
chat_message_store_factory: Factory function to create an instance of ChatMessageStoreProtocol.
context_provider: Context providers to include during agent invocation.
middleware: List of middleware to intercept agent and function invocations.
kwargs: Any additional keyword arguments.
Returns:
A ChatAgent instance configured with this chat client.
"""
return super().as_agent(
id=id,
name=name,
description=description,
instructions=instructions,
tools=tools,
default_options=default_options,
chat_message_store_factory=chat_message_store_factory,
context_provider=context_provider,
middleware=middleware,
**kwargs,
)
@@ -1,14 +1,19 @@
# Copyright (c) Microsoft. All rights reserved.
import sys
from collections.abc import Mapping, MutableSequence
from collections.abc import Callable, Mapping, MutableMapping, MutableSequence, Sequence
from typing import TYPE_CHECKING, Any, ClassVar, Generic, TypedDict, TypeVar, cast
from agent_framework import (
AGENT_FRAMEWORK_USER_AGENT,
ChatAgent,
ChatMessage,
ChatMessageStoreProtocol,
ContextProvider,
HostedMCPTool,
Middleware,
TextContent,
ToolProtocol,
get_logger,
use_chat_middleware,
use_function_invocation,
@@ -511,3 +516,59 @@ class AzureAIClient(OpenAIBaseResponsesClient[TAzureAIClientOptions], Generic[TA
mcp["require_approval"] = {"never": {"tool_names": list(never_require_approvals)}}
return mcp
@override
def as_agent(
self,
*,
id: str | None = None,
name: str | None = None,
description: str | None = None,
instructions: str | None = None,
tools: ToolProtocol
| Callable[..., Any]
| MutableMapping[str, Any]
| Sequence[ToolProtocol | Callable[..., Any] | MutableMapping[str, Any]]
| None = None,
default_options: TAzureAIClientOptions | None = None,
chat_message_store_factory: Callable[[], ChatMessageStoreProtocol] | None = None,
context_provider: ContextProvider | None = None,
middleware: Sequence[Middleware] | None = None,
**kwargs: Any,
) -> ChatAgent[TAzureAIClientOptions]:
"""Convert this chat client to a ChatAgent.
This method creates a ChatAgent instance with this client pre-configured.
It does NOT create an agent on the Azure AI service - the actual agent
will be created on the server during the first invocation (run).
For creating and managing persistent agents on the server, use
:class:`~agent_framework_azure_ai.AzureAIProjectAgentProvider` instead.
Keyword Args:
id: The unique identifier for the agent. Will be created automatically if not provided.
name: The name of the agent.
description: A brief description of the agent's purpose.
instructions: Optional instructions for the agent.
tools: The tools to use for the request.
default_options: A TypedDict containing chat options.
chat_message_store_factory: Factory function to create an instance of ChatMessageStoreProtocol.
context_provider: Context providers to include during agent invocation.
middleware: List of middleware to intercept agent and function invocations.
kwargs: Any additional keyword arguments.
Returns:
A ChatAgent instance configured with this chat client.
"""
return super().as_agent(
id=id,
name=name,
description=description,
instructions=instructions,
tools=tools,
default_options=default_options,
chat_message_store_factory=chat_message_store_factory,
context_provider=context_provider,
middleware=middleware,
**kwargs,
)
@@ -104,13 +104,13 @@ class AgentFunctionApp(DFAppBase):
from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient
# Create agents with unique names
weather_agent = AzureOpenAIChatClient(...).create_agent(
weather_agent = AzureOpenAIChatClient(...).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent.",
tools=[get_weather],
)
math_agent = AzureOpenAIChatClient(...).create_agent(
math_agent = AzureOpenAIChatClient(...).as_agent(
name="MathAgent",
instructions="You are a helpful math assistant.",
tools=[calculate],
@@ -377,7 +377,7 @@ class BaseChatClient(SerializationMixin, ABC, Generic[TOptions_co]):
"""
return "Unknown"
def create_agent(
def as_agent(
self,
*,
id: str | None = None,
@@ -428,7 +428,7 @@ class BaseChatClient(SerializationMixin, ABC, Generic[TOptions_co]):
client = OpenAIChatClient(model_id="gpt-4")
# Create an agent using the convenience method
agent = client.create_agent(
agent = client.as_agent(
name="assistant",
instructions="You are a helpful assistant.",
default_options={"temperature": 0.7, "max_tokens": 500},
@@ -710,9 +710,9 @@ class HandoffBuilder:
from agent_framework.openai import OpenAIChatClient
client = OpenAIChatClient()
triage = client.create_agent(instructions="...", name="triage_agent")
refund = client.create_agent(instructions="...", name="refund_agent")
billing = client.create_agent(instructions="...", name="billing_agent")
triage = client.as_agent(instructions="...", name="triage_agent")
refund = client.as_agent(instructions="...", name="refund_agent")
billing = client.as_agent(instructions="...", name="billing_agent")
builder = HandoffBuilder().participants([triage, refund, billing])
builder.with_start_agent(triage)
@@ -9,8 +9,12 @@ from collections.abc import (
Mapping,
MutableMapping,
MutableSequence,
Sequence,
)
from typing import Any, Generic, Literal, TypedDict, cast
from typing import TYPE_CHECKING, Any, Generic, Literal, TypedDict, cast
if TYPE_CHECKING:
from .._agents import ChatAgent
from openai import AsyncOpenAI
from openai.types.beta.threads import (
@@ -28,11 +32,14 @@ from openai.types.beta.threads.runs import RunStep
from pydantic import ValidationError
from .._clients import BaseChatClient
from .._middleware import use_chat_middleware
from .._memory import ContextProvider
from .._middleware import Middleware, use_chat_middleware
from .._threads import ChatMessageStoreProtocol
from .._tools import (
AIFunction,
HostedCodeInterpreterTool,
HostedFileSearchTool,
ToolProtocol,
use_function_invocation,
)
from .._types import (
@@ -761,3 +768,59 @@ class OpenAIAssistantsClient(
self.assistant_name = agent_name
if description and not self.assistant_description:
self.assistant_description = description
@override
def as_agent(
self,
*,
id: str | None = None,
name: str | None = None,
description: str | None = None,
instructions: str | None = None,
tools: ToolProtocol
| Callable[..., Any]
| MutableMapping[str, Any]
| Sequence[ToolProtocol | Callable[..., Any] | MutableMapping[str, Any]]
| None = None,
default_options: TOpenAIAssistantsOptions | None = None,
chat_message_store_factory: Callable[[], ChatMessageStoreProtocol] | None = None,
context_provider: ContextProvider | None = None,
middleware: Sequence[Middleware] | None = None,
**kwargs: Any,
) -> "ChatAgent[TOpenAIAssistantsOptions]":
"""Convert this chat client to a ChatAgent.
This method creates a ChatAgent instance with this client pre-configured.
It does NOT create an assistant on the OpenAI service - the actual assistant
will be created on the server during the first invocation (run).
For creating and managing persistent assistants on the server, use
:class:`~agent_framework.openai.OpenAIAssistantProvider` instead.
Keyword Args:
id: The unique identifier for the agent. Will be created automatically if not provided.
name: The name of the agent.
description: A brief description of the agent's purpose.
instructions: Optional instructions for the agent.
tools: The tools to use for the request.
default_options: A TypedDict containing chat options.
chat_message_store_factory: Factory function to create an instance of ChatMessageStoreProtocol.
context_provider: Context providers to include during agent invocation.
middleware: List of middleware to intercept agent and function invocations.
kwargs: Any additional keyword arguments.
Returns:
A ChatAgent instance configured with this chat client.
"""
return super().as_agent(
id=id,
name=name,
description=description,
instructions=instructions,
tools=tools,
default_options=default_options,
chat_message_store_factory=chat_message_store_factory,
context_provider=context_provider,
middleware=middleware,
**kwargs,
)
@@ -72,7 +72,7 @@ class WorkflowFactory:
# Pre-register agents for InvokeAzureAgent actions
chat_client = AzureOpenAIChatClient()
agent = chat_client.create_agent(name="MyAgent", instructions="You are helpful.")
agent = chat_client.as_agent(name="MyAgent", instructions="You are helpful.")
factory = WorkflowFactory(agents={"MyAgent": agent})
workflow = factory.create_workflow_from_yaml_path("workflow.yaml")
@@ -115,8 +115,8 @@ class WorkflowFactory:
# With pre-registered agents
client = AzureOpenAIChatClient()
agents = {
"WriterAgent": client.create_agent(name="Writer", instructions="Write content."),
"ReviewerAgent": client.create_agent(name="Reviewer", instructions="Review content."),
"WriterAgent": client.as_agent(name="Writer", instructions="Write content."),
"ReviewerAgent": client.as_agent(name="Reviewer", instructions="Review content."),
}
factory = WorkflowFactory(agents=agents)
@@ -533,14 +533,14 @@ class WorkflowFactory:
WorkflowFactory()
.register_agent(
"Writer",
client.create_agent(
client.as_agent(
name="Writer",
instructions="Write content.",
),
)
.register_agent(
"Reviewer",
client.create_agent(
client.as_agent(
name="Reviewer",
instructions="Review content.",
),
@@ -169,7 +169,7 @@ class FoundryLocalClient(OpenAIBaseChatClient[TFoundryLocalChatOptions], Generic
client = FoundryLocalClient(model_id="phi-4-mini")
agent = client.create_agent(
agent = client.as_agent(
name="LocalAgent",
instructions="You are a helpful agent.",
tools=get_weather,
@@ -65,7 +65,7 @@ async def main() -> None:
print(
f"- {model.alias} for {model.task} - id={model.id} - {(model.file_size_mb / 1000):.2f} GB - {model.license}"
)
agent = client.create_agent(
agent = client.as_agent(
name="LocalAgent",
instructions="You are a helpful agent.",
tools=get_weather,
@@ -49,7 +49,7 @@ async def create_gaia_agent() -> AsyncIterator[ChatAgent]:
"""
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="GaiaAgent",
instructions="Solve tasks to your best ability. Use Bing Search to find "
"information and Code Interpreter to perform calculations and data analysis.",
@@ -49,7 +49,7 @@ async def create_gaia_agent() -> AsyncIterator[ChatAgent]:
"""
chat_client = OpenAIResponsesClient()
async with chat_client.create_agent(
async with chat_client.as_agent(
name="GaiaAgent",
instructions="Solve tasks to your best ability. Use Web Search to find "
"information and Code Interpreter to perform calculations and data analysis.",
@@ -59,17 +59,17 @@ async def run_agent_framework() -> None:
client = OpenAIChatClient(model_id="gpt-4.1-mini")
# Create specialized agents
researcher = client.create_agent(
researcher = client.as_agent(
name="researcher",
instructions="You are a researcher. Provide facts and data about the topic.",
)
writer = client.create_agent(
writer = client.as_agent(
name="writer",
instructions="You are a writer. Turn research into engaging content.",
)
editor = client.create_agent(
editor = client.as_agent(
name="editor",
instructions="You are an editor. Review and finalize the content.",
)
@@ -109,17 +109,17 @@ async def run_agent_framework_with_cycle() -> None:
client = OpenAIChatClient(model_id="gpt-4.1-mini")
# Create specialized agents
researcher = client.create_agent(
researcher = client.as_agent(
name="researcher",
instructions="You are a researcher. Provide facts and data about the topic.",
)
writer = client.create_agent(
writer = client.as_agent(
name="writer",
instructions="You are a writer. Turn research into engaging content.",
)
editor = client.create_agent(
editor = client.as_agent(
name="editor",
instructions="You are an editor. Review and finalize the content. End with APPROVED if satisfied.",
)
@@ -65,19 +65,19 @@ async def run_agent_framework() -> None:
client = OpenAIChatClient(model_id="gpt-4.1-mini")
# Create specialized agents
python_expert = client.create_agent(
python_expert = client.as_agent(
name="python_expert",
instructions="You are a Python programming expert. Answer Python-related questions.",
description="Expert in Python programming",
)
javascript_expert = client.create_agent(
javascript_expert = client.as_agent(
name="javascript_expert",
instructions="You are a JavaScript programming expert. Answer JavaScript-related questions.",
description="Expert in JavaScript programming",
)
database_expert = client.create_agent(
database_expert = client.as_agent(
name="database_expert",
instructions="You are a database expert. Answer SQL and database-related questions.",
description="Expert in databases and SQL",
@@ -87,7 +87,7 @@ async def run_agent_framework() -> None:
GroupChatBuilder()
.participants([python_expert, javascript_expert, database_expert])
.set_manager(
manager=client.create_agent(
manager=client.as_agent(
name="selector_manager",
instructions="Based on the conversation, select the most appropriate expert to respond next.",
),
@@ -108,7 +108,7 @@ async def run_agent_framework() -> None:
client = OpenAIChatClient(model_id="gpt-4.1-mini")
# Create triage agent
triage_agent = client.create_agent(
triage_agent = client.as_agent(
name="triage",
instructions=(
"You are a triage agent. Analyze the user's request and route to the appropriate specialist:\n"
@@ -119,14 +119,14 @@ async def run_agent_framework() -> None:
)
# Create billing specialist
billing_agent = client.create_agent(
billing_agent = client.as_agent(
name="billing_agent",
instructions="You are a billing specialist. Help with payment and billing questions. Provide clear assistance.",
description="Handles billing and payment questions",
)
# Create technical support specialist
tech_support = client.create_agent(
tech_support = client.as_agent(
name="technical_support",
instructions="You are technical support. Help with technical issues. Provide clear assistance.",
description="Handles technical support questions",
@@ -69,19 +69,19 @@ async def run_agent_framework() -> None:
client = OpenAIChatClient(model_id="gpt-4.1-mini")
# Create specialized agents
researcher = client.create_agent(
researcher = client.as_agent(
name="researcher",
instructions="You are a research analyst. Gather and analyze information.",
description="Research analyst for data gathering",
)
coder = client.create_agent(
coder = client.as_agent(
name="coder",
instructions="You are a programmer. Write code based on requirements.",
description="Software developer for implementation",
)
reviewer = client.create_agent(
reviewer = client.as_agent(
name="reviewer",
instructions="You are a code reviewer. Review code for quality and correctness.",
description="Code reviewer for quality assurance",
@@ -33,7 +33,7 @@ async def run_agent_framework() -> None:
# AF constructs a lightweight ChatAgent backed by OpenAIChatClient
client = OpenAIChatClient(model_id="gpt-4.1-mini")
agent = client.create_agent(
agent = client.as_agent(
name="assistant",
instructions="You are a helpful assistant. Answer in one sentence.",
)
@@ -65,7 +65,7 @@ async def run_agent_framework() -> None:
# Create agent with tool
client = OpenAIChatClient(model_id="gpt-4.1-mini")
agent = client.create_agent(
agent = client.as_agent(
name="assistant",
instructions="You are a helpful assistant. Use available tools to answer questions.",
tools=[get_weather],
@@ -40,7 +40,7 @@ async def run_agent_framework() -> None:
from agent_framework.openai import OpenAIChatClient
client = OpenAIChatClient(model_id="gpt-4.1-mini")
agent = client.create_agent(
agent = client.as_agent(
name="assistant",
instructions="You are a helpful math tutor.",
)
@@ -54,7 +54,7 @@ async def run_agent_framework() -> None:
client = OpenAIChatClient(model_id="gpt-4.1-mini")
# Create specialized writer agent
writer = client.create_agent(
writer = client.as_agent(
name="writer",
instructions="You are a creative writer. Write short, engaging content.",
)
@@ -68,7 +68,7 @@ async def run_agent_framework() -> None:
)
# Create coordinator agent with writer tool
coordinator = client.create_agent(
coordinator = client.as_agent(
name="coordinator",
instructions="You coordinate with specialized agents. Delegate writing tasks to the writer agent.",
tools=[writer_tool],
@@ -8,7 +8,7 @@ from azure.identity import DefaultAzureCredential
def main():
# Create an Agent using the Azure OpenAI Chat Client with a MCP Tool that connects to Microsoft Learn MCP
agent = AzureOpenAIChatClient(credential=DefaultAzureCredential()).create_agent(
agent = AzureOpenAIChatClient(credential=DefaultAzureCredential()).as_agent(
name="DocsAgent",
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
tools=HostedMCPTool(
@@ -93,7 +93,7 @@ class TextSearchContextProvider(ContextProvider):
def main():
# Create an Agent using the Azure OpenAI Chat Client
agent = AzureOpenAIChatClient(credential=DefaultAzureCredential()).create_agent(
agent = AzureOpenAIChatClient(credential=DefaultAzureCredential()).as_agent(
name="SupportSpecialist",
instructions=(
"You are a helpful support specialist for Contoso Outdoors. "
@@ -8,21 +8,21 @@ from azure.identity import DefaultAzureCredential # pyright: ignore[reportUnkno
def main():
# Create agents
researcher = AzureOpenAIChatClient(credential=DefaultAzureCredential()).create_agent(
researcher = AzureOpenAIChatClient(credential=DefaultAzureCredential()).as_agent(
instructions=(
"You're an expert market and product researcher. "
"Given a prompt, provide concise, factual insights, opportunities, and risks."
),
name="researcher",
)
marketer = AzureOpenAIChatClient(credential=DefaultAzureCredential()).create_agent(
marketer = AzureOpenAIChatClient(credential=DefaultAzureCredential()).as_agent(
instructions=(
"You're a creative marketing strategist. "
"Craft compelling value propositions and target messaging aligned to the prompt."
),
name="marketer",
)
legal = AzureOpenAIChatClient(credential=DefaultAzureCredential()).create_agent(
legal = AzureOpenAIChatClient(credential=DefaultAzureCredential()).as_agent(
instructions=(
"You're a cautious legal/compliance reviewer. "
"Highlight constraints, disclaimers, and policy concerns based on the prompt."
@@ -93,7 +93,7 @@ def get_weather(
def build_agent() -> ChatAgent:
"""Create and return the chat agent instance with weather tool registered."""
return OpenAIChatClient().create_agent(
return OpenAIChatClient().as_agent(
name="WeatherAgent", instructions="You are a helpful weather agent.", tools=get_weather
)
@@ -78,7 +78,7 @@ class ResearchLead(Executor):
def __init__(self, chat_client: AzureAIClient, id: str = "travel-planning-coordinator"):
# store=True to preserve conversation history for evaluation
self.agent = chat_client.create_agent(
self.agent = chat_client.as_agent(
id="travel-planning-coordinator",
instructions=(
"You are the final coordinator. You will receive responses from multiple agents: "
@@ -220,7 +220,7 @@ async def _create_workflow(project_client, credential):
travel_request_handler_client = AzureAIClient(
project_client=project_client, credential=credential, agent_name="travel-request-handler"
)
travel_request_handler = travel_request_handler_client.create_agent(
travel_request_handler = travel_request_handler_client.as_agent(
id="travel-request-handler",
instructions=(
"You receive user travel queries and relay them to specialized agents. Extract key information: destination, dates, budget, and preferences. Pass this information forward clearly to the next agents."
@@ -233,7 +233,7 @@ async def _create_workflow(project_client, credential):
hotel_search_client = AzureAIClient(
project_client=project_client, credential=credential, agent_name="hotel-search-agent"
)
hotel_search_agent = hotel_search_client.create_agent(
hotel_search_agent = hotel_search_client.as_agent(
id="hotel-search-agent",
instructions=(
"You are a hotel search specialist. Your task is ONLY to search for and provide hotel information. Use search_hotels to find options, get_hotel_details for specifics, and check_availability to verify rooms. Output format: List hotel names, prices per night, total cost for the stay, locations, ratings, amenities, and addresses. IMPORTANT: Only provide hotel information without additional commentary."
@@ -247,7 +247,7 @@ async def _create_workflow(project_client, credential):
flight_search_client = AzureAIClient(
project_client=project_client, credential=credential, agent_name="flight-search-agent"
)
flight_search_agent = flight_search_client.create_agent(
flight_search_agent = flight_search_client.as_agent(
id="flight-search-agent",
instructions=(
"You are a flight search specialist. Your task is ONLY to search for and provide flight information. Use search_flights to find options, get_flight_details for specifics, and check_availability for seats. Output format: List flight numbers, airlines, departure/arrival times, prices, durations, and cabin class. IMPORTANT: Only provide flight information without additional commentary."
@@ -261,7 +261,7 @@ async def _create_workflow(project_client, credential):
activity_search_client = AzureAIClient(
project_client=project_client, credential=credential, agent_name="activity-search-agent"
)
activity_search_agent = activity_search_client.create_agent(
activity_search_agent = activity_search_client.as_agent(
id="activity-search-agent",
instructions=(
"You are an activities specialist. Your task is ONLY to search for and provide activity information. Use search_activities to find options for activities. Output format: List activity names, descriptions, prices, durations, ratings, and categories. IMPORTANT: Only provide activity information without additional commentary."
@@ -275,7 +275,7 @@ async def _create_workflow(project_client, credential):
booking_confirmation_client = AzureAIClient(
project_client=project_client, credential=credential, agent_name="booking-confirmation-agent"
)
booking_confirmation_agent = booking_confirmation_client.create_agent(
booking_confirmation_agent = booking_confirmation_client.as_agent(
id="booking-confirmation-agent",
instructions=(
"You confirm bookings. Use check_hotel_availability and check_flight_availability to verify slots, then confirm_booking to finalize. Provide ONLY: confirmation numbers, booking references, and confirmation status."
@@ -289,7 +289,7 @@ async def _create_workflow(project_client, credential):
booking_payment_client = AzureAIClient(
project_client=project_client, credential=credential, agent_name="booking-payment-agent"
)
booking_payment_agent = booking_payment_client.create_agent(
booking_payment_agent = booking_payment_client.as_agent(
id="booking-payment-agent",
instructions=(
"You process payments. Use validate_payment_method to verify payment, then process_payment to complete transactions. Provide ONLY: payment confirmation status, transaction IDs, and payment amounts."
@@ -303,7 +303,7 @@ async def _create_workflow(project_client, credential):
booking_info_client = AzureAIClient(
project_client=project_client, credential=credential, agent_name="booking-info-aggregation-agent"
)
booking_info_aggregation_agent = booking_info_client.create_agent(
booking_info_aggregation_agent = booking_info_client.as_agent(
id="booking-info-aggregation-agent",
instructions=(
"You aggregate hotel and flight search results. Receive options from search agents and organize them. Provide: top 2-3 hotel options with prices and top 2-3 flight options with prices in a structured format."
@@ -17,7 +17,7 @@ This sample demonstrates using Anthropic with:
async def main() -> None:
"""Example of streaming response (get results as they are generated)."""
agent = AnthropicClient[AnthropicChatOptions]().create_agent(
agent = AnthropicClient[AnthropicChatOptions]().as_agent(
name="DocsAgent",
instructions="You are a helpful agent for both Microsoft docs questions and general questions.",
tools=[
@@ -26,7 +26,7 @@ async def non_streaming_example() -> None:
print("=== Non-streaming Response Example ===")
agent = AnthropicClient(
).create_agent(
).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
@@ -43,7 +43,7 @@ async def streaming_example() -> None:
print("=== Streaming Response Example ===")
agent = AnthropicClient(
).create_agent(
).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
@@ -28,7 +28,7 @@ To use the Foundry integration ensure you have the following environment variabl
async def main() -> None:
"""Example of streaming response (get results as they are generated)."""
agent = AnthropicClient(anthropic_client=AsyncAnthropicFoundry()).create_agent(
agent = AnthropicClient(anthropic_client=AsyncAnthropicFoundry()).as_agent(
name="DocsAgent",
instructions="You are a helpful agent for both Microsoft docs questions and general questions.",
tools=[
@@ -31,7 +31,7 @@ async def main() -> None:
# Create a agent with the pptx skill enabled
# Skills also need the code interpreter tool to function
agent = client.create_agent(
agent = client.as_agent(
name="DocsAgent",
instructions="You are a helpful agent for creating powerpoint presentations.",
tools=HostedCodeInterpreterTool(),
@@ -145,49 +145,6 @@ async def get_agent_by_reference_example() -> None:
)
async def get_agent_by_details_example() -> None:
"""Example of using provider.get_agent(details=...) with pre-fetched AgentDetails.
This method uses pre-fetched AgentDetails to get the latest version.
Use this when you already have AgentDetails from a previous API call.
"""
print("=== provider.get_agent(details=...) 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="TestAgentByDetails",
description="Test agent for get_agent by details example.",
definition=PromptAgentDefinition(
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
instructions="You are a helpful assistant. Always include an emoji in your response.",
),
)
try:
# Fetch AgentDetails separately (simulating a previous API call)
agent_details = await project_client.agents.get(agent_name=created_agent.name)
# Get the agent using the pre-fetched details (sync - no HTTP call)
provider = AzureAIProjectAgentProvider(project_client=project_client)
agent = provider.as_agent(agent_details.versions.latest)
print(f"Retrieved agent: {agent.name} (from pre-fetched details)")
query = "How are you today?"
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.
@@ -284,7 +241,6 @@ async def main() -> None:
await create_agent_example()
await get_agent_by_name_example()
await get_agent_by_reference_example()
await get_agent_by_details_example()
await as_agent_example()
await multiple_agents_example()
@@ -32,7 +32,7 @@ async def non_streaming_example() -> None:
# and deleted after getting a response
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
async with AzureOpenAIAssistantsClient(credential=AzureCliCredential()).create_agent(
async with AzureOpenAIAssistantsClient(credential=AzureCliCredential()).as_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent:
@@ -48,7 +48,7 @@ async def streaming_example() -> None:
# Since no assistant ID is provided, the assistant will be automatically created
# and deleted after getting a response
async with AzureOpenAIAssistantsClient(credential=AzureCliCredential()).create_agent(
async with AzureOpenAIAssistantsClient(credential=AzureCliCredential()).as_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent:
@@ -34,7 +34,7 @@ async def main() -> None:
endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
deployment_name=os.environ["AZURE_OPENAI_CHAT_DEPLOYMENT_NAME"],
credential=AzureCliCredential(),
).create_agent(
).as_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
) as agent:
@@ -31,7 +31,7 @@ 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()).create_agent(
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
)
@@ -49,7 +49,7 @@ 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()).create_agent(
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
)
@@ -34,7 +34,7 @@ async def main() -> None:
deployment_name=os.environ["AZURE_OPENAI_CHAT_DEPLOYMENT_NAME"],
endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
credential=AzureCliCredential(),
).create_agent(
).as_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
)
@@ -30,7 +30,7 @@ async def non_streaming_example() -> None:
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).create_agent(
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).as_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
)
@@ -47,7 +47,7 @@ async def streaming_example() -> None:
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).create_agent(
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).as_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
)
@@ -18,7 +18,7 @@ async def main():
print("=== Azure Responses Agent with Image Analysis ===")
# 1. Create an Azure Responses agent with vision capabilities
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).create_agent(
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).as_agent(
name="VisionAgent",
instructions="You are a helpful agent that can analyze images.",
)
@@ -34,7 +34,7 @@ async def main() -> None:
deployment_name=os.environ["AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME"],
endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
credential=AzureCliCredential(),
).create_agent(
).as_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
)
@@ -37,7 +37,7 @@ async def main():
credential=credential,
)
agent: ChatAgent = responses_client.create_agent(
agent: ChatAgent = responses_client.as_agent(
name="DocsAgent",
instructions=("You are a helpful assistant that can help with Microsoft documentation questions."),
)
@@ -125,7 +125,7 @@ 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.create_agent(
echo_agent = echo_client.as_agent(
name="EchoAgent",
instructions="You are a helpful assistant that echoes back what users say.",
)
@@ -27,7 +27,7 @@ async def non_streaming_example() -> None:
"""Example of non-streaming response (get the complete result at once)."""
print("=== Non-streaming Response Example ===")
agent = OllamaChatClient().create_agent(
agent = OllamaChatClient().as_agent(
name="TimeAgent",
instructions="You are a helpful time agent answer in one sentence.",
tools=get_time,
@@ -43,7 +43,7 @@ async def streaming_example() -> None:
"""Example of streaming response (get results as they are generated)."""
print("=== Streaming Response Example ===")
agent = OllamaChatClient().create_agent(
agent = OllamaChatClient().as_agent(
name="TimeAgent",
instructions="You are a helpful time agent answer in one sentence.",
tools=get_time,
@@ -21,7 +21,7 @@ https://ollama.com/
async def reasoning_example() -> None:
print("=== Response Reasoning Example ===")
agent = OllamaChatClient().create_agent(
agent = OllamaChatClient().as_agent(
name="TimeAgent",
instructions="You are a helpful agent answer in one sentence.",
default_options={"think": True}, # Enable Reasoning on agent level
@@ -36,7 +36,7 @@ async def non_streaming_example() -> None:
api_key="ollama", # Just a placeholder, Ollama doesn't require API key
base_url=os.getenv("OLLAMA_ENDPOINT"),
model_id=os.getenv("OLLAMA_MODEL"),
).create_agent(
).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
@@ -56,7 +56,7 @@ async def streaming_example() -> None:
api_key="ollama", # Just a placeholder, Ollama doesn't require API key
base_url=os.getenv("OLLAMA_ENDPOINT"),
model_id=os.getenv("OLLAMA_MODEL"),
).create_agent(
).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
@@ -26,7 +26,7 @@ async def non_streaming_example() -> None:
"""Example of non-streaming response (get the complete result at once)."""
print("=== Non-streaming Response Example ===")
agent = OpenAIChatClient().create_agent(
agent = OpenAIChatClient().as_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
@@ -42,7 +42,7 @@ async def streaming_example() -> None:
"""Example of streaming response (get results as they are generated)."""
print("=== Streaming Response Example ===")
agent = OpenAIChatClient().create_agent(
agent = OpenAIChatClient().as_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
@@ -30,7 +30,7 @@ async def main() -> None:
agent = OpenAIChatClient(
model_id=os.environ["OPENAI_CHAT_MODEL_ID"],
api_key=os.environ["OPENAI_API_KEY"],
).create_agent(
).as_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
)
@@ -55,7 +55,7 @@ async def mcp_tools_on_agent_level() -> None:
# Tools are provided when creating the agent
# The agent can use these tools for any query during its lifetime
# The agent will connect to the MCP server through its context manager.
async with OpenAIChatClient().create_agent(
async with OpenAIChatClient().as_agent(
name="DocsAgent",
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
tools=MCPStreamableHTTPTool( # Tools defined at agent creation
@@ -32,7 +32,7 @@ runtime_schema = {
async def non_streaming_example() -> None:
print("=== Non-streaming runtime JSON schema example ===")
agent = OpenAIChatClient[OpenAIChatOptions]().create_agent(
agent = OpenAIChatClient[OpenAIChatOptions]().as_agent(
name="RuntimeSchemaAgent",
instructions="Return only JSON that matches the provided schema. Do not add commentary.",
)
@@ -65,7 +65,7 @@ async def non_streaming_example() -> None:
async def streaming_example() -> None:
print("=== Streaming runtime JSON schema example ===")
agent = OpenAIChatClient().create_agent(
agent = OpenAIChatClient().as_agent(
name="RuntimeSchemaAgent",
instructions="Return only JSON that matches the provided schema. Do not add commentary.",
)
@@ -17,7 +17,7 @@ async def main():
print("=== OpenAI Responses Agent with Image Analysis ===")
# 1. Create an OpenAI Responses agent with vision capabilities
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
name="VisionAgent",
instructions="You are a helpful agent that can analyze images.",
)
@@ -48,7 +48,7 @@ async def main() -> None:
print("=== OpenAI Responses Image Generation Agent Example ===")
# Create an agent with customized image generation options
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
instructions="You are a helpful AI that can generate images.",
tools=[
HostedImageGenerationTool(
@@ -19,7 +19,7 @@ In this case they are here: https://platform.openai.com/docs/api-reference/respo
"""
agent = OpenAIResponsesClient[OpenAIResponsesOptions](model_id="gpt-5").create_agent(
agent = OpenAIResponsesClient[OpenAIResponsesOptions](model_id="gpt-5").as_agent(
name="MathHelper",
instructions="You are a personal math tutor. When asked a math question, "
"reason over how best to approach the problem and share your thought process.",
@@ -42,7 +42,7 @@ async def main():
print("=== OpenAI Streaming Image Generation Example ===\n")
# Create agent with streaming image generation enabled
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
instructions="You are a helpful agent that can generate images.",
tools=[
HostedImageGenerationTool(
@@ -30,7 +30,7 @@ async def main() -> None:
agent = OpenAIResponsesClient(
model_id=os.environ["OPENAI_RESPONSES_MODEL_ID"],
api_key=os.environ["OPENAI_API_KEY"],
).create_agent(
).as_agent(
instructions="You are a helpful weather agent.",
tools=get_weather,
)
@@ -32,7 +32,7 @@ runtime_schema = {
async def non_streaming_example() -> None:
print("=== Non-streaming runtime JSON schema example ===")
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
name="RuntimeSchemaAgent",
instructions="Return only JSON that matches the provided schema. Do not add commentary.",
)
@@ -65,7 +65,7 @@ async def non_streaming_example() -> None:
async def streaming_example() -> None:
print("=== Streaming runtime JSON schema example ===")
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
name="RuntimeSchemaAgent",
instructions="Return only JSON that matches the provided schema. Do not add commentary.",
)
@@ -25,7 +25,7 @@ async def non_streaming_example() -> None:
print("=== Non-streaming example ===")
# Create an OpenAI Responses agent
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
name="CityAgent",
instructions="You are a helpful agent that describes cities in a structured format.",
)
@@ -51,7 +51,7 @@ async def streaming_example() -> None:
print("=== Streaming example ===")
# Create an OpenAI Responses agent
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
name="CityAgent",
instructions="You are a helpful agent that describes cities in a structured format.",
)
@@ -16,7 +16,7 @@ from azure.identity import AzureCliCredential
def _create_agent() -> Any:
"""Create the Joker agent."""
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name="Joker",
instructions="You are good at telling jokes.",
)
@@ -52,13 +52,13 @@ def calculate_tip(bill_amount: float, tip_percentage: float = 15.0) -> dict[str,
# 1. Create multiple agents, each with its own instruction set and tools.
chat_client = AzureOpenAIChatClient(credential=AzureCliCredential())
weather_agent = chat_client.create_agent(
weather_agent = chat_client.as_agent(
name="WeatherAgent",
instructions="You are a helpful weather assistant. Provide current weather information.",
tools=[get_weather],
)
math_agent = chat_client.create_agent(
math_agent = chat_client.as_agent(
name="MathAgent",
instructions="You are a helpful math assistant. Help users with calculations like tip calculations.",
tools=[calculate_tip],
@@ -151,7 +151,7 @@ redis_callback = RedisStreamCallback()
# Create the travel planner agent
def create_travel_agent():
"""Create the TravelPlanner agent with tools."""
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name="TravelPlanner",
instructions="""You are an expert travel planner who creates detailed, personalized travel itineraries.
When asked to plan a trip, you should:
@@ -32,7 +32,7 @@ def _create_writer_agent() -> Any:
"when given an improved sentence you polish it further."
)
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name=WRITER_AGENT_NAME,
instructions=instructions,
)
@@ -29,12 +29,12 @@ CHEMIST_AGENT_NAME = "ChemistAgent"
def _create_agents() -> list[Any]:
chat_client = AzureOpenAIChatClient(credential=AzureCliCredential())
physicist = chat_client.create_agent(
physicist = chat_client.as_agent(
name=PHYSICIST_AGENT_NAME,
instructions="You are an expert in physics. You answer questions from a physics perspective.",
)
chemist = chat_client.create_agent(
chemist = chat_client.as_agent(
name=CHEMIST_AGENT_NAME,
instructions="You are an expert in chemistry. You answer questions from a chemistry perspective.",
)
@@ -45,12 +45,12 @@ class EmailPayload(BaseModel):
def _create_agents() -> list[Any]:
chat_client = AzureOpenAIChatClient(credential=AzureCliCredential())
spam_agent = chat_client.create_agent(
spam_agent = chat_client.as_agent(
name=SPAM_AGENT_NAME,
instructions="You are a spam detection assistant that identifies spam emails.",
)
email_agent = chat_client.create_agent(
email_agent = chat_client.as_agent(
name=EMAIL_AGENT_NAME,
instructions="You are an email assistant that helps users draft responses to emails with professionalism.",
)
@@ -51,7 +51,7 @@ def _create_writer_agent() -> Any:
"Return your response as JSON with 'title' and 'content' fields."
)
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name=WRITER_AGENT_NAME,
instructions=instructions,
)
@@ -145,17 +145,17 @@ from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient
chat_client = AzureOpenAIChatClient()
# Define agents with different roles
joker_agent = chat_client.create_agent(
joker_agent = chat_client.as_agent(
name="Joker",
instructions="You are good at telling jokes.",
)
stock_agent = chat_client.create_agent(
stock_agent = chat_client.as_agent(
name="StockAdvisor",
instructions="Check stock prices.",
)
plant_agent = chat_client.create_agent(
plant_agent = chat_client.as_agent(
name="PlantAdvisor",
instructions="Recommend plants.",
description="Get plant recommendations.",
@@ -30,19 +30,19 @@ chat_client = AzureOpenAIChatClient()
# Define three AI agents with different roles
# Agent 1: Joker - HTTP trigger only (default)
agent1 = chat_client.create_agent(
agent1 = chat_client.as_agent(
name="Joker",
instructions="You are good at telling jokes.",
)
# Agent 2: StockAdvisor - MCP tool trigger only
agent2 = chat_client.create_agent(
agent2 = chat_client.as_agent(
name="StockAdvisor",
instructions="Check stock prices.",
)
# Agent 3: PlantAdvisor - Both HTTP and MCP tool triggers
agent3 = chat_client.create_agent(
agent3 = chat_client.as_agent(
name="PlantAdvisor",
instructions="Recommend plants.",
description="Get plant recommendations.",
@@ -32,7 +32,7 @@ async def main() -> None:
# 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).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="FriendlyAssistant",
instructions="You are a friendly assistant.",
tools=retrieve_company_report,
@@ -35,7 +35,7 @@ async def main() -> None:
local_mem0_client = AsyncMemory()
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="FriendlyAssistant",
instructions="You are a friendly assistant.",
tools=retrieve_company_report,
@@ -27,7 +27,7 @@ async def example_global_thread_scope() -> None:
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="GlobalMemoryAssistant",
instructions="You are an assistant that remembers user preferences across conversations.",
tools=get_user_preferences,
@@ -65,7 +65,7 @@ async def example_per_operation_thread_scope() -> None:
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="ScopedMemoryAssistant",
instructions="You are an assistant with thread-scoped memory.",
tools=get_user_preferences,
@@ -113,14 +113,14 @@ async def example_multiple_agents() -> None:
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="PersonalAssistant",
instructions="You are a personal assistant that helps with personal tasks.",
context_provider=Mem0Provider(
agent_id=agent_id_1,
),
) as personal_agent,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="WorkAssistant",
instructions="You are a work assistant that helps with professional tasks.",
context_provider=Mem0Provider(
@@ -77,7 +77,7 @@ async def main() -> None:
client = OpenAIChatClient()
# Create agent with Azure Redis store
agent = client.create_agent(
agent = client.as_agent(
name="AzureRedisAssistant",
instructions="You are a helpful assistant.",
chat_message_store_factory=chat_message_store_factory,
@@ -178,7 +178,7 @@ async def main() -> None:
client = OpenAIChatClient(model_id=os.getenv("OPENAI_CHAT_MODEL_ID"), api_key=os.getenv("OPENAI_API_KEY"))
# Create agent wired to the Redis context provider. The provider automatically
# persists conversational details and surfaces relevant context on each turn.
agent = client.create_agent(
agent = client.as_agent(
name="MemoryEnhancedAssistant",
instructions=(
"You are a helpful assistant. Personalize replies using provided context. "
@@ -220,7 +220,7 @@ 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 = OpenAIChatClient(model_id=os.getenv("OPENAI_CHAT_MODEL_ID"), api_key=os.getenv("OPENAI_API_KEY"))
agent = client.create_agent(
agent = client.as_agent(
name="MemoryEnhancedAssistant",
instructions=(
"You are a helpful assistant. Personalize replies using provided context. "
@@ -63,7 +63,7 @@ async def main() -> None:
client = OpenAIChatClient(model_id=os.getenv("OPENAI_CHAT_MODEL_ID"), api_key=os.getenv("OPENAI_API_KEY"))
# Create agent wired to the Redis context provider. The provider automatically
# persists conversational details and surfaces relevant context on each turn.
agent = client.create_agent(
agent = client.as_agent(
name="MemoryEnhancedAssistant",
instructions=(
"You are a helpful assistant. Personalize replies using provided context. "
@@ -63,7 +63,7 @@ async def example_global_thread_scope() -> None:
scope_to_per_operation_thread_id=False, # Share memories across all threads
)
agent = client.create_agent(
agent = client.as_agent(
name="GlobalMemoryAssistant",
instructions=(
"You are a helpful assistant. Personalize replies using provided context. "
@@ -125,7 +125,7 @@ async def example_per_operation_thread_scope() -> None:
vector_distance_metric="cosine",
)
agent = client.create_agent(
agent = client.as_agent(
name="ScopedMemoryAssistant",
instructions="You are an assistant with thread-scoped memory.",
context_provider=provider,
@@ -190,7 +190,7 @@ async def example_multiple_agents() -> None:
vector_distance_metric="cosine",
)
personal_agent = client.create_agent(
personal_agent = client.as_agent(
name="PersonalAssistant",
instructions="You are a personal assistant that helps with personal tasks.",
context_provider=personal_provider,
@@ -208,7 +208,7 @@ async def example_multiple_agents() -> None:
vector_distance_metric="cosine",
)
work_agent = client.create_agent(
work_agent = client.as_agent(
name="WorkAssistant",
instructions="You are a work assistant that helps with professional tasks.",
context_provider=work_provider,
@@ -62,7 +62,7 @@ def is_approved(message: Any) -> bool:
chat_client = AzureOpenAIChatClient(api_key=os.environ.get("AZURE_OPENAI_API_KEY", ""))
# Create Writer agent - generates content
writer = chat_client.create_agent(
writer = chat_client.as_agent(
name="Writer",
instructions=(
"You are an excellent content writer. "
@@ -72,7 +72,7 @@ writer = chat_client.create_agent(
)
# Create Reviewer agent - evaluates and provides structured feedback
reviewer = chat_client.create_agent(
reviewer = chat_client.as_agent(
name="Reviewer",
instructions=(
"You are an expert content reviewer. "
@@ -90,7 +90,7 @@ reviewer = chat_client.create_agent(
)
# Create Editor agent - improves content based on feedback
editor = chat_client.create_agent(
editor = chat_client.as_agent(
name="Editor",
instructions=(
"You are a skilled editor. "
@@ -101,7 +101,7 @@ editor = chat_client.create_agent(
)
# Create Publisher agent - formats content for publication
publisher = chat_client.create_agent(
publisher = chat_client.as_agent(
name="Publisher",
instructions=(
"You are a publishing agent. "
@@ -111,7 +111,7 @@ publisher = chat_client.create_agent(
)
# Create Summarizer agent - creates final publication report
summarizer = chat_client.create_agent(
summarizer = chat_client.as_agent(
name="Summarizer",
instructions=(
"You are a summarizer agent. "
@@ -113,7 +113,7 @@ async def main() -> None:
credential = AzureCliCredential()
# 2. Create agent inline
agent = AzureOpenAIChatClient(credential=credential).create_agent(
agent = AzureOpenAIChatClient(credential=credential).as_agent(
model="gpt-4o",
instructions="You are a helpful financial advisor..."
)
@@ -41,7 +41,7 @@ async def main() -> None:
# Create the agent
# Constructor automatically reads from environment variables:
# AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_DEPLOYMENT_NAME, AZURE_OPENAI_API_KEY
agent = AzureOpenAIChatClient(credential=credential).create_agent(
agent = AzureOpenAIChatClient(credential=credential).as_agent(
name="FinancialAdvisor",
instructions="""You are a professional financial advisor assistant.
@@ -275,7 +275,7 @@ async def run_self_reflection_batch(
agent = AzureOpenAIChatClient(
credential=AzureCliCredential(),
deployment_name=agent_model,
).create_agent(
).as_agent(
instructions="You are a helpful agent.",
)
@@ -48,7 +48,7 @@ def get_item_price(
async def run() -> None:
# Define an agent
# Agent's name and description provide better context for AI model
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
name="RestaurantAgent",
description="Answer questions about the menu.",
tools=[get_specials, get_item_price],
@@ -166,7 +166,7 @@ async def main() -> None:
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather assistant.",
tools=get_weather,
@@ -142,7 +142,7 @@ async def class_based_chat_middleware() -> None:
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="EnhancedChatAgent",
instructions="You are a helpful AI assistant.",
# Register class-based middleware at agent level (applies to all runs)
@@ -164,7 +164,7 @@ async def function_based_chat_middleware() -> None:
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="FunctionMiddlewareAgent",
instructions="You are a helpful AI assistant.",
# Register function-based middleware at agent level
@@ -194,7 +194,7 @@ async def run_level_middleware() -> None:
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="RunLevelAgent",
instructions="You are a helpful AI assistant.",
tools=get_weather,
@@ -99,7 +99,7 @@ async def main() -> None:
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather assistant.",
tools=get_weather,
@@ -70,7 +70,7 @@ async def main() -> None:
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="TimeAgent",
instructions="You are a helpful time assistant. Call get_current_time when asked about time.",
tools=get_current_time,
@@ -58,7 +58,7 @@ async def main() -> None:
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="DataAgent",
instructions="You are a helpful data assistant. Use the data service tool to fetch information for users.",
tools=unstable_data_service,
@@ -83,7 +83,7 @@ async def main() -> None:
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather assistant.",
tools=get_weather,
@@ -110,7 +110,7 @@ async def pre_termination_middleware() -> None:
print("\n--- Example 1: Pre-termination Middleware ---")
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather assistant.",
tools=get_weather,
@@ -137,7 +137,7 @@ async def post_termination_middleware() -> None:
print("\n--- Example 2: Post-termination Middleware ---")
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather assistant.",
tools=get_weather,
@@ -83,7 +83,7 @@ async def main() -> None:
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather assistant. Use the weather tool to get current conditions.",
tools=get_weather,
@@ -147,7 +147,7 @@ async def pattern_1_single_agent_with_closure() -> None:
client = OpenAIChatClient(model_id="gpt-4o-mini")
# Create agent with both tools and shared context via middleware
communication_agent = client.create_agent(
communication_agent = client.as_agent(
name="communication_agent",
instructions=(
"You are a communication assistant that can send emails and notifications. "
@@ -294,14 +294,14 @@ async def pattern_2_hierarchical_with_kwargs_propagation() -> None:
client = OpenAIChatClient(model_id="gpt-4o-mini")
# Create specialized sub-agents
email_agent = client.create_agent(
email_agent = client.as_agent(
name="email_agent",
instructions="You send emails using the send_email_v2 tool.",
tools=[send_email_v2],
middleware=[email_kwargs_tracker],
)
sms_agent = client.create_agent(
sms_agent = client.as_agent(
name="sms_agent",
instructions="You send SMS messages using the send_sms tool.",
tools=[send_sms],
@@ -309,7 +309,7 @@ async def pattern_2_hierarchical_with_kwargs_propagation() -> None:
)
# Create coordinator that delegates to sub-agents
coordinator = client.create_agent(
coordinator = client.as_agent(
name="coordinator",
instructions=(
"You coordinate communication tasks. "
@@ -396,7 +396,7 @@ async def pattern_3_hierarchical_with_middleware() -> None:
client = OpenAIChatClient(model_id="gpt-4o-mini")
# Sub-agent with validation middleware
protected_agent = client.create_agent(
protected_agent = client.as_agent(
name="protected_agent",
instructions="You perform protected operations that require authentication.",
tools=[protected_operation],
@@ -404,7 +404,7 @@ async def pattern_3_hierarchical_with_middleware() -> None:
)
# Coordinator delegates to protected agent
coordinator = client.create_agent(
coordinator = client.as_agent(
name="coordinator",
instructions="You coordinate protected operations. Delegate to protected_executor.",
tools=[
@@ -93,7 +93,7 @@ async def main() -> None:
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="UtilityAgent",
instructions="You are a helpful assistant that can provide weather information and current time.",
tools=[get_weather, get_time],
@@ -70,7 +70,7 @@ async def main() -> None:
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather assistant.",
tools=get_weather,
@@ -15,7 +15,7 @@ def get_weather(
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
agent = OpenAIChatClient().create_agent(
agent = OpenAIChatClient().as_agent(
name="WeatherAgent", instructions="You are a helpful weather agent.", tools=get_weather
)
print(asyncio.run(agent.run("What's the weather like in Seattle?")))
@@ -58,7 +58,7 @@ async def main() -> None:
# OpenAI Chat Client is used as an example here,
# other chat clients can be used as well.
agent = OpenAIChatClient().create_agent(
agent = OpenAIChatClient().as_agent(
name="CustomBot",
instructions="You are a helpful assistant that remembers our conversation.",
# Use custom chat message store.
@@ -33,7 +33,7 @@ async def example_manual_memory_store() -> None:
thread = AgentThread(message_store=redis_store)
# Create agent
agent = OpenAIChatClient().create_agent(
agent = OpenAIChatClient().as_agent(
name="RedisBot",
instructions="You are a helpful assistant that remembers our conversation using Redis.",
)
@@ -76,7 +76,7 @@ async def example_user_session_management() -> None:
)
# Create agent with factory pattern
agent = OpenAIChatClient().create_agent(
agent = OpenAIChatClient().as_agent(
name="SessionBot",
instructions="You are a helpful assistant. Keep track of user preferences.",
chat_message_store_factory=create_user_session_store,
@@ -129,7 +129,7 @@ async def example_conversation_persistence() -> None:
)
thread1 = AgentThread(message_store=store1)
agent = OpenAIChatClient().create_agent(
agent = OpenAIChatClient().as_agent(
name="PersistentBot",
instructions="You are a helpful assistant. Remember our conversation history.",
)
@@ -189,7 +189,7 @@ async def example_thread_serialization() -> None:
original_thread = AgentThread(message_store=original_store)
agent = OpenAIChatClient().create_agent(
agent = OpenAIChatClient().as_agent(
name="SerializationBot",
instructions="You are a helpful assistant.",
)
@@ -241,7 +241,7 @@ async def example_message_limits() -> None:
)
thread = AgentThread(message_store=store)
agent = OpenAIChatClient().create_agent(
agent = OpenAIChatClient().as_agent(
name="LimitBot",
instructions="You are a helpful assistant with limited memory.",
)
@@ -22,7 +22,7 @@ async def suspend_resume_service_managed_thread() -> None:
# AzureAIAgentClient supports service-managed threads.
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).create_agent(
AzureAIAgentClient(credential=credential).as_agent(
name="MemoryBot", instructions="You are a helpful assistant that remembers our conversation."
) as agent,
):
@@ -55,7 +55,7 @@ async def suspend_resume_in_memory_thread() -> None:
# OpenAI Chat Client is used as an example here,
# other chat clients can be used as well.
agent = OpenAIChatClient().create_agent(
agent = OpenAIChatClient().as_agent(
name="MemoryBot", instructions="You are a helpful assistant that remembers our conversation."
)
@@ -80,7 +80,7 @@ class MyTools:
# Create instance and use methods as tools
tools = MyTools(mode="safe")
agent = client.create_agent(tools=tools.process)
agent = client.as_agent(tools=tools.process)
# Change behavior dynamically
tools.mode = "normal"
@@ -19,7 +19,7 @@ async def main():
description="Get the current time in ISO 8601 format.",
)
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
name="DeclarationOnlyToolAgent",
instructions="You are a helpful agent that uses tools.",
tools=function_declaration,
@@ -57,7 +57,7 @@ async def main() -> None:
# - "func": the parameter name that will receive the injected function
tool = AIFunction.from_dict(definition, dependencies={"ai_function": {"name:add_numbers": {"func": func}}})
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
name="FunctionToolAgent", instructions="You are a helpful assistant.", tools=tool
)
response = await agent.run("What is 5 + 3?")
@@ -36,7 +36,7 @@ def safe_divide(
async def main():
# tools = Tools()
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
name="ToolAgent",
instructions="Use the provided tools.",
tools=[greet, safe_divide],
@@ -36,7 +36,7 @@ def get_weather(
async def main() -> None:
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
name="WeatherAgent",
instructions="You are a helpful weather assistant.",
tools=[get_weather],
@@ -31,7 +31,7 @@ def safe_divide(
async def main():
# tools = Tools()
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
name="ToolAgent",
instructions="Use the provided tools.",
tools=[safe_divide],
@@ -20,7 +20,7 @@ def unicorn_function(times: Annotated[int, "The number of unicorns to return."])
async def main():
# tools = Tools()
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
name="ToolAgent",
instructions="Use the provided tools.",
tools=[unicorn_function],
@@ -35,7 +35,7 @@ async def get_weather(
async def main() -> None:
agent = OpenAIChatClient().create_agent(
agent = OpenAIChatClient().as_agent(
name="WeatherAgent", instructions="You are a helpful weather assistant.", tools=[get_weather]
)
@@ -45,7 +45,7 @@ async def main():
# Applying the ai_function decorator to one of the methods of the class
add_function = ai_function(description="Add two numbers.")(tools.add)
agent = OpenAIResponsesClient().create_agent(
agent = OpenAIResponsesClient().as_agent(
name="ToolAgent",
instructions="Use the provided tools.",
)
@@ -27,7 +27,7 @@ async def main():
client.function_invocation_configuration.max_iterations = 40
print(f"Function invocation configured as: \n{client.function_invocation_configuration.to_json(indent=2)}")
agent = client.create_agent(name="ToolAgent", instructions="Use the provided tools.", tools=add)
agent = client.as_agent(name="ToolAgent", instructions="Use the provided tools.", tools=add)
print("=" * 60)
print("Call add(239847293, 29834)")
@@ -28,14 +28,14 @@ async def main():
"""Build and run a simple two node agent workflow: Writer then Reviewer."""
# Create the Azure chat client. AzureCliCredential uses your current az login.
chat_client = AzureOpenAIChatClient(credential=AzureCliCredential())
writer_agent = chat_client.create_agent(
writer_agent = chat_client.as_agent(
instructions=(
"You are an excellent content writer. You create new content and edit contents based on the feedback."
),
name="writer",
)
reviewer_agent = chat_client.create_agent(
reviewer_agent = chat_client.as_agent(
instructions=(
"You are an excellent content reviewer."
"Provide actionable feedback to the writer about the provided content."
@@ -52,7 +52,7 @@ class Writer(Executor):
def __init__(self, chat_client: AzureOpenAIChatClient, id: str = "writer"):
# Create a domain specific agent using your configured AzureOpenAIChatClient.
self.agent = chat_client.create_agent(
self.agent = chat_client.as_agent(
instructions=(
"You are an excellent content writer. You create new content and edit contents based on the feedback."
),
@@ -89,7 +89,7 @@ class Reviewer(Executor):
def __init__(self, chat_client: AzureOpenAIChatClient, id: str = "reviewer"):
# Create a domain specific agent that evaluates and refines content.
self.agent = chat_client.create_agent(
self.agent = chat_client.as_agent(
instructions=(
"You are an excellent content reviewer. You review the content and provide feedback to the writer."
),

Some files were not shown because too many files have changed in this diff Show More