Skip to content

Commit 9dd8323

Browse files
authored
Merge pull request #7 from pamelafox/context-examples
Add context/memory examples and migrate to latest agent-framework API
2 parents af44c28 + 526b932 commit 9dd8323

File tree

81 files changed

+11111
-532
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

81 files changed

+11111
-532
lines changed

.devcontainer/Dockerfile

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
FROM mcr.microsoft.com/devcontainers/python:3.12-bookworm
22

3+
# Required for cloning agent-framework from GitHub (it uses Git LFS)
4+
RUN apt-get update && apt-get install -y git-lfs && git lfs install && rm -rf /var/lib/apt/lists/*
5+
36
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /usr/local/bin/
47

58
COPY pyproject.toml uv.lock /tmp/uv-tmp/

.devcontainer/devcontainer.json

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@
22
"name": "python-agentframework-demos",
33
"dockerComposeFile": "docker-compose.yml",
44
"service": "app",
5-
"workspaceFolder": "/workspaces/python-agentframework-demos",
5+
"workspaceFolder": "/workspace",
6+
"forwardPorts": [5432, 6379, 18888],
67
"features": {
7-
"ghcr.io/azure/azure-dev/azd:latest": {}
8+
"ghcr.io/azure/azure-dev/azd:latest": {},
9+
"ghcr.io/devcontainers/features/azure-cli:latest": {},
10+
"ghcr.io/devcontainers/features/github-cli:1": {}
811
},
912
"customizations": {
1013
"vscode": {

.devcontainer/docker-compose.yml

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,38 @@ services:
44
context: ..
55
dockerfile: .devcontainer/Dockerfile
66
volumes:
7-
- ..:/workspaces/python-agentframework-demos:cached
7+
- ..:/workspace:cached
88
command: sleep infinity
99
environment:
1010
- OTEL_EXPORTER_OTLP_ENDPOINT=http://aspire-dashboard:18889
11+
- OTEL_EXPORTER_OTLP_PROTOCOL=grpc
12+
- REDIS_URL=redis://redis:6379
13+
- POSTGRES_URL=postgresql://admin:LocalPasswordOnly@db:5432/postgres
14+
15+
db:
16+
image: pgvector/pgvector:pg17
17+
restart: unless-stopped
18+
volumes:
19+
- postgres-data:/var/lib/postgresql/data
20+
environment:
21+
POSTGRES_DB: postgres
22+
POSTGRES_USER: admin
23+
POSTGRES_PASSWORD: LocalPasswordOnly
24+
ports:
25+
- "5433:5432"
26+
27+
redis:
28+
image: redis/redis-stack-server:latest
29+
restart: unless-stopped
30+
ports:
31+
- '6380:6379'
1132

1233
aspire-dashboard:
1334
image: mcr.microsoft.com/dotnet/aspire-dashboard:latest
1435
ports:
1536
- "18888:18888"
1637
environment:
1738
- DASHBOARD__FRONTEND__AUTHMODE=Unsecured
39+
40+
volumes:
41+
postgres-data:

.env.sample

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,16 @@ OPENAI_MODEL=gpt-3.5-turbo
99
# Configure for GitHub models: (GITHUB_TOKEN already exists inside Codespaces)
1010
GITHUB_MODEL=gpt-5-mini
1111
GITHUB_TOKEN=YOUR-GITHUB-PERSONAL-ACCESS-TOKEN
12+
# Configure for Redis (used by agent_history_redis.py, defaults to dev container Redis):
13+
REDIS_URL=redis://localhost:6379
1214
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
15+
OTEL_EXPORTER_OTLP_PROTOCOL=grpc
16+
# Or use console exporters instead of OTLP:
17+
# ENABLE_CONSOLE_EXPORTERS=true
1318
# Optional: Set to export telemetry to Azure Application Insights
1419
APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=YOUR-KEY;IngestionEndpoint=https://YOUR-REGION.in.applicationinsights.azure.com/
20+
# Configure for Azure AI Search (used by agent_knowledge_aisearch.py):
21+
AZURE_SEARCH_ENDPOINT=https://YOUR-SEARCH-SERVICE.search.windows.net
22+
AZURE_SEARCH_KNOWLEDGE_BASE_NAME=YOUR-KB-NAME
1523
# Optional: Set to log evaluation results to Azure AI Foundry for rich visualization
1624
AZURE_AI_PROJECT=https://YOUR-ACCOUNT.services.ai.azure.com/api/projects/YOUR-PROJECT
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
name: review_slides
3+
description: Use this to review slides for accuracy
4+
---
5+
Review the given slides for consistency with the code samples in the repository.
6+
7+
Use the markitdown skill to convert the PDF to markdown first.
8+
9+
Point out any errors, inconsistencies, or areas that may need clarification. Provide specific feedback on how to improve the slides to better align with the code and concepts presented in the repository.
10+
Make sure all URLs/filenames are valid.
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
name: update_translations
3+
description: Use this prompt to update the Spanish translations in the repo.
4+
model: GPT-5.2 (copilot)
5+
---
6+
7+
Update the Spanish translations in the repo according to the guidelines in AGENTS.md. Ensure there are spanish equivalents of each english example. Make sure to keep the translations consistent with the original content and maintain the technical accuracy of the code.
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
---
2+
name: pdf-to-markdown
3+
description: Converts PDF files to Markdown using Microsoft's markitdown package. Use this skill when the user asks to convert a PDF to Markdown, extract text from a PDF, or read/parse PDF content.
4+
argument-hint: "[path to file]"
5+
---
6+
7+
# PDF to Markdown Conversion
8+
9+
This skill converts PDF files to Markdown format using [Microsoft's markitdown](https://github.com/microsoft/markitdown) package.
10+
11+
## When to use
12+
13+
- User asks to convert a PDF to Markdown
14+
- User wants to extract text content from a PDF
15+
- User needs to read or parse a PDF document
16+
- User asks to summarize or analyze a PDF file
17+
18+
## How to use
19+
20+
Use `uvx` to run markitdown directly. Pick the dependency group matching the file type:
21+
22+
| File type | Dependency group |
23+
|-----------|-----------------|
24+
| PDF | `pdf` |
25+
| PowerPoint | `pptx` |
26+
| Word | `docx` |
27+
| Excel (.xlsx) | `xlsx` |
28+
| Excel (.xls) | `xls` |
29+
30+
```bash
31+
uvx 'markitdown[pdf]' <path-to-file> -o output.md
32+
```
33+
34+
Or install all optional dependencies at once:
35+
36+
```bash
37+
uvx 'markitdown[all]' <path-to-file> -o output.md
38+
```
39+
40+
## Examples
41+
42+
```bash
43+
uvx 'markitdown[pdf]' report.pdf -o report.md
44+
uvx 'markitdown[pptx]' slides.pptx -o slides.md
45+
uvx 'markitdown[docx]' document.docx -o document.md
46+
```
47+
48+
## Output
49+
50+
- If you were asked to save the output to a specific file, save it to the requested file using `-o`.
51+
- If no output file was specified, use the source filename with a `.md` suffix.

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,3 +147,8 @@ node_modules
147147
static/
148148

149149
.DS_Store
150+
*.sqlite3
151+
152+
# Red team scan results (may contain sensitive/graphic content)
153+
redteam_results.json/
154+
.scan_*/

AGENTS.md

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
# Instructions for coding agents
2+
3+
This repository contains many examples of using the Microsoft Agent Framework in Python (agent-framework), sometimes abbreviated as MAF.
4+
5+
The agent-framework GitHub repo is here:
6+
https://github.com/microsoft/agent-framework
7+
It contains both Python and .NET agent framework code, but we are only using the Python packages in this repo.
8+
9+
MAF is changing rapidly still, so we sometimes need to check the repo changelog and issues to see if there are any breaking changes that might affect our code.
10+
The Python changelog is here:
11+
https://github.com/microsoft/agent-framework/blob/main/python/CHANGELOG.md
12+
13+
MAF documentation is available on Microsoft Learn here:
14+
https://learn.microsoft.com/agent-framework/
15+
When available, the MS Learn MCP server can be used to explore the documentation, ask questions, and get code examples.
16+
17+
## Package management
18+
19+
This project uses [uv](https://docs.astral.sh/uv/) for dependency management. Use `uv` commands instead of `pip`:
20+
21+
```bash
22+
uv add <package>
23+
uv sync
24+
```
25+
26+
## Spanish translations
27+
28+
There are Spanish equivalents of each example in /examples/spanish.
29+
30+
Each example .py file should have a corresponding file with the same name under /examples/spanish/ that is the translation of the original, but with the same code. Here's a guide on what should be translated vs. what should be left in English:
31+
32+
* Comments: Spanish
33+
* Docstrings: Spanish
34+
* System prompts (agent instructions): Spanish
35+
* Tool descriptions (metadata like description=): English
36+
* Parameter descriptions (Field(description=...)): English
37+
* Identifiers (functions/classes/vars): English
38+
* User-facing output/data (e.g., example responses, sample values): Spanish
39+
* HITL control words: bilingual (approve/aprobar, exit/salir)
40+
41+
Use informal (tuteo) LATAM Spanish, tu not usted, puedes not podes, etc. The content is technical so if a word is best kept in English, then do so.
42+
43+
The /examples/spanish/README.md corresponds to the root README.md and should be kept in sync with it, but translated to Spanish.
44+
45+
## Debugging Azure Python SDK HTTP requests
46+
47+
When debugging HTTP interactions between Azure Python SDKs (like `azure-ai-evaluation`) and Azure services, there are three levels of logging you can enable:
48+
49+
### 1. Azure SDK logger (request headers and URLs)
50+
51+
Set the Azure SDK loggers to DEBUG level to see request URLs, headers, and status codes:
52+
53+
```python
54+
import logging
55+
56+
logging.basicConfig(level=logging.WARNING)
57+
logging.getLogger("azure").setLevel(logging.DEBUG)
58+
logging.getLogger("azure.core.pipeline.policies.http_logging_policy").setLevel(logging.DEBUG)
59+
```
60+
61+
### 2. Raw HTTP wire data (request/response headers)
62+
63+
Enable `http.client` debug logging to see the raw HTTP wire protocol, including request and response headers:
64+
65+
```python
66+
import http.client
67+
http.client.HTTPConnection.debuglevel = 1
68+
```
69+
70+
Note: Response bodies will typically not be visible at this level because Azure SDKs use gzip compression, and `http.client` logs the raw compressed bytes.
71+
72+
### 3. Decompressed response bodies
73+
74+
To see actual response bodies, monkey-patch the Azure SDK's `HttpLoggingPolicy.on_response` method. This works because `response.http_response.body()` returns the decompressed content:
75+
76+
```python
77+
from azure.core.pipeline.policies import HttpLoggingPolicy
78+
79+
_original_on_response = HttpLoggingPolicy.on_response
80+
81+
def _on_response_with_body(self, request, response):
82+
_original_on_response(self, request, response)
83+
try:
84+
body = response.http_response.body()
85+
if body:
86+
_logger = logging.getLogger("azure.core.pipeline.policies.http_logging_policy")
87+
_logger.debug("Response body: %s", body[:4096].decode("utf-8", errors="replace"))
88+
except Exception:
89+
pass
90+
91+
HttpLoggingPolicy.on_response = _on_response_with_body
92+
```

README.md

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ A related option is VS Code Dev Containers, which will open the project in your
5858
3. In the VS Code window that opens, once the project files show up (this may take several minutes), open a terminal window.
5959
4. Continue with the steps to run the examples
6060

61+
The dev container includes a Redis server, which is used by the `agent_history_redis.py` example.
62+
6163
### Local environment
6264

6365
1. Make sure the following tools are installed:
@@ -79,6 +81,18 @@ A related option is VS Code Dev Containers, which will open the project in your
7981
uv sync
8082
```
8183

84+
4. *Optional:* To run the `agent_history_redis.py` example, you need a Redis server running locally:
85+
86+
```shell
87+
docker run -d -p 6379:6379 redis:7-alpine
88+
```
89+
90+
5. *Optional:* To run the PostgreSQL examples (`agent_knowledge_postgres.py`, `agent_knowledge_pg.py`, `agent_knowledge_pg_rewrite.py`), you need PostgreSQL with pgvector running locally:
91+
92+
```shell
93+
docker run -d -p 5432:5432 -e POSTGRES_USER=admin -e POSTGRES_PASSWORD=LocalPasswordOnly pgvector/pgvector:pg17
94+
```
95+
8296
## Configuring model providers
8397

8498
These examples can be run with Azure AI Foundry, OpenAI.com, or GitHub Models, depending on the environment variables you set. All the scripts reference the environment variables from a `.env` file, and an example `.env.sample` file is provided. Host-specific instructions are below.
@@ -125,6 +139,12 @@ This project includes infrastructure as code (IaC) to provision Azure OpenAI dep
125139
azd auth login --use-device-code
126140
```
127141
142+
If you are using a tenant besides the default tenant, you may need to also login with Azure CLI to that tenant:
143+
144+
```shell
145+
az login --tenant your-tenant-id
146+
```
147+
128148
3. Provision the OpenAI account:
129149
130150
```shell
@@ -165,17 +185,22 @@ You can run the examples in this repository by executing the scripts in the `exa
165185
| [agent_basic.py](examples/agent_basic.py) | A basic informational agent. |
166186
| [agent_tool.py](examples/agent_tool.py) | An agent with a single weather tool. |
167187
| [agent_tools.py](examples/agent_tools.py) | A weekend planning agent with multiple tools. |
188+
| [agent_session.py](examples/agent_session.py) | In-memory sessions for multi-turn conversations with memory across messages. |
189+
| [agent_history_redis.py](examples/agent_history_redis.py) | Persistent chat history with Redis for conversation history that survives restarts. |
168190
| [agent_supervisor.py](examples/agent_supervisor.py) | A supervisor orchestrating activity and recipe sub-agents. |
169191
| [workflow_magenticone.py](examples/workflow_magenticone.py) | A MagenticOne multi-agent workflow. |
170192
| [workflow_hitl.py](examples/workflow_hitl.py) | Human-in-the-loop (HITL) for tool-enabled agents with human feedback. |
171193
| [agent_middleware.py](examples/agent_middleware.py) | Agent, chat, and function middleware for logging, timing, and blocking. |
194+
| [agent_knowledge_sqlite.py](examples/agent_knowledge_sqlite.py) | Knowledge retrieval (RAG) using a custom context provider with SQLite FTS5. |
195+
| [agent_knowledge_postgres.py](examples/agent_knowledge_postgres.py) | Knowledge retrieval (RAG) with PostgreSQL hybrid search (pgvector + full-text) using Reciprocal Rank Fusion. |
172196
| [agent_mcp_remote.py](examples/agent_mcp_remote.py) | An agent using a remote MCP server (Microsoft Learn) for documentation search. |
173197
| [agent_mcp_local.py](examples/agent_mcp_local.py) | An agent connected to a local MCP server (e.g. for expense logging). |
174198
| [openai_tool_calling.py](examples/openai_tool_calling.py) | Tool calling with the low-level OpenAI SDK, showing manual tool dispatch. |
175199
| [workflow_basic.py](examples/workflow_basic.py) | A workflow-based agent. |
176200
| [agent_otel_aspire.py](examples/agent_otel_aspire.py) | An agent with OpenTelemetry tracing, metrics, and structured logs exported to the [Aspire Dashboard](https://aspire.dev/dashboard/standalone/). |
177201
| [agent_otel_appinsights.py](examples/agent_otel_appinsights.py) | An agent with OpenTelemetry tracing, metrics, and structured logs exported to [Azure Application Insights](https://learn.microsoft.com/azure/azure-monitor/app/app-insights-overview). Requires Azure provisioning via `azd provision`. |
178202
| [agent_evaluation.py](examples/agent_evaluation.py) | Evaluate a travel planner agent using [Azure AI Evaluation](https://learn.microsoft.com/azure/ai-foundry/concepts/evaluation-evaluators/agent-evaluators) agent evaluators (IntentResolution, ToolCallAccuracy, TaskAdherence, ResponseCompleteness). Optionally set `AZURE_AI_PROJECT` in `.env` to log results to [Azure AI Foundry](https://learn.microsoft.com/azure/ai-foundry/how-to/develop/agent-evaluate-sdk). |
203+
| [agent_redteam.py](examples/agent_redteam.py) | Red-team a financial advisor agent using [Azure AI Evaluation](https://learn.microsoft.com/azure/ai-foundry/how-to/develop/red-teaming-agent) to test resilience against adversarial attacks across risk categories (Violence, HateUnfairness, Sexual, SelfHarm). Requires `AZURE_AI_PROJECT` in `.env`. |
179204
180205
## Using the Aspire Dashboard for telemetry
181206
@@ -190,7 +215,7 @@ The Aspire Dashboard runs automatically as a service alongside the dev container
190215
2. Run the example:
191216
192217
```sh
193-
uv run agent_otel_aspire.py
218+
uv run examples/agent_otel_aspire.py
194219
```
195220
196221
3. Open the dashboard at <http://localhost:18888> and explore:

0 commit comments

Comments
 (0)