Python: Clean up imports (#2318)

* chore: tidy imports

* Update python/packages/azurefunctions/agent_framework_azurefunctions/_errors.py

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update python/packages/azurefunctions/agent_framework_azurefunctions/_callbacks.py

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* chore: revert stub file change

* chore: trigger pre-commit hook, re-add `annotations` import

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
Brandon McConnell
2025-11-19 18:41:01 -05:00
committed by GitHub
Unverified
parent b3e96b80ae
commit 79bb87061b
45 changed files with 191 additions and 228 deletions
@@ -250,7 +250,7 @@ class WeatherChatKitServer(ChatKitServer[dict[str, Any]]):
context: The context dictionary.
"""
logger.info(f"Attempting to update thread title for thread: {thread.id}")
if not thread_items:
logger.debug("No thread items available for title generation")
return
@@ -33,7 +33,7 @@ async def non_streaming_example() -> None:
print("=== Non-streaming Response Example ===")
agent = OpenAIChatClient(
api_key="ollama", # Just a placeholder, Ollama doesn't require API key
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(
@@ -53,7 +53,7 @@ async def streaming_example() -> None:
print("=== Streaming Response Example ===")
agent = OpenAIChatClient(
api_key="ollama", # Just a placeholder, Ollama doesn't require API key
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(
@@ -10,6 +10,8 @@ from typing import Any
from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient
from azure.identity import AzureCliCredential
# 1. Instantiate the agent with the chosen deployment and instructions.
def _create_agent() -> Any:
"""Create the Joker agent."""
@@ -40,6 +40,7 @@ class EmailPayload(BaseModel):
email_id: str
email_content: str
# 2. Instantiate both agents so they can be registered with AgentFunctionApp.
def _create_agents() -> list[Any]:
chat_client = AzureOpenAIChatClient(credential=AzureCliCredential())
@@ -275,7 +275,7 @@ async def get_orchestration_status(
show_history_output=False,
show_input=True,
)
# Check if status is None or if the instance doesn't exist (runtime_status is None)
if status is None or getattr(status, "runtime_status", None) is None:
return func.HttpResponse(
@@ -15,9 +15,9 @@ from agent_framework import (
FunctionInvocationContext,
Role,
TextContent,
ai_function,
chat_middleware,
function_middleware,
ai_function
)
from agent_framework.azure import AzureOpenAIChatClient
from agent_framework_devui import register_cleanup
@@ -122,6 +122,7 @@ def get_forecast(
return f"Weather forecast for {location}:\n" + "\n".join(forecast)
@ai_function(approval_mode="always_require")
def send_email(
recipient: Annotated[str, "The email address of the recipient."],
@@ -131,6 +132,7 @@ def send_email(
"""Simulate sending an email."""
return f"Email sent to {recipient} with subject '{subject}'."
# Agent instance following Agent Framework conventions
agent = ChatAgent(
name="AzureWeatherAgent",
@@ -13,6 +13,7 @@ def create_sample_image() -> str:
png_data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=="
return f"data:image/png;base64,{png_data}"
async def test_image() -> None:
"""Test image analysis with Azure OpenAI."""
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
@@ -37,5 +38,6 @@ async def main() -> None:
print("Testing image analysis (supported by Chat Completions API)")
await test_image()
if __name__ == "__main__":
asyncio.run(main())
@@ -20,7 +20,6 @@ Environment variables:
- PURVIEW_CERT_PASSWORD (optional)
- PURVIEW_DEFAULT_USER_ID (optional, user ID for Purview evaluation)
"""
from __future__ import annotations
import asyncio
import os
@@ -28,18 +27,17 @@ from typing import Any
from agent_framework import AgentRunResponse, ChatAgent, ChatMessage, Role
from agent_framework.azure import AzureOpenAIChatClient
from agent_framework.microsoft import (
PurviewChatPolicyMiddleware,
PurviewPolicyMiddleware,
PurviewSettings,
)
from azure.identity import (
AzureCliCredential,
CertificateCredential,
InteractiveBrowserCredential,
)
from agent_framework.microsoft import (
PurviewPolicyMiddleware,
PurviewChatPolicyMiddleware,
PurviewSettings,
)
JOKER_NAME = "Joker"
JOKER_INSTRUCTIONS = "You are good at telling jokes. Keep responses concise."
@@ -96,7 +94,6 @@ class SimpleDictCacheProvider:
print(f"[CustomCache] Removed key: {key[:50]}...")
def _get_env(name: str, *, required: bool = True, default: str | None = None) -> str:
val = os.environ.get(name, default)
if required and not val:
@@ -176,7 +173,7 @@ async def run_with_chat_middleware() -> None:
deployment = os.environ.get("AZURE_OPENAI_DEPLOYMENT_NAME", default="gpt-4o-mini")
user_id = os.environ.get("PURVIEW_DEFAULT_USER_ID")
chat_client = AzureOpenAIChatClient(
deployment_name=deployment,
endpoint=endpoint,
@@ -216,6 +213,7 @@ async def run_with_chat_middleware() -> None:
)
print("Second response (chat middleware):\n", second)
async def run_with_custom_cache_provider() -> None:
"""Demonstrate implementing and using a custom cache provider."""
endpoint = os.environ.get("AZURE_OPENAI_ENDPOINT")
@@ -246,7 +244,7 @@ async def run_with_custom_cache_provider() -> None:
print("-- Custom Cache Provider Path --")
print("Using SimpleDictCacheProvider")
first: AgentRunResponse = await agent.run(
ChatMessage(role=Role.USER, text="Tell me a joke about a programmer.", additional_properties={"user_id": user_id})
)
@@ -256,7 +254,7 @@ async def run_with_custom_cache_provider() -> None:
ChatMessage(role=Role.USER, text="That's hilarious! One more?", additional_properties={"user_id": user_id})
)
print("Second response (custom provider):\n", second)
"""Demonstrate using the default built-in cache."""
endpoint = os.environ.get("AZURE_OPENAI_ENDPOINT")
if not endpoint:
@@ -286,7 +284,7 @@ async def run_with_custom_cache_provider() -> None:
print("-- Default Cache Path --")
print("Using default InMemoryCacheProvider with settings-based configuration")
first: AgentRunResponse = await agent.run(
ChatMessage(role=Role.USER, text="Tell me a joke about AI.", additional_properties={"user_id": user_id})
)
@@ -300,7 +298,7 @@ async def run_with_custom_cache_provider() -> None:
async def main() -> None:
print("== Purview Agent Sample (Middleware with Automatic Caching) ==")
try:
await run_with_agent_middleware()
except Exception as ex: # pragma: no cover - demo resilience
@@ -50,7 +50,7 @@ async def main() -> None:
# Create the AIFunction tool using dependency injection
# The 'definition' dictionary contains the serialized tool configuration,
# while the actual function implementation is provided via dependencies.
#
#
# Dependency structure: {"ai_function": {"name:add_numbers": {"func": func}}}
# - "ai_function": matches the tool type identifier
# - "name:add_numbers": instance-specific injection targeting tools with name="add_numbers"
@@ -45,7 +45,7 @@ async def approval_example() -> None:
# Check for approval requests
if result.user_input_requests:
for request in result.user_input_requests:
print(f"\nApproval needed:")
print("\nApproval needed:")
print(f" Function: {request.function_call.name}")
print(f" Arguments: {request.function_call.arguments}")
@@ -79,12 +79,12 @@ async def rejection_example() -> None:
if result.user_input_requests:
for request in result.user_input_requests:
print(f"\nApproval needed:")
print("\nApproval needed:")
print(f" Function: {request.function_call.name}")
print(f" Arguments: {request.function_call.arguments}")
# User rejects
print(f" Decision: Rejected")
print(" Decision: Rejected")
# Send rejection response
rejection_response = request.create_response(approved=False)
@@ -13,32 +13,30 @@ async def run_semantic_kernel() -> None:
from azure.identity.aio import AzureCliCredential
from semantic_kernel.agents import AzureAIAgent, AzureAIAgentSettings
async with AzureCliCredential() as credential:
async with AzureAIAgent.create_client(credential=credential) as client:
settings = AzureAIAgentSettings() # Reads env vars for region/deployment.
# SK builds the remote agent definition then wraps it with AzureAIAgent.
definition = await client.agents.create_agent(
model=settings.model_deployment_name,
name="Support",
instructions="Answer customer questions in one paragraph.",
)
agent = AzureAIAgent(client=client, definition=definition)
response = await agent.get_response("How do I upgrade my plan?")
print("[SK]", response.message.content)
async with AzureCliCredential() as credential, AzureAIAgent.create_client(credential=credential) as client:
settings = AzureAIAgentSettings() # Reads env vars for region/deployment.
# SK builds the remote agent definition then wraps it with AzureAIAgent.
definition = await client.agents.create_agent(
model=settings.model_deployment_name,
name="Support",
instructions="Answer customer questions in one paragraph.",
)
agent = AzureAIAgent(client=client, definition=definition)
response = await agent.get_response("How do I upgrade my plan?")
print("[SK]", response.message.content)
async def run_agent_framework() -> None:
from azure.identity.aio import AzureCliCredential
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential
async with AzureCliCredential() as credential:
async with AzureAIAgentClient(async_credential=credential).create_agent(
name="Support",
instructions="Answer customer questions in one paragraph.",
) as agent:
# AF client returns an asynchronous context manager for remote agents.
reply = await agent.run("How do I upgrade my plan?")
print("[AF]", reply.text)
async with AzureCliCredential() as credential, AzureAIAgentClient(async_credential=credential).create_agent(
name="Support",
instructions="Answer customer questions in one paragraph.",
) as agent:
# AF client returns an asynchronous context manager for remote agents.
reply = await agent.run("How do I upgrade my plan?")
print("[AF]", reply.text)
async def main() -> None:
@@ -13,39 +13,37 @@ async def run_semantic_kernel() -> None:
from azure.identity.aio import AzureCliCredential
from semantic_kernel.agents import AzureAIAgent, AzureAIAgentSettings
async with AzureCliCredential() as credential:
async with AzureAIAgent.create_client(credential=credential) as client:
settings = AzureAIAgentSettings()
# Register the hosted code interpreter tool with the remote agent.
definition = await client.agents.create_agent(
model=settings.model_deployment_name,
name="Analyst",
instructions="Use the code interpreter for numeric work.",
tools=[{"type": "code_interpreter"}],
)
agent = AzureAIAgent(client=client, definition=definition)
response = await agent.get_response(
"Use Python to compute 42 ** 2 and explain the result.",
)
print("[SK]", response.message.content)
async with AzureCliCredential() as credential, AzureAIAgent.create_client(credential=credential) as client:
settings = AzureAIAgentSettings()
# Register the hosted code interpreter tool with the remote agent.
definition = await client.agents.create_agent(
model=settings.model_deployment_name,
name="Analyst",
instructions="Use the code interpreter for numeric work.",
tools=[{"type": "code_interpreter"}],
)
agent = AzureAIAgent(client=client, definition=definition)
response = await agent.get_response(
"Use Python to compute 42 ** 2 and explain the result.",
)
print("[SK]", response.message.content)
async def run_agent_framework() -> None:
from azure.identity.aio import AzureCliCredential
from agent_framework.azure import AzureAIAgentClient, HostedCodeInterpreterTool
from azure.identity.aio import AzureCliCredential
async with AzureCliCredential() as credential:
async with AzureAIAgentClient(async_credential=credential).create_agent(
name="Analyst",
instructions="Use the code interpreter for numeric work.",
tools=[HostedCodeInterpreterTool()],
) as agent:
# HostedCodeInterpreterTool mirrors the built-in Azure AI capability.
reply = await agent.run(
"Use Python to compute 42 ** 2 and explain the result.",
tool_choice="auto",
)
print("[AF]", reply.text)
async with AzureCliCredential() as credential, AzureAIAgentClient(async_credential=credential).create_agent(
name="Analyst",
instructions="Use the code interpreter for numeric work.",
tools=[HostedCodeInterpreterTool()],
) as agent:
# HostedCodeInterpreterTool mirrors the built-in Azure AI capability.
reply = await agent.run(
"Use Python to compute 42 ** 2 and explain the result.",
tool_choice="auto",
)
print("[AF]", reply.text)
async def main() -> None:
@@ -8,53 +8,51 @@ async def run_semantic_kernel() -> None:
from azure.identity.aio import AzureCliCredential
from semantic_kernel.agents import AzureAIAgent, AzureAIAgentSettings, AzureAIAgentThread
async with AzureCliCredential() as credential:
async with AzureAIAgent.create_client(credential=credential) as client:
settings = AzureAIAgentSettings()
definition = await client.agents.create_agent(
model=settings.model_deployment_name,
name="Planner",
instructions="Track follow-up questions within the same thread.",
)
agent = AzureAIAgent(client=client, definition=definition)
async with AzureCliCredential() as credential, AzureAIAgent.create_client(credential=credential) as client:
settings = AzureAIAgentSettings()
definition = await client.agents.create_agent(
model=settings.model_deployment_name,
name="Planner",
instructions="Track follow-up questions within the same thread.",
)
agent = AzureAIAgent(client=client, definition=definition)
thread: AzureAIAgentThread | None = None
# SK returns the updated AzureAIAgentThread on each response.
first = await agent.get_response("Outline the onboarding checklist.", thread=thread)
thread = first.thread
print("[SK][turn1]", first.message.content)
thread: AzureAIAgentThread | None = None
# SK returns the updated AzureAIAgentThread on each response.
first = await agent.get_response("Outline the onboarding checklist.", thread=thread)
thread = first.thread
print("[SK][turn1]", first.message.content)
second = await agent.get_response(
"Highlight the items that require legal review.",
thread=thread,
)
print("[SK][turn2]", second.message.content)
if thread is not None:
print("[SK][thread-id]", thread.id)
second = await agent.get_response(
"Highlight the items that require legal review.",
thread=thread,
)
print("[SK][turn2]", second.message.content)
if thread is not None:
print("[SK][thread-id]", thread.id)
async def run_agent_framework() -> None:
from azure.identity.aio import AzureCliCredential
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential
async with AzureCliCredential() as credential:
async with AzureAIAgentClient(async_credential=credential).create_agent(
name="Planner",
instructions="Track follow-up questions within the same thread.",
) as agent:
thread = agent.get_new_thread()
# AF threads are explicit and can be serialized for external storage.
first = await agent.run("Outline the onboarding checklist.", thread=thread)
print("[AF][turn1]", first.text)
async with AzureCliCredential() as credential, AzureAIAgentClient(async_credential=credential).create_agent(
name="Planner",
instructions="Track follow-up questions within the same thread.",
) as agent:
thread = agent.get_new_thread()
# AF threads are explicit and can be serialized for external storage.
first = await agent.run("Outline the onboarding checklist.", thread=thread)
print("[AF][turn1]", first.text)
second = await agent.run(
"Highlight the items that require legal review.",
thread=thread,
)
print("[AF][turn2]", second.text)
second = await agent.run(
"Highlight the items that require legal review.",
thread=thread,
)
print("[AF][turn2]", second.text)
serialized = await thread.serialize()
print("[AF][thread-json]", serialized)
serialized = await thread.serialize()
print("[AF][thread-json]", serialized)
async def main() -> None: