# Microsoft Agent Framework

Microsoft's Agent Framework is an open-source toolkit for building intelligent agents. The framework offers components for creating agents that connect to services, execute tasks, and manage complex workflows. It supports multiple LLM providers including Azure OpenAI and OpenAI, with native OpenTelemetry integration for observability.

This guide covers routing telemetry from Microsoft Agent Framework applications to InteractiveAI for monitoring, debugging, and evaluating agent behavior.

### Prerequisites

* InteractiveAI account with API credentials
* Azure OpenAI credentials or OpenAI API key

***

### Installation

```bash
pip install agent-framework interactiveai
```

***

### Configuration

Set your API credentials as environment variables:

```python
import os

# InteractiveAI credentials
# Obtain keys from Settings > API Keys in the dashboard
os.environ["INTERACTIVEAI_PUBLIC_KEY"] = "pk-ia-..."
os.environ["INTERACTIVEAI_SECRET_KEY"] = "sk-ia-..."
os.environ["INTERACTIVEAI_HOST"] = "https://app.interactiveai.com"

# Azure OpenAI credentials
os.environ["AZURE_OPENAI_API_KEY"] = "your-azure-openai-key"
os.environ["AZURE_OPENAI_ENDPOINT"] = "https://your-resource.openai.azure.com/"
os.environ["AZURE_OPENAI_CHAT_DEPLOYMENT_NAME"] = "gpt-4o-mini"
os.environ["OPENAI_CHAT_MODEL_ID"] = "gpt-4o-mini"
```

Initialize the client and confirm connectivity:

```python
from interactiveai import Interactive

client = Interactive(
    public_key=os.environ["INTERACTIVEAI_PUBLIC_KEY"],
    secret_key=os.environ["INTERACTIVEAI_SECRET_KEY"],
    host=os.environ.get("INTERACTIVEAI_HOST", "https://app.interactiveai.com")
)

if client.auth_check():
    print("Connection established")
else:
    print("Authentication failed - verify credentials")
```

***

### Enabling Trace Capture

The Microsoft Agent Framework includes native OpenTelemetry support. Activate it by calling `configure_otel_providers()` to route traces to InteractiveAI:

```python
from agent_framework.observability import configure_otel_providers

configure_otel_providers(enable_sensitive_data=True)
```

Setting `enable_sensitive_data=True` captures complete request and response payloads including function arguments and return values.

***

### Running an Agent with Azure OpenAI

Here's a working example with a tool-equipped agent using Azure OpenAI:

```python
import asyncio
from random import randint
from typing import Annotated
from agent_framework.azure import AzureOpenAIChatClient
from pydantic import Field

def get_stock_price(
    ticker: Annotated[str, Field(description="The stock ticker symbol to look up.")],
) -> str:
    """Get the current stock price for a given ticker."""
    prices = {"AAPL": 187, "MSFT": 378, "GOOGL": 141}
    price = prices.get(ticker.upper(), randint(50, 500))
    return f"{ticker.upper()} is currently trading at ${price}."

async def main():
    async with AzureOpenAIChatClient().create_agent(
        instructions="You are a helpful financial assistant.",
        tools=get_stock_price,
    ) as agent:
        query = "What's the current price of Microsoft stock?"
        print(f"User: {query}")
        result = await agent.run(query)
        print(f"Agent: {result}\n")

await main()
```

***

### Running an Agent with OpenAI

The framework also supports direct OpenAI access. Use `OpenAIResponsesClient` instead of `AzureOpenAIChatClient`:

```python
import os
from random import randint
from typing import Annotated
from agent_framework.openai import OpenAIResponsesClient
from pydantic import Field

os.environ["OPENAI_API_KEY"] = "sk-proj-..."
os.environ["OPENAI_RESPONSES_MODEL_ID"] = "gpt-4o-mini"

def get_stock_price(
    ticker: Annotated[str, Field(description="The stock ticker symbol to look up.")],
) -> str:
    """Get the current stock price for a given ticker."""
    prices = {"AAPL": 187, "MSFT": 378, "GOOGL": 141}
    price = prices.get(ticker.upper(), randint(50, 500))
    return f"{ticker.upper()} is currently trading at ${price}."

async def main():
    async with OpenAIResponsesClient().create_agent(
        instructions="You are a helpful financial assistant.",
        tools=get_stock_price,
    ) as agent:
        query = "What's the current price of Apple stock?"
        print(f"User: {query}")
        result = await agent.run(query)
        print(f"Agent: {result}\n")

await main()
```

***

### Enriching Traces with Context

Combine the framework's integration with the InteractiveAI SDK to attach identifiers and metadata:

```python
from interactiveai import Interactive
from agent_framework.azure import AzureOpenAIChatClient

client = Interactive(
    public_key=os.environ["INTERACTIVEAI_PUBLIC_KEY"],
    secret_key=os.environ["INTERACTIVEAI_SECRET_KEY"],
    host=os.environ.get("INTERACTIVEAI_HOST", "https://app.interactiveai.com")
)

async def run_with_context():
    with client.start_as_current_span(name="financial-agent-task") as span:
        
        client.update_current_trace(
            user_id="user_123",
            session_id="session_abc",
            tags=["microsoft-agent", "financial"],
            metadata={"department": "trading", "environment": "production"}
        )
        
        async with AzureOpenAIChatClient().create_agent(
            instructions="You are a helpful financial assistant.",
            tools=get_stock_price,
        ) as agent:
            query = "Compare the prices of Apple and Google stock."
            result = await agent.run(query)
            
            client.update_current_trace(
                input=query,
                output=str(result)
            )

    client.flush()

await run_with_context()
```

***

### Trace Visibility

The InteractiveAI dashboard displays:

* Agent execution flow and task completion
* LLM calls with prompts and completions
* Tool invocations with arguments and results
* Token consumption and latency metrics
* Cost tracking per request


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.interactive.ai/integrations/ai-frameworks/microsoft-agent-framework.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
