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
@@ -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."
),
@@ -59,7 +59,7 @@ async def reverse_text(text: str, ctx: WorkflowContext[str]) -> None:
def create_agent() -> ChatAgent:
"""Factory function to create a Writer agent."""
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
instructions=("You decode messages. Try to reconstruct the original message."),
name="decoder",
)
@@ -27,7 +27,7 @@ Prerequisites:
def create_writer_agent(client: AzureAIAgentClient) -> ChatAgent:
return client.create_agent(
return client.as_agent(
name="Writer",
instructions=(
"You are an excellent content writer. You create new content and edit contents based on the feedback."
@@ -36,7 +36,7 @@ def create_writer_agent(client: AzureAIAgentClient) -> ChatAgent:
def create_reviewer_agent(client: AzureAIAgentClient) -> ChatAgent:
return client.create_agent(
return client.as_agent(
name="Reviewer",
instructions=(
"You are an excellent content reviewer. "
@@ -87,7 +87,7 @@ async def enrich_with_references(
def create_research_agent():
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name="research_agent",
instructions=(
"Produce a short, bullet-style briefing with two actionable ideas. Label the section as 'Initial Draft'."
@@ -96,7 +96,7 @@ def create_research_agent():
def create_final_editor_agent():
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name="final_editor_agent",
instructions=(
"Use all conversation context (including external notes) to produce the final answer. "
@@ -27,7 +27,7 @@ Prerequisites:
def create_writer_agent():
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
instructions=(
"You are an excellent content writer. You create new content and edit contents based on the feedback."
),
@@ -36,7 +36,7 @@ def create_writer_agent():
def create_reviewer_agent():
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
instructions=(
"You are an excellent content reviewer."
"Provide actionable feedback to the writer about the provided content."
@@ -168,7 +168,7 @@ class Coordinator(Executor):
def create_writer_agent() -> ChatAgent:
"""Creates a writer agent with tools."""
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name="writer_agent",
instructions=(
"You are a marketing writer. Call the available tools before drafting copy so you are precise. "
@@ -182,7 +182,7 @@ def create_writer_agent() -> ChatAgent:
def create_final_editor_agent() -> ChatAgent:
"""Creates a final editor agent."""
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name="final_editor_agent",
instructions=(
"You are an editor who polishes marketing copy after human approval. "
@@ -28,7 +28,7 @@ async def main() -> None:
# 1) Create three domain agents using AzureOpenAIChatClient
chat_client = AzureOpenAIChatClient(credential=AzureCliCredential())
researcher = chat_client.create_agent(
researcher = chat_client.as_agent(
instructions=(
"You're an expert market and product researcher. Given a prompt, provide concise, factual insights,"
" opportunities, and risks."
@@ -36,7 +36,7 @@ async def main() -> None:
name="researcher",
)
marketer = chat_client.create_agent(
marketer = chat_client.as_agent(
instructions=(
"You're a creative marketing strategist. Craft compelling value propositions and target messaging"
" aligned to the prompt."
@@ -44,7 +44,7 @@ async def main() -> None:
name="marketer",
)
legal = chat_client.create_agent(
legal = chat_client.as_agent(
instructions=(
"You're a cautious legal/compliance reviewer. Highlight constraints, disclaimers, and policy concerns"
" based on the prompt."
@@ -43,7 +43,7 @@ class Writer(Executor):
def __init__(self, id: str = "writer"):
# Create a domain specific agent using your configured AzureOpenAIChatClient.
self.agent = AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
self.agent = AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
instructions=(
"You are an excellent content writer. You create new content and edit contents based on the feedback."
),
@@ -85,7 +85,7 @@ class Reviewer(Executor):
def __init__(self, id: str = "reviewer"):
# Create a domain specific agent that evaluates and refines content.
self.agent = AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
self.agent = AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
instructions=(
"You are an excellent content reviewer. You review the content and provide feedback to the writer."
),
@@ -35,7 +35,7 @@ async def main() -> None:
workflow = (
GroupChatBuilder()
.with_agent_orchestrator(
OpenAIChatClient().create_agent(
OpenAIChatClient().as_agent(
name="Orchestrator",
instructions="You coordinate a team conversation to solve the user's task.",
)
@@ -66,7 +66,7 @@ def create_agents(chat_client: AzureOpenAIChatClient) -> tuple[ChatAgent, ChatAg
Tuple of (triage_agent, refund_agent, order_agent, return_agent)
"""
# Triage agent: Acts as the frontline dispatcher
triage_agent = chat_client.create_agent(
triage_agent = chat_client.as_agent(
instructions=(
"You are frontline support triage. Route customer issues to the appropriate specialist agents "
"based on the problem described."
@@ -75,7 +75,7 @@ def create_agents(chat_client: AzureOpenAIChatClient) -> tuple[ChatAgent, ChatAg
)
# Refund specialist: Handles refund requests
refund_agent = chat_client.create_agent(
refund_agent = chat_client.as_agent(
instructions="You process refund requests.",
name="refund_agent",
# In a real application, an agent can have multiple tools; here we keep it simple
@@ -83,7 +83,7 @@ def create_agents(chat_client: AzureOpenAIChatClient) -> tuple[ChatAgent, ChatAg
)
# Order/shipping specialist: Resolves delivery issues
order_agent = chat_client.create_agent(
order_agent = chat_client.as_agent(
instructions="You handle order and shipping inquiries.",
name="order_agent",
# In a real application, an agent can have multiple tools; here we keep it simple
@@ -91,7 +91,7 @@ def create_agents(chat_client: AzureOpenAIChatClient) -> tuple[ChatAgent, ChatAg
)
# Return specialist: Handles return requests
return_agent = chat_client.create_agent(
return_agent = chat_client.as_agent(
instructions="You manage product return requests.",
name="return_agent",
# In a real application, an agent can have multiple tools; here we keep it simple
@@ -82,7 +82,7 @@ def create_coding_agent(client: AzureAIAgentClient) -> ChatAgent:
Returns:
A ChatAgent configured with coding instructions and tools
"""
return client.create_agent(
return client.as_agent(
name="CodingAgent",
instructions=("You are a helpful assistant that can write and execute Python code to solve problems."),
tools=HostedCodeInterpreterTool(),
@@ -29,12 +29,12 @@ async def main() -> None:
# 1) Create agents
chat_client = AzureOpenAIChatClient(credential=AzureCliCredential())
writer = chat_client.create_agent(
writer = chat_client.as_agent(
instructions=("You are a concise copywriter. Provide a single, punchy marketing sentence based on the prompt."),
name="writer",
)
reviewer = chat_client.create_agent(
reviewer = chat_client.as_agent(
instructions=("You are a thoughtful reviewer. Give brief feedback on the previous assistant message."),
name="reviewer",
)
@@ -79,7 +79,7 @@ async def main() -> None:
chat_client = OpenAIChatClient()
# Create agent with tools that use kwargs
agent = chat_client.create_agent(
agent = chat_client.as_agent(
name="assistant",
instructions=(
"You are a helpful assistant. Use the available tools to help users. "
@@ -40,7 +40,7 @@ async def main() -> None:
# Define factory functions for workflow participants
def create_assistant() -> ChatAgent:
return chat_client.create_agent(
return chat_client.as_agent(
name="assistant",
instructions=(
"You are a helpful assistant. Answer questions based on the conversation "
@@ -49,7 +49,7 @@ async def main() -> None:
)
def create_summarizer() -> ChatAgent:
return chat_client.create_agent(
return chat_client.as_agent(
name="summarizer",
instructions=(
"You are a summarizer. After the assistant responds, provide a brief "
@@ -124,7 +124,7 @@ async def demonstrate_thread_serialization() -> None:
chat_client = OpenAIChatClient()
def create_assistant() -> ChatAgent:
return chat_client.create_agent(
return chat_client.as_agent(
name="memory_assistant",
instructions="You are a helpful assistant with good memory. Remember details from our conversation.",
)
@@ -178,7 +178,7 @@ def create_workflow(checkpoint_storage: FileCheckpointStorage) -> Workflow:
workflow_builder = (
WorkflowBuilder(max_iterations=6)
.register_agent(
lambda: AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
lambda: AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
instructions="Write concise, warm release notes that sound human and helpful.",
# The agent name is stable across runs which keeps checkpoints deterministic.
name="writer",
@@ -60,7 +60,7 @@ def submit_refund(refund_description: str, amount: str, order_id: str) -> str:
def create_agents(client: AzureOpenAIChatClient) -> tuple[ChatAgent, ChatAgent, ChatAgent]:
"""Create a simple handoff scenario: triage, refund, and order specialists."""
triage = client.create_agent(
triage = client.as_agent(
name="triage_agent",
instructions=(
"You are a customer service triage agent. Listen to customer issues and determine "
@@ -69,7 +69,7 @@ def create_agents(client: AzureOpenAIChatClient) -> tuple[ChatAgent, ChatAgent,
),
)
refund = client.create_agent(
refund = client.as_agent(
name="refund_agent",
instructions=(
"You are a refund specialist. Help customers with refund requests. "
@@ -80,7 +80,7 @@ def create_agents(client: AzureOpenAIChatClient) -> tuple[ChatAgent, ChatAgent,
tools=[submit_refund],
)
order = client.create_agent(
order = client.as_agent(
name="order_agent",
instructions=(
"You are an order tracking specialist. Help customers track their orders. "
@@ -44,13 +44,13 @@ async def basic_checkpointing() -> None:
chat_client = OpenAIChatClient()
def create_assistant() -> ChatAgent:
return chat_client.create_agent(
return chat_client.as_agent(
name="assistant",
instructions="You are a helpful assistant. Keep responses brief.",
)
def create_reviewer() -> ChatAgent:
return chat_client.create_agent(
return chat_client.as_agent(
name="reviewer",
instructions="You are a reviewer. Provide a one-sentence summary of the assistant's response.",
)
@@ -88,7 +88,7 @@ async def checkpointing_with_thread() -> None:
chat_client = OpenAIChatClient()
def create_assistant() -> ChatAgent:
return chat_client.create_agent(
return chat_client.as_agent(
name="memory_assistant",
instructions="You are a helpful assistant with good memory. Reference previous conversation when relevant.",
)
@@ -132,7 +132,7 @@ async def streaming_with_checkpoints() -> None:
chat_client = OpenAIChatClient()
def create_assistant() -> ChatAgent:
return chat_client.create_agent(
return chat_client.as_agent(
name="streaming_assistant",
instructions="You are a helpful assistant.",
)
@@ -75,7 +75,7 @@ async def main() -> None:
chat_client = OpenAIChatClient()
# Create an agent with tools that use kwargs
inner_agent = chat_client.create_agent(
inner_agent = chat_client.as_agent(
name="data_agent",
instructions=(
"You are a data access agent. Use the available tools to help users. "
@@ -131,7 +131,7 @@ async def to_email_assistant_request(
def create_spam_detector_agent() -> ChatAgent:
"""Helper to create a spam detection agent."""
# AzureCliCredential uses your current az login. This avoids embedding secrets in code.
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
instructions=(
"You are a spam detection assistant that identifies spam emails. "
"Always return JSON with fields is_spam (bool), reason (string), and email_content (string). "
@@ -145,7 +145,7 @@ def create_spam_detector_agent() -> ChatAgent:
def create_email_assistant_agent() -> ChatAgent:
"""Helper to create an email assistant agent."""
# AzureCliCredential uses your current az login. This avoids embedding secrets in code.
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
instructions=(
"You are an email assistant that helps users draft professional responses to emails. "
"Your input may be a JSON object that includes 'email_content'; base your reply on that content. "
@@ -183,7 +183,7 @@ async def database_access(analysis: AnalysisResult, ctx: WorkflowContext[Never,
def create_email_analysis_agent() -> ChatAgent:
"""Creates the email analysis agent."""
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
instructions=(
"You are a spam detection assistant that identifies spam emails. "
"Always return JSON with fields 'spam_decision' (one of NotSpam, Spam, Uncertain) "
@@ -196,7 +196,7 @@ def create_email_analysis_agent() -> ChatAgent:
def create_email_assistant_agent() -> ChatAgent:
"""Creates the email assistant agent."""
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
instructions=("You are an email assistant that helps users draft responses to emails with professionalism."),
name="email_assistant_agent",
default_options={"response_format": EmailResponse},
@@ -205,7 +205,7 @@ def create_email_assistant_agent() -> ChatAgent:
def create_email_summary_agent() -> ChatAgent:
"""Creates the email summary agent."""
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
instructions=("You are an assistant that helps users summarize emails."),
name="email_summary_agent",
default_options={"response_format": EmailSummaryModel},
@@ -117,7 +117,7 @@ class ParseJudgeResponse(Executor):
def create_judge_agent() -> ChatAgent:
"""Create a judge agent that evaluates guesses."""
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
instructions=("You strictly respond with one of: MATCHED, ABOVE, BELOW based on the given target and guess."),
name="judge_agent",
)
@@ -154,7 +154,7 @@ async def handle_uncertain(detection: DetectionResult, ctx: WorkflowContext[Neve
def create_spam_detection_agent() -> ChatAgent:
"""Create and return the spam detection agent."""
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
instructions=(
"You are a spam detection assistant that identifies spam emails. "
"Be less confident in your assessments. "
@@ -168,7 +168,7 @@ def create_spam_detection_agent() -> ChatAgent:
def create_email_assistant_agent() -> ChatAgent:
"""Create and return the email assistant agent."""
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
instructions=("You are an email assistant that helps users draft responses to emails with professionalism."),
name="email_assistant_agent",
default_options={"response_format": EmailResponse},
@@ -168,40 +168,40 @@ async def main() -> None:
chat_client = AzureOpenAIChatClient(credential=AzureCliCredential())
# Create agents with structured outputs
self_service_agent = chat_client.create_agent(
self_service_agent = chat_client.as_agent(
name="SelfServiceAgent",
instructions=SELF_SERVICE_INSTRUCTIONS,
default_options={"response_format": SelfServiceResponse},
)
ticketing_agent = chat_client.create_agent(
ticketing_agent = chat_client.as_agent(
name="TicketingAgent",
instructions=TICKETING_INSTRUCTIONS,
tools=plugin.get_functions(),
default_options={"response_format": TicketingResponse},
)
routing_agent = chat_client.create_agent(
routing_agent = chat_client.as_agent(
name="TicketRoutingAgent",
instructions=TICKET_ROUTING_INSTRUCTIONS,
tools=[plugin.get_ticket],
default_options={"response_format": RoutingResponse},
)
windows_support_agent = chat_client.create_agent(
windows_support_agent = chat_client.as_agent(
name="WindowsSupportAgent",
instructions=WINDOWS_SUPPORT_INSTRUCTIONS,
tools=[plugin.get_ticket],
default_options={"response_format": SupportResponse},
)
resolution_agent = chat_client.create_agent(
resolution_agent = chat_client.as_agent(
name="TicketResolutionAgent",
instructions=RESOLUTION_INSTRUCTIONS,
tools=[plugin.resolve_ticket],
)
escalation_agent = chat_client.create_agent(
escalation_agent = chat_client.as_agent(
name="TicketEscalationAgent",
instructions=ESCALATION_INSTRUCTIONS,
tools=[plugin.get_ticket, plugin.send_notification],
@@ -126,38 +126,38 @@ async def main() -> None:
chat_client = AzureOpenAIChatClient(credential=AzureCliCredential())
# Create agents
research_agent = chat_client.create_agent(
research_agent = chat_client.as_agent(
name="ResearchAgent",
instructions=RESEARCH_INSTRUCTIONS,
)
planner_agent = chat_client.create_agent(
planner_agent = chat_client.as_agent(
name="PlannerAgent",
instructions=PLANNER_INSTRUCTIONS,
)
manager_agent = chat_client.create_agent(
manager_agent = chat_client.as_agent(
name="ManagerAgent",
instructions=MANAGER_INSTRUCTIONS,
default_options={"response_format": ManagerResponse},
)
summary_agent = chat_client.create_agent(
summary_agent = chat_client.as_agent(
name="SummaryAgent",
instructions=SUMMARY_INSTRUCTIONS,
)
knowledge_agent = chat_client.create_agent(
knowledge_agent = chat_client.as_agent(
name="KnowledgeAgent",
instructions=KNOWLEDGE_INSTRUCTIONS,
)
coder_agent = chat_client.create_agent(
coder_agent = chat_client.as_agent(
name="CoderAgent",
instructions=CODER_INSTRUCTIONS,
)
weather_agent = chat_client.create_agent(
weather_agent = chat_client.as_agent(
name="WeatherAgent",
instructions=WEATHER_INSTRUCTIONS,
)
@@ -73,7 +73,7 @@ Session Complete
```python
# Create the agent with tools
chat_client = AzureOpenAIChatClient(credential=AzureCliCredential())
menu_agent = chat_client.create_agent(
menu_agent = chat_client.as_agent(
name="MenuAgent",
instructions="You are a helpful restaurant menu assistant...",
tools=[get_menu, get_specials, get_item_price],

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