mistralM

Docs

sideBar

Microsoft Agent Framework Demo

Hands-on notebooks and guides for building with the Mistral API.

Microsoft Agent Framework Demo

This notebook introduces the Microsoft Agent Framework using Mistral Large 3 hosted in Azure AI Foundry. It walks through six progressively richer patterns:

Section

What you learn

1. Basic agentSend a prompt, receive a reply — non-streaming and streaming
2. ToolsGive the agent a Python function it can call during reasoning
3. MCP toolsAttach a remote Model Context Protocol server hosted in Foundry
4. Multi-turn sessionsMaintain conversation history across multiple turns
5. Memory / context providersPersist user information between calls
6. WorkflowsChain executors into a multi-step processing pipeline

Prerequisites: A .env file in this directory with AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_DEPLOYMENT_NAME set.

Setup — Imports

All Agent Framework primitives come from the agent_framework namespace. OpenAIChatCompletionClient (from agent_framework.openai) connects to any OpenAI-compatible endpoint, including Azure AI Foundry.

The cell applies a one-time monkey-patch to strip the name field from assistant messages before they are sent — Mistral endpoints reject that field. A guard flag prevents double-patching if the cell is re-run.

import os
from dotenv import load_dotenv
from typing import Annotated, Any
from random import randint
from pydantic import Field
from agent_framework.openai import OpenAIChatCompletionClient
from agent_framework import Agent, tool, ContextProvider, AgentSession, SessionContext, Executor, WorkflowBuilder, AgentResponseUpdate, WorkflowContext, executor, handler

from typing_extensions import Never

from azure.identity import AzureCliCredential

# Mistral endpoints reject the `name` field on assistant messages.
# Patch the framework to strip it before sending.
# Guard prevents double-patching if this cell is re-run.
from agent_framework_openai._chat_completion_client import RawOpenAIChatCompletionClient

if not getattr(RawOpenAIChatCompletionClient, "_name_patch_applied", False):
    _orig_prepare = RawOpenAIChatCompletionClient._prepare_message_for_openai

    def _prepare_without_assistant_name(self, message):
        msgs = _orig_prepare(self, message)
        for msg in msgs:
            if msg.get("role") == "assistant":
                msg.pop("name", None)
        return msgs

    RawOpenAIChatCompletionClient._prepare_message_for_openai = _prepare_without_assistant_name
    RawOpenAIChatCompletionClient._name_patch_applied = True

Configuration

Load credentials from .env. AZURE_AI_PROJECT_ENDPOINT is your Foundry project URL; AZURE_AI_DEPLOYMENT_NAME is the name of the deployed Mistral model (e.g. mistral-large-2411).

load_dotenv()

AZURE_AI_PROJECT_ENDPOINT = os.getenv("AZURE_AI_PROJECT_ENDPOINT")
AZURE_AI_DEPLOYMENT_NAME = os.getenv("AZURE_AI_DEPLOYMENT_NAME")

print(f"AZURE_AI_PROJECT_ENDPOINT: {AZURE_AI_PROJECT_ENDPOINT}")
print(f"AZURE_AI_DEPLOYMENT_NAME: {AZURE_AI_DEPLOYMENT_NAME}")

1. Basic Agent

OpenAIChatCompletionClient wraps the Foundry endpoint. Passing it to Agent adds instruction handling, tool routing, session management, and context-provider support on top.

client = OpenAIChatCompletionClient(
    azure_endpoint=AZURE_AI_PROJECT_ENDPOINT,
    model=AZURE_AI_DEPLOYMENT_NAME,
    credential=AzureCliCredential(),
)

agent = Agent(
    client=client,
    name="MistralAgent",
    instructions="You are a friendly assistant. Keep your answers brief.",
)

Non-streaming call

agent.run() sends the prompt and blocks until the full response arrives. The returned object exposes .text and the raw message history.

# Non-streaming: get the complete response at once
result = await agent.run("What is the capital of France?")
print(f"Agent: {result}")

Streaming call

Pass stream=True to receive an async generator of AgentResponseUpdate chunks. Print each chunk's .text as it arrives to display tokens progressively.

# Streaming: receive tokens as they are generated
print("Agent (streaming): ", end="", flush=True)
async for chunk in agent.run("Tell me a one-sentence fun fact.", stream=True):
    if chunk.text:
        print(chunk.text, end="", flush=True)
print()

2. Tools

Tools let the agent call Python functions during reasoning. The LLM decides when to invoke them and what arguments to pass, based on the function's docstring and parameter annotations.

Decorate a function with @tool to register it. approval_mode="never_require" means the framework calls it automatically without pausing for user confirmation.

@tool(approval_mode="never_require")
def get_weather(
    location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
    """Get the weather for a given location."""
    print(f"[DEBUG] get_weather called with location={location!r}")
    conditions = ["sunny", "cloudy", "rainy", "stormy"]
    return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."

Attach the tool to a new Agent via the tools list. The framework converts the decorated function into a JSON schema that the model inspects to decide when and how to call it.

weatherAgent = Agent(
    client=client,
    name="WeatherAgent",
    instructions="You are a helpful weather agent. Use the get_weather tool to answer questions.",
    tools=[get_weather],
)

Run the weather agent with a location question. The model calls get_weather autonomously, then incorporates the returned string into its natural-language reply.

result =  await weatherAgent.run("What's the weather like in Seattle, call the get_weather tool?")
print(f"Weather Agent: {result}")

3. MCP Tools (Model Context Protocol)

MCP is an open standard that lets agents call tools hosted on a remote server over HTTP rather than executing local Python functions. Azure AI Foundry can host MCP servers that expose APIs, databases, or any capability you choose.

See the full guide: Azure Foundry MCP tools

Attach an MCPTool to a PromptAgentDefinition (shown in Foundry_Agent_Tool_Calling.ipynb). No additional code cell is included here — the pattern is demonstrated in the companion notebook.

4. Multi-Turn Conversations

By default agent.run() is stateless — each call starts a fresh context. A Session carries the message history across calls so the model can refer to earlier turns without you manually managing the prompt array.

Create a fresh Agent for the conversation demo. The same client can be shared across multiple agents safely.


agent = Agent(
    client=client,
    name="ConversationAgent",
    instructions="You are a friendly assistant. Keep your answers brief.",
)

Multi-turn example

agent.create_session() returns a Session object that accumulates message history server-side. Pass the same session to consecutive run() calls so the model remembers earlier turns.

# Create a session to maintain conversation history
session = agent.create_session()

# First turn
result = await agent.run("My name is Alice and I love hiking.", session=session)
print(f"Agent: {result}\n")

# Second turn — the agent should remember the user's name and hobby
result = await agent.run("What do you remember about me?", session=session)
print(f"Agent: {result}")

5. Memory & Context Providers

A ContextProvider injects dynamic content into the system prompt before each LLM call and can inspect the conversation after each response. This is the primary extension point for memory, RAG retrieval, or per-turn personalisation.

ContextProvider has two hooks:

  • before_run — inject instructions based on stored state.
  • after_run — extract information from the user's message and persist it.

The example below asks for the user's name on the first turn and addresses them by name on every subsequent turn.

Implementing UserMemoryProvider

Subclass ContextProvider and override before_run and after_run:

  • before_run: reads user_name from session state. If found, tells the model to use the name; otherwise asks for it.
  • after_run: scans input messages for the phrase "my name is" and stores the extracted name in state for future turns.
class UserMemoryProvider(ContextProvider):
    """A context provider that remembers user info in session state."""

    DEFAULT_SOURCE_ID = "user_memory"

    def __init__(self):
        super().__init__(self.DEFAULT_SOURCE_ID)

    async def before_run(
        self,
        *,
        agent: Any,
        session: AgentSession | None,
        context: SessionContext,
        state: dict[str, Any],
    ) -> None:
        """Inject personalization instructions based on stored user info."""
        user_name = state.get("user_name")
        if user_name:
            context.extend_instructions(
                self.source_id,
                f"The user's name is {user_name}. Always address them by name.",
            )
        else:
            context.extend_instructions(
                self.source_id,
                "You don't know the user's name yet. Ask for it politely.",
            )

    async def after_run(
        self,
        *,
        agent: Any,
        session: AgentSession | None,
        context: SessionContext,
        state: dict[str, Any],
    ) -> None:
        """Extract and store user info in session state after each call."""
        for msg in context.input_messages:
            text = msg.text if hasattr(msg, "text") else ""
            if isinstance(text, str) and "my name is" in text.lower():
                state["user_name"] = text.lower().split("my name is")[-1].strip().split()[0].capitalize()

Attach UserMemoryProvider to the agent. Multiple providers can be stacked — each injects its own system-prompt fragment before every LLM call.

agent = Agent(
    client=client,
    name="MemoryAgent",
    instructions="You are a friendly assistant.",
    context_providers=[UserMemoryProvider()],
)

The first turn: the provider doesn't know the user's name yet, so it asks. After the second message ("My name is Alice"), the name is stored in state and the model uses it from the third turn onward.

session = agent.create_session()

# The provider doesn't know the user yet — it will ask for a name
result = await agent.run("Hello! What's the square root of 9?", session=session)
print(f"Agent: {result}\n")

# Now provide the name — the provider stores it in session state
result = await agent.run("My name is Alice", session=session)
print(f"Agent: {result}\n")

# Subsequent calls are personalized — name persists via session state
result = await agent.run("What is 2 + 2?", session=session)
print(f"Agent: {result}\n")

# Inspect session state to see what the provider stored
provider_state = session.state.get("user_memory", {})
print(f"[Session State] Stored user name: {provider_state.get('user_name')}")

6. Workflows

A workflow chains executors into a directed acyclic graph. Each executor receives the output of the previous one, transforms it, and forwards the result. Workflows are useful for multi-step pipelines where each stage has a clear, single responsibility.

The example below builds a two-step pipeline: UpperCase → reverse_text.

Executor styles:

  • Class-based (class Foo(Executor)) — useful when the executor needs constructor arguments or state.
  • Function-based (@executor decorator) — concise for stateless steps.

Each executor calls ctx.send_message() to forward data, or ctx.yield_output() to mark the final result.

Define the two pipeline stages. UpperCase is a class-based executor (useful when constructor args are needed). reverse_text uses the @executor function decorator — a concise alternative for stateless steps. ctx.yield_output() marks the terminal result.


# Step 1: A class-based executor that converts text to uppercase
class UpperCase(Executor):
    def __init__(self, id: str):
        super().__init__(id=id)

    @handler
    async def to_upper_case(self, text: str, ctx: WorkflowContext[str]) -> None:
        """Convert input to uppercase and forward to the next node."""
        await ctx.send_message(text.upper())


# Step 2: A function-based executor that reverses the string and yields output
@executor(id="reverse_text")
async def reverse_text(text: str, ctx: WorkflowContext[Never, str]) -> None:
    """Reverse the string and yield the final workflow output."""
    await ctx.yield_output(text[::-1])


def create_workflow():
    """Build the workflow: UpperCase → reverse_text."""
    upper = UpperCase(id="upper_case")
    return WorkflowBuilder(start_executor=upper).add_edge(upper, reverse_text).build()

Wire the executors into a pipeline with WorkflowBuilder, then run it. events.get_outputs() collects every value emitted by yield_output(). The input "hello world" becomes "DLROW OLLEH" after uppercasing and reversal.

workflow = create_workflow()

events = await workflow.run("hello world")
print(f"Output: {events.get_outputs()}")
print(f"Final state: {events.get_final_state()}")