|
| 1 | +# --------------------------------------------------------- |
| 2 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | +# --------------------------------------------------------- |
| 4 | +# pylint: disable=logging-fstring-interpolation |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +import asyncio # pylint: disable=do-not-import-asyncio |
| 8 | +import os |
| 9 | +from typing import Any, AsyncGenerator, Union |
| 10 | + |
| 11 | +from agent_framework import AgentProtocol |
| 12 | +from agent_framework.azure import AzureAIAgentClient # pylint: disable=no-name-in-module |
| 13 | +from opentelemetry import trace |
| 14 | + |
| 15 | +from azure.ai.agentserver.core import AgentRunContext, FoundryCBAgent |
| 16 | +from azure.ai.agentserver.core.constants import Constants as AdapterConstants |
| 17 | +from azure.ai.agentserver.core.logger import get_logger |
| 18 | +from azure.ai.agentserver.core.models import ( |
| 19 | + CreateResponse, |
| 20 | + Response as OpenAIResponse, |
| 21 | + ResponseStreamEvent, |
| 22 | +) |
| 23 | +from azure.ai.projects import AIProjectClient |
| 24 | +from azure.identity import DefaultAzureCredential |
| 25 | + |
| 26 | +from .models.agent_framework_input_converters import AgentFrameworkInputConverter |
| 27 | +from .models.agent_framework_output_non_streaming_converter import ( |
| 28 | + AgentFrameworkOutputNonStreamingConverter, |
| 29 | +) |
| 30 | +from .models.agent_framework_output_streaming_converter import AgentFrameworkOutputStreamingConverter |
| 31 | +from .models.constants import Constants |
| 32 | + |
| 33 | +logger = get_logger() |
| 34 | + |
| 35 | + |
| 36 | +class AgentFrameworkCBAgent(FoundryCBAgent): |
| 37 | + """ |
| 38 | + Adapter class for integrating Agent Framework agents with the FoundryCB agent interface. |
| 39 | +
|
| 40 | + This class wraps an Agent Framework `AgentProtocol` instance and provides a unified interface |
| 41 | + for running agents in both streaming and non-streaming modes. It handles input and output |
| 42 | + conversion between the Agent Framework and the expected formats for FoundryCB agents. |
| 43 | +
|
| 44 | + Parameters: |
| 45 | + agent (AgentProtocol): An instance of an Agent Framework agent to be adapted. |
| 46 | +
|
| 47 | + Usage: |
| 48 | + - Instantiate with an Agent Framework agent. |
| 49 | + - Call `agent_run` with a `CreateResponse` request body to execute the agent. |
| 50 | + - Supports both streaming and non-streaming responses based on the `stream` flag. |
| 51 | + """ |
| 52 | + |
| 53 | + def __init__(self, agent: AgentProtocol): |
| 54 | + super().__init__() |
| 55 | + self.agent = agent |
| 56 | + logger.info(f"Initialized AgentFrameworkCBAgent with agent: {type(agent).__name__}") |
| 57 | + |
| 58 | + def _resolve_stream_timeout(self, request_body: CreateResponse) -> float: |
| 59 | + """Resolve idle timeout for streaming updates. |
| 60 | +
|
| 61 | + Order of precedence: |
| 62 | + 1) request_body.stream_timeout_s (if provided) |
| 63 | + 2) env var Constants.AGENTS_ADAPTER_STREAM_TIMEOUT_S |
| 64 | + 3) Constants.DEFAULT_STREAM_TIMEOUT_S |
| 65 | +
|
| 66 | + :param request_body: The CreateResponse request body. |
| 67 | + :type request_body: CreateResponse |
| 68 | +
|
| 69 | + :return: The resolved stream timeout in seconds. |
| 70 | + :rtype: float |
| 71 | + """ |
| 72 | + override = request_body.get("stream_timeout_s", None) |
| 73 | + if override is not None: |
| 74 | + return float(override) |
| 75 | + env_val = os.getenv(Constants.AGENTS_ADAPTER_STREAM_TIMEOUT_S) |
| 76 | + return float(env_val) if env_val is not None else float(Constants.DEFAULT_STREAM_TIMEOUT_S) |
| 77 | + |
| 78 | + def init_tracing(self): |
| 79 | + exporter = os.environ.get(AdapterConstants.OTEL_EXPORTER_ENDPOINT) |
| 80 | + app_insights_conn_str = os.environ.get(AdapterConstants.APPLICATION_INSIGHTS_CONNECTION_STRING) |
| 81 | + project_endpoint = os.environ.get(AdapterConstants.AZURE_AI_PROJECT_ENDPOINT) |
| 82 | + |
| 83 | + if project_endpoint: |
| 84 | + project_client = AIProjectClient(endpoint=project_endpoint, credential=DefaultAzureCredential()) |
| 85 | + agent_client = AzureAIAgentClient(project_client=project_client) |
| 86 | + agent_client.setup_azure_ai_observability() |
| 87 | + elif exporter or app_insights_conn_str: |
| 88 | + os.environ["WORKFLOW_ENABLE_OTEL"] = "true" |
| 89 | + from agent_framework.observability import setup_observability |
| 90 | + |
| 91 | + setup_observability( |
| 92 | + enable_sensitive_data=True, |
| 93 | + otlp_endpoint=exporter, |
| 94 | + applicationinsights_connection_string=app_insights_conn_str, |
| 95 | + ) |
| 96 | + self.tracer = trace.get_tracer(__name__) |
| 97 | + |
| 98 | + async def agent_run( |
| 99 | + self, context: AgentRunContext |
| 100 | + ) -> Union[ |
| 101 | + OpenAIResponse, |
| 102 | + AsyncGenerator[ResponseStreamEvent, Any], |
| 103 | + ]: |
| 104 | + logger.info(f"Starting agent_run with stream={context.stream}") |
| 105 | + request_input = context.request.get("input") |
| 106 | + |
| 107 | + input_converter = AgentFrameworkInputConverter() |
| 108 | + message = input_converter.transform_input(request_input) |
| 109 | + logger.debug(f"Transformed input message type: {type(message)}") |
| 110 | + |
| 111 | + # Use split converters |
| 112 | + if context.stream: |
| 113 | + logger.info("Running agent in streaming mode") |
| 114 | + streaming_converter = AgentFrameworkOutputStreamingConverter(context) |
| 115 | + |
| 116 | + async def stream_updates(): |
| 117 | + update_count = 0 |
| 118 | + timeout_s = self._resolve_stream_timeout(context.request) |
| 119 | + logger.info("Starting streaming with idle-timeout=%.2fs", timeout_s) |
| 120 | + for ev in streaming_converter.initial_events(): |
| 121 | + yield ev |
| 122 | + |
| 123 | + # Iterate with per-update timeout; terminate if idle too long |
| 124 | + aiter = self.agent.run_stream(message).__aiter__() |
| 125 | + while True: |
| 126 | + try: |
| 127 | + update = await asyncio.wait_for(aiter.__anext__(), timeout=timeout_s) |
| 128 | + except StopAsyncIteration: |
| 129 | + logger.debug("Agent streaming iterator finished (StopAsyncIteration)") |
| 130 | + break |
| 131 | + except asyncio.TimeoutError: |
| 132 | + logger.warning("Streaming idle timeout reached (%.1fs); terminating stream.", timeout_s) |
| 133 | + for ev in streaming_converter.completion_events(): |
| 134 | + yield ev |
| 135 | + return |
| 136 | + update_count += 1 |
| 137 | + transformed = streaming_converter.transform_output_for_streaming(update) |
| 138 | + for event in transformed: |
| 139 | + yield event |
| 140 | + for ev in streaming_converter.completion_events(): |
| 141 | + yield ev |
| 142 | + logger.info("Streaming completed with %d updates", update_count) |
| 143 | + |
| 144 | + return stream_updates() |
| 145 | + |
| 146 | + # Non-streaming path |
| 147 | + logger.info("Running agent in non-streaming mode") |
| 148 | + non_streaming_converter = AgentFrameworkOutputNonStreamingConverter(context) |
| 149 | + result = await self.agent.run(message) |
| 150 | + logger.debug(f"Agent run completed, result type: {type(result)}") |
| 151 | + transformed_result = non_streaming_converter.transform_output_for_response(result) |
| 152 | + logger.info("Agent run and transformation completed successfully") |
| 153 | + return transformed_result |
0 commit comments