Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions samples/microsoft_agent_framework/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
FOUNDRY_PROJECT_ENDPOINT= "..."
FOUNDRY_MODEL="..."
APPLICATIONINSIGHTS_CONNECTION_STRING="..."
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
63 changes: 63 additions & 0 deletions samples/microsoft_agent_framework/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# Microsoft Agent Framework Sample

This sample demonstrates how to use [Agent Framework](https://aka.ms/agent-framework) to create a simple agent using Foundry model services and export OpenTelemetry traces using the Microsoft OpenTelemetry SDK to Azure Monitor (Application Insights) or a local OpenTelemetry Collector.

Learn more about the Microsoft Agent Framework in our [GitHub repository](https://github.com/microsoft/agent-framework).

## Prerequisites

- Python 3.10+
- A [Foundry project](https://learn.microsoft.com/en-us/azure/foundry/tutorials/quickstart-create-foundry-resources?tabs=portal) endpoint and model
- (Optional) An [Application Insights](https://learn.microsoft.com/en-us/azure/azure-monitor/app/create-workspace-resource?tabs=portal) resource (for the connection string)
- (Optional) An [Aspire Dashboard](https://aspire.dev/dashboard/overview/#standalone-mode) to visualize traces (if you want to use a local OpenTelemetry Collector)

## Environment setup

1. Create and activate a virtual environment using [uv](https://docs.astral.sh/uv/) (recommended):

```bash
uv venv .venv
```

```bash
# Windows (PowerShell)
.venv\Scripts\Activate.ps1

# Windows (Command Prompt)
.venv\Scripts\activate.bat

# macOS/Linux
source .venv/bin/activate
```

> **Note:** `python -m venv .venv` also works, but can hang indefinitely on Windows with Microsoft Store Python due to a known `ensurepip` issue. Use `uv venv .venv` to avoid this.

2. Install dependencies:

```bash
uv pip install -r requirements.txt
```

3. Create a `.env` file with your Foundry configuration following the `env.example` file in the sample.

4. Make sure you are logged in with the Azure CLI:

```bash
az login
```

## Azure Monitor

Create an Application Insights resource in the Azure portal and copy the connection string to your `.env` file. If you don't have an Application Insights resource, you can skip this step, but you won't be able to see traces in Azure Monitor.

## OTel Exporter

You can also configure the OTLP exporter endpoint to send traces to a local OpenTelemetry Collector by setting the `OTEL_EXPORTER_OTLP_ENDPOINT` environment variable in your `.env` file.

## Run the sample

Microsoft Agent Framework is natively instrumented with OpenTelemetry, so you can run the sample directly:

```bash
python sample_maf_agent.py
```
3 changes: 3 additions & 0 deletions samples/microsoft_agent_framework/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
agent-framework-core
Comment thread
TaoChenOSU marked this conversation as resolved.
agent-framework-foundry
microsoft-opentelemetry
63 changes: 63 additions & 0 deletions samples/microsoft_agent_framework/sample_maf_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# Copyright (c) Microsoft. All rights reserved.

import asyncio
from random import randint
from typing import Annotated

from agent_framework import Agent, tool
from agent_framework.foundry import FoundryChatClient
from agent_framework.observability import get_tracer
from azure.identity import AzureCliCredential
from dotenv import load_dotenv
from microsoft.opentelemetry import use_microsoft_opentelemetry
from opentelemetry.trace import SpanKind
from opentelemetry.trace.span import format_trace_id
from pydantic import Field

# Load environment variables from .env file
load_dotenv()


@tool(approval_mode="never_require")
async def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
"""Get the weather for a given location."""
await asyncio.sleep(randint(0, 10) / 10.0) # Simulate a network call
conditions = ["sunny", "cloudy", "rainy", "stormy"]
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."


async def main():
# Set up Azure monitor exporters for telemetry
# This will automatically enable instrumentation for Agent Framework
use_microsoft_opentelemetry(enable_azure_monitor=True)

questions = [
"What's the weather in Amsterdam?",
"and in Paris, and which is better?",
"Why is the sky blue?",
]

with get_tracer().start_as_current_span("Scenario: Agent Chat", kind=SpanKind.CLIENT) as current_span:
print(f"Trace ID: {format_trace_id(current_span.get_span_context().trace_id)}")

agent = Agent(
client=FoundryChatClient(credential=AzureCliCredential()),
tools=get_weather,
name="WeatherAgent",
instructions="You are a weather assistant.",
id="weather-agent",
)

session = agent.create_session()
for question in questions:
print(f"\nUser: {question}")
print(f"{agent.name}: ", end="")
async for update in agent.run(question, session=session, stream=True):
if update.text:
print(update.text, end="")


if __name__ == "__main__":
asyncio.run(main())
Loading