- Resources
Cookbooks
OCR-RAG Agentic Workflow
OCR-RAG Agentic Workflow
This notebook builds a three-stage agentic workflow using the Microsoft Agent Framework:
Stage | Executor | What it does |
|---|---|---|
| 1 | OcrExecutor | Calls Mistral OCR (hosted in Azure Foundry) to extract Markdown from a PDF |
| 2 | KnowledgeIndexExecutor | Embeds the text with mistral-embed and writes it to Azure AI Search |
| 3 | AnswerExecutor | Performs vector retrieval then uses Mistral to answer the invoice question |
Why a workflow? Each stage has one responsibility. The framework routes state between executors automatically — adding or swapping a stage later requires only a single add_edge() change.
Prerequisites: A .env file and table.png.pdf in this directory.
Dependencies
Key packages:
Package | Role |
|---|---|
| agent-framework-core | Agent, Executor, WorkflowBuilder, handler |
| agent-framework-openai | OpenAIChatCompletionClient (Foundry adapter) |
| agent-framework-azure-ai-search | AzureAISearchContextProvider (vector RAG) |
| agent-framework-mistral | MistralEmbeddingClient (mistral-embed) |
| azure-search-documents | Index management and document upload |
%pip install -U agent-framework-core agent-framework-openai agent-framework-azure-ai-search agent-framework-mistral azure-identity azure-search-documents httpx python-dotenv
Imports
- base64 / httpx — encode the PDF and POST it to the Mistral OCR REST endpoint.
- SearchClient / SearchIndexClient — async Azure Search clients for uploading documents and managing the index schema.
- AzureKeyCredential — authenticates with an API key when provided; falls back to AzureCliCredential (Azure CLI login) when absent.
- Agent Framework primitives — Executor, handler, WorkflowBuilder, WorkflowContext.
import base64
import os
from pathlib import Path
from typing import Any
import httpx
from dotenv import load_dotenv
from azure.identity import AzureCliCredential
from azure.core.credentials import AzureKeyCredential
from azure.search.documents.aio import SearchClient
from azure.search.documents.indexes.aio import SearchIndexClient
from azure.search.documents.indexes.models import (
HnswAlgorithmConfiguration,
SearchField,
SearchFieldDataType,
SearchIndex,
SearchableField,
SimpleField,
VectorSearch,
VectorSearchProfile,
)
from agent_framework import Agent, Executor, WorkflowBuilder, WorkflowContext, handler
from agent_framework.azure import AzureAISearchContextProvider
from agent_framework.mistral import MistralEmbeddingClient
from agent_framework.openai import OpenAIChatCompletionClient
load_dotenv()
Configuration
Variable | Purpose |
|---|---|
| MISTRAL_OCR_ENDPOINT | Azure-hosted Mistral OCR REST endpoint |
| MISTRAL_API_KEY | API key for OCR and embeddings |
| AZURE_AI_PROJECT_ENDPOINT | Foundry project URL for the answering model |
| AZURE_AI_QNA_MODEL | Deployed model name for Q&A |
| AZURE_SEARCH_ENDPOINT | Azure AI Search service URL |
| AZURE_SEARCH_INDEX_NAME | Index to create or reuse |
| AZURE_SEARCH_API_KEY | Optional — absent → CLI credentials used |
| AZURE_SEARCH_SEMANTIC_CONFIG | Optional semantic ranker config name |
VECTOR_DIMENSIONS = 1024 matches the output size of mistral-embed.
PDF_PATH = Path("table.png.pdf")
OCR_MODEL = os.getenv("AZURE_AI_OCR_NAME")
MISTRAL_OCR_ENDPOINT = os.environ["MISTRAL_OCR_ENDPOINT"].rstrip("/")
MISTRAL_OCR_KEY = os.environ["MISTRAL_API_KEY"]
FOUNDRY_ENDPOINT = os.environ["AZURE_AI_PROJECT_ENDPOINT"]
ANSWER_MODEL = os.getenv("AZURE_AI_QNA_MODEL")
SEARCH_ENDPOINT = os.environ["AZURE_SEARCH_ENDPOINT"]
SEARCH_INDEX_NAME = os.getenv("AZURE_SEARCH_INDEX_NAME")
SEARCH_API_KEY = os.getenv("AZURE_SEARCH_API_KEY")
SEARCH_SEMANTIC_CONFIG = os.getenv("AZURE_SEARCH_SEMANTIC_CONFIG")
QUERY = "what's the sum of unpaid balance in the invoice"
VECTOR_DIMENSIONS = 1024 # mistral-embed
if not PDF_PATH.exists():
raise FileNotFoundError(f"Expected local input PDF at {PDF_PATH.resolve()}")
credential = AzureCliCredential() if not SEARCH_API_KEY else None
print(f"Input: {PDF_PATH}")
print(f"OCR model: {OCR_MODEL}")
print(f"Answer model: {ANSWER_MODEL}")
print(f"Search index: {SEARCH_INDEX_NAME}")
Stage 1 — OCR Executor
Mistral OCR accepts a base64-encoded data URL, so the PDF never needs to be uploaded to a separate public location.
- mistral_ocr_url — normalises the endpoint URL; the Foundry deployment may or may not include the /ocr suffix.
- run_mistral_ocr — encodes the PDF, POSTs it to the endpoint, and joins per-page Markdown into a single string.
- OcrExecutor — the @handler method stores ocr_text in workflow state and calls ctx.send_message(state) to hand control to the next stage.
def mistral_ocr_url(endpoint: str) -> str:
if endpoint.endswith("/ocr"):
return endpoint
return f"{endpoint}/providers/mistral/azure/ocr"
async def run_mistral_ocr(pdf_path: Path) -> str:
encoded_pdf = base64.b64encode(pdf_path.read_bytes()).decode("ascii")
payload = {
"model": OCR_MODEL,
"document": {
"type": "document_url",
"document_url": f"data:application/pdf;base64,{encoded_pdf}",
},
}
headers = {"api-key": MISTRAL_OCR_KEY, "content-type": "application/json"}
async with httpx.AsyncClient(timeout=300) as client:
response = await client.post(mistral_ocr_url(MISTRAL_OCR_ENDPOINT), headers=headers, json=payload)
response.raise_for_status()
result = response.json()
pages = result.get("pages", [])
text = "\n\n".join(page.get("markdown", "") for page in pages).strip()
if not text:
raise ValueError(f"Mistral OCR returned no page Markdown: {result}")
return text
class OcrExecutor(Executor):
def __init__(self) -> None:
super().__init__(id="mistral_ocr")
@handler
async def convert(self, state: dict[str, Any], ctx: WorkflowContext) -> None:
state["ocr_text"] = await run_mistral_ocr(Path(state["pdf_path"]))
await ctx.send_message(state)
Stage 2 — Knowledge Index Executor
Azure AI Search stores the embedded OCR text as a searchable vector document. The index is created on first run and reused on subsequent runs.
- build_search_index — defines the schema: a key field, a full-text content field, and a 1024-d contentVector HNSW field.
- get_embedding_client — reuses the Mistral API key for mistral-embed.
- index_ocr_text — embeds the text, creates the index if absent, and uploads one document. The fixed ID invoice-doc-1 means re-runs overwrite rather than duplicate.
def build_search_index() -> SearchIndex:
fields = [
SimpleField(name="id", type=SearchFieldDataType.String, key=True),
SearchableField(name="source", type=SearchFieldDataType.String),
SearchableField(name="content", type=SearchFieldDataType.String),
SearchField(
name="contentVector",
type=SearchFieldDataType.Collection(SearchFieldDataType.Single),
searchable=True,
vector_search_dimensions=VECTOR_DIMENSIONS,
vector_search_profile_name="invoice-vector-profile",
),
]
return SearchIndex(
name=SEARCH_INDEX_NAME,
fields=fields,
vector_search=VectorSearch(
algorithms=[HnswAlgorithmConfiguration(name="invoice-hnsw")],
profiles=[VectorSearchProfile(name="invoice-vector-profile", algorithm_configuration_name="invoice-hnsw")],
),
)
async def get_embedding_client() -> MistralEmbeddingClient:
return MistralEmbeddingClient(
model=os.getenv("AZURE_MISTRAL_EMBEDDING_MODEL", "mistral-embed"),
api_key=MISTRAL_OCR_KEY,
server_url=MISTRAL_OCR_ENDPOINT,
)
async def index_ocr_text(text: str) -> None:
embedding_client = await get_embedding_client()
try:
embedding_result = await embedding_client.get_embeddings([text])
vector = embedding_result[0].vector
finally:
await embedding_client.close()
cred = AzureKeyCredential(SEARCH_API_KEY) if SEARCH_API_KEY else AzureCliCredential()
async with SearchIndexClient(endpoint=SEARCH_ENDPOINT, credential=cred) as idx_client:
existing = {idx.name async for idx in idx_client.list_indexes()}
if SEARCH_INDEX_NAME not in existing:
await idx_client.create_index(build_search_index())
async with SearchClient(endpoint=SEARCH_ENDPOINT, index_name=SEARCH_INDEX_NAME, credential=cred) as sc:
await sc.upload_documents([{
"id": "invoice-doc-1",
"source": str(PDF_PATH),
"content": text,
"contentVector": vector,
}])
KnowledgeIndexExecutor is a thin executor wrapper: it delegates all index work to index_ocr_text and calls ctx.send_message(state) to advance the workflow to the answer stage.
class KnowledgeIndexExecutor(Executor):
def __init__(self) -> None:
super().__init__(id="foundry_knowledge_index")
@handler
async def write(self, state: dict[str, Any], ctx: WorkflowContext) -> None:
await index_ocr_text(state["ocr_text"])
await ctx.send_message(state)
Stage 3 — Retrieval-Augmented Answer Executor
- AzureAISearchContextProvider — performs a vector similarity search before each LLM call and injects the top-3 passages as grounding context.
- OpenAIChatCompletionClient — connects to the Foundry endpoint with AzureCliCredential.
- The agent's instructions constrain it to answer from retrieved context only and to show line-item arithmetic — important for verifiable invoice sums.
The monkey-patch at the top of this cell strips the name field from assistant messages, which Mistral endpoints reject.
# Mistral endpoints reject the `name` field on assistant messages.
from agent_framework_openai._chat_completion_client import RawOpenAIChatCompletionClient
_original_prepare = RawOpenAIChatCompletionClient._prepare_message_for_openai
def _prepare_without_assistant_name(self, message):
messages = _original_prepare(self, message)
for item in messages:
if item.get("role") == "assistant":
item.pop("name", None)
return messages
RawOpenAIChatCompletionClient._prepare_message_for_openai = _prepare_without_assistant_name
async def build_invoice_agent() -> Agent:
embedding_client = await get_embedding_client()
provider_kwargs = {
"source_id": "invoice_knowledge_index",
"endpoint": SEARCH_ENDPOINT,
"index_name": SEARCH_INDEX_NAME,
"mode": "semantic",
"top_k": 3,
"vector_field_name": "contentVector",
"embedding_function": embedding_client,
}
if SEARCH_API_KEY:
provider_kwargs["api_key"] = SEARCH_API_KEY
else:
provider_kwargs["credential"] = AzureCliCredential()
if SEARCH_SEMANTIC_CONFIG:
provider_kwargs["semantic_configuration_name"] = SEARCH_SEMANTIC_CONFIG
search_provider = AzureAISearchContextProvider(**provider_kwargs)
client = OpenAIChatCompletionClient(
azure_endpoint=FOUNDRY_ENDPOINT,
model=ANSWER_MODEL,
credential=AzureCliCredential(),
)
return Agent(
client=client,
name="InvoiceRagAgent",
instructions=(
"Answer only from the retrieved invoice context. "
"Calculate the sum of unpaid balances carefully, state the currency, "
"and show the line-item arithmetic. If the context is insufficient, say so."
),
context_providers=[search_provider],
)
class AnswerExecutor(Executor):
def __init__(self) -> None:
super().__init__(id="mistral_medium_answer")
@handler
async def answer(self, state: dict[str, Any], ctx: WorkflowContext) -> None:
agent = await build_invoice_agent()
try:
result = await agent.run(state["query"])
state["answer"] = result.text
finally:
await agent.client.close()
await ctx.yield_output(state)
Run the Workflow
Wire the three executors into a linear pipeline and execute:
OcrExecutor → KnowledgeIndexExecutor → AnswerExecutor
The initial state carries pdf_path (for the OCR stage) and query (for the answer stage). events.get_outputs() collects every value emitted by ctx.yield_output() — here, the single invoice answer.
ocr = OcrExecutor()
indexer = KnowledgeIndexExecutor()
answerer = AnswerExecutor()
workflow = (
WorkflowBuilder(start_executor=ocr)
.add_edge(ocr, indexer)
.add_edge(indexer, answerer)
.build()
)
events = await workflow.run({"pdf_path": str(PDF_PATH), "query": QUERY})
for output in events.get_outputs():
print(output["answer"])