Files
agent-framework/python/samples
T
Ben Thomas b000a2cf51 Python: Adding AgentFileStore and FileAccessProvider to support file access operations. (#6099)
* Adding AgentFileStore and FileAccessProvider to support file ased operations for agents.

* Address PR review feedback on FileAccessProvider

- Probe symlinks on the unresolved candidate path so in-root symlinks
  cannot silently pass and out-of-root symlinks surface the correct
  error message.
- Validate matching_lines elements in FileSearchResult.from_dict and
  raise a clean ValueError for non-mapping entries.
- Cap search regex pattern length (256 chars) via a new
  _compile_search_regex helper to mitigate ReDoS, and surface the cap
  in the file_access_search_files tool description.
- Skip non-UTF-8 files during filesystem search instead of aborting
  the entire directory walk.
- Replace the module-scope trailing string in the data-processing
  sample with comments to avoid Ruff B018.
- Remove the checked-in working/region_totals.md sample artifact so
  the save flow works from a clean checkout.
- Expand the Windows stdout reconfiguration comment in task_runner.py
  for clarity.
- Add tests for invalid/oversize regex, non-UTF-8 file search, and
  in-root symlink rejection.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Fix mypy redundant-cast in FileSearchResult.from_dict

Use cast(list[object], ...) instead of cast(list[Any], ...) so the
cast represents a real type change (lists are invariant) and is no
longer flagged by mypy as redundant, while still satisfying pyright's
reportUnknownVariableType. Matches the existing pattern in _memory.py.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Tighten path normalization and directory resolution in FileAccess

- _normalize_relative_path now strips surrounding whitespace up front
  so leading/trailing spaces never leak into file segments, and
  rejects trailing path separators for file paths so 'foo/' is no
  longer silently coerced to 'foo'.
- FileSystemAgentFileStore._resolve_safe_directory_path normalizes
  with is_directory=True and maps an empty normalized result to the
  root. This matches InMemoryAgentFileStore so whitespace-only
  directory inputs resolve to the root instead of raising.
- Added tests for whitespace stripping, trailing-separator rejection,
  and whitespace-only directory listing on the filesystem store.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Harden FileAccess search and atomic save in store API

- Add wall-clock timeout (10s) around regex scans so a pathological pattern (e.g. `(a+)+`) below the length cap cannot stall the event loop.
- Offload the InMemoryAgentFileStore regex scan to a worker thread, matching the filesystem store.
- Fail closed when `Path.is_symlink` raises during the safe-path probe so a permission error cannot silently bypass the symlink/reparse-point rejection.
- Add `overwrite: bool = True` to `AgentFileStore.write_file`; the in-memory store performs the check under the existing lock and the filesystem store uses `open(mode='x')` so concurrent callers cannot race past `overwrite=False`.
- `file_access_save_file` now relies on the atomic store call instead of a separate `file_exists` round-trip.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Fix Python 3.10 timeout handling and add directory arg to list/search tools

- Catch asyncio.TimeoutError in _run_search_with_timeout. In Python 3.10
  asyncio.wait_for raises asyncio.exceptions.TimeoutError, which is
  distinct from the builtin TimeoutError (the two were unified in 3.11).
  Catching the asyncio alias works on every supported version.
- Add an optional directory parameter to file_access_list_files and
  file_access_search_files so agents can enumerate / scope searches to
  nested folders, not just the store root.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Address FileAccess review feedback: case, errors, signal, TOCTOU

- InMemoryAgentFileStore now stores (display_name, content) so list_files
  and search_files return the original-case names callers wrote, matching
  the behaviour of FileSystemAgentFileStore on case-preserving filesystems
  and removing the silent in-memory vs. on-disk contract divergence.
- FileSystemAgentFileStore.read_file raises ValueError instead of letting
  UnicodeDecodeError bubble for binary / non-UTF-8 input, restoring
  symmetry with search_files (which still skips) and giving the tool
  layer a recoverable type to translate.
- Tool wrappers now catch ValueError and OSError around every operation
  and surface them as readable strings, so 'you used ..' and 'the file
  already exists' are both reported to the model the same way instead of
  the former crashing out as an unhandled exception.
- _search_files_sync logs per skipped non-UTF-8 file at WARNING and an
  aggregate INFO summary so operators can distinguish 'no matches' from
  'half the corpus was unreadable'.
- FileSystemAgentFileStore softens its docstrings to acknowledge the
  inherent probe-then-open TOCTOU window. On POSIX both read and write
  now pass O_NOFOLLOW so the kernel refuses if the leaf segment becomes
  a symlink between the probe and the open. Windows has no equivalent
  flag; the limitation is documented.
- Tests cover: case preservation on list/search, ValueError on non-UTF-8
  read at the store and tool layer, tool-layer string responses for
  path-traversal and oversized-regex inputs, search-skip log output,
  symlink rejection on delete/search/list, and symlinked intermediate
  directory rejection.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Address FileAccess nit comments: docstrings, enumerate, opt-in delete approval

- Expand FileSearchMatch/FileSearchResult.to_dict docstrings to explain why
  the override is needed (__slots__ defeats the mixin's __dict__ iteration)
  and why exclude/exclude_none are accepted-but-ignored (mixin signature
  compatibility for callers like to_json).
- Use enumerate(lines, start=1) in _search_file_content so the +1 below is
  no longer needed; rename loop variable to line_number for clarity.
- Add opt-in require_delete_approval: bool = False on FileAccessProvider.
  When True, file_access_delete_file is registered with approval_mode
  'always_require' so the host must approve every delete. Default False
  preserves current behaviour and matches the .NET reference, but
  deployments that want a safer-by-default posture can enable it.
- Add tests covering both delete approval modes.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* FileAccess: require delete approval by default

Flip the default for FileAccessProvider(require_delete_approval=...) from
False to True so destructive deletes are gated by host approval out of the
box. Callers that want the previous autonomous behaviour (which matches the
.NET reference) can pass require_delete_approval=False.

Tests updated accordingly.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Fixing linkinspector by installing Chrome for puppeteer first.

---------

Co-authored-by: Ben Thomas <25218250+alliscode@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
b000a2cf51 · 2026-05-28 20:09:50 +00:00
History
..
2025-07-28 07:33:42 +00:00

Python Samples

This directory contains samples demonstrating the capabilities of Microsoft Agent Framework for Python.

Structure

Folder Description
01-get-started/ Progressive tutorial: hello agent → hosting
02-agents/ Deep-dive by concept: tools, middleware, providers, orchestrations
03-workflows/ Workflow patterns: sequential, concurrent, state, declarative, explicit output designation
04-hosting/ Deployment: Azure Functions, Durable Tasks, A2A
05-end-to-end/ Full applications, evaluation, demos

Getting Started

Start with 01-get-started/ and work through the numbered files:

  1. 01_hello_agent.py — Create and run your first agent
  2. 02_add_tools.py — Add function tools with @tool
  3. 03_multi_turn.py — Multi-turn conversations with AgentSession
  4. 04_memory.py — Agent memory with ContextProvider
  5. 05_functional_workflow_with_agents.py — Call agents inside a functional workflow
  6. 06_functional_workflow_basics.py — Write a workflow as a plain async function
  7. 07_first_graph_workflow.py — Build a workflow with executors and edges
  8. 08_host_your_agent.py — Host your agent via Azure Functions

Prerequisites

pip install agent-framework

Environment Variables

Samples call load_dotenv() to automatically load environment variables from a .env file in the python/ directory. This is a convenience for local development and testing.

For local development, set up your environment using any of these methods:

Option 1: Using a .env file (recommended for local development):

  1. Copy .env.example to .env in the python/ directory:
    cp .env.example .env
    
  2. Edit .env and set your values (API keys, endpoints, etc.)

Option 2: Export environment variables directly:

export FOUNDRY_PROJECT_ENDPOINT="your-foundry-project-endpoint"
export FOUNDRY_MODEL="gpt-4o"

Option 3: Using env_file_path parameter (for per-client configuration):

All client classes (e.g., OpenAIChatClient, OpenAIChatCompletionClient) support an env_file_path parameter to load environment variables from a specific file:

from agent_framework.openai import OpenAIChatClient

# Load from a custom .env file
client = OpenAIChatClient(env_file_path="path/to/custom.env")

This allows different clients to use different configuration files if needed.

For the generic OpenAI clients (OpenAIChatClient and OpenAIChatCompletionClient), routing precedence is:

  1. Explicit Azure inputs such as credential, azure_endpoint, or api_version
  2. OPENAI_API_KEY / explicit OpenAI API-key parameters
  3. Azure environment fallback such as AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_API_KEY

If you keep both OpenAI and Azure variables in your shell, the generic clients stay on OpenAI until you pass an explicit Azure input.

For the getting-started samples, you'll need at minimum:

FOUNDRY_PROJECT_ENDPOINT="your-foundry-project-endpoint"
FOUNDRY_MODEL="gpt-4o"

Consolidated sample env inventory

This is the single source of truth for package-level environment variables read by packages included by agent-framework-core[all]. It intentionally excludes variables that are only read by standalone samples, package sample folders, or tests. When package code adds, removes, or renames an environment variable, update this table in the same change.

Example values below are illustrative. For entries not backed by a single public class, the class column names the closest public surface, helper, or package-level initialization point that reads the variable.

package class/module env var example value
agent-framework-anthropic AnthropicClient ANTHROPIC_API_KEY sk-ant-api03-...
agent-framework-anthropic AnthropicClient ANTHROPIC_CHAT_MODEL claude-sonnet-4-5-20250929
agent-framework-foundry FoundryEmbeddingClient FOUNDRY_MODELS_ENDPOINT https://my-endpoint.inference.ai.azure.com
agent-framework-foundry FoundryEmbeddingClient FOUNDRY_MODELS_API_KEY env-key
agent-framework-foundry FoundryEmbeddingClient FOUNDRY_EMBEDDING_MODEL text-embedding-3-small
agent-framework-foundry FoundryEmbeddingClient FOUNDRY_IMAGE_EMBEDDING_MODEL Cohere-embed-v3-english
agent-framework-azure-ai-search AzureAISearchContextProvider AZURE_SEARCH_ENDPOINT https://my-search.search.windows.net
agent-framework-azure-ai-search AzureAISearchContextProvider AZURE_SEARCH_API_KEY search-key
agent-framework-azure-ai-search AzureAISearchContextProvider AZURE_SEARCH_INDEX_NAME hotels-index
agent-framework-azure-ai-search AzureAISearchContextProvider AZURE_SEARCH_KNOWLEDGE_BASE_NAME hotels-kb
agent-framework-azure-cosmos CosmosHistoryProvider AZURE_COSMOS_ENDPOINT https://my-cosmos.documents.azure.com:443/
agent-framework-azure-cosmos CosmosHistoryProvider AZURE_COSMOS_DATABASE_NAME agent-history
agent-framework-azure-cosmos CosmosHistoryProvider AZURE_COSMOS_CONTAINER_NAME messages
agent-framework-azure-cosmos CosmosHistoryProvider AZURE_COSMOS_KEY C2F...==
agent-framework-bedrock BedrockChatClient BEDROCK_REGION us-east-1
agent-framework-bedrock BedrockChatClient BEDROCK_CHAT_MODEL anthropic.claude-3-5-sonnet-20241022-v2:0
agent-framework-bedrock BedrockEmbeddingClient BEDROCK_REGION us-east-1
agent-framework-bedrock BedrockEmbeddingClient BEDROCK_EMBEDDING_MODEL amazon.titan-embed-text-v2:0
agent-framework-bedrock BedrockChatClient / BedrockEmbeddingClient AWS_ACCESS_KEY_ID AKIAIOSFODNN7EXAMPLE
agent-framework-bedrock BedrockChatClient / BedrockEmbeddingClient AWS_SECRET_ACCESS_KEY wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
agent-framework-bedrock BedrockChatClient / BedrockEmbeddingClient AWS_SESSION_TOKEN IQoJb3JpZ2luX2VjEO7//////////wEaCXVzLXdlc3QtMiJHMEUCIQD...
agent-framework-copilotstudio CopilotStudioAgent COPILOTSTUDIOAGENT__ENVIRONMENTID 00000000-0000-0000-0000-000000000000
agent-framework-copilotstudio CopilotStudioAgent COPILOTSTUDIOAGENT__SCHEMANAME cr123_agentname
agent-framework-copilotstudio CopilotStudioAgent COPILOTSTUDIOAGENT__TENANTID 11111111-1111-1111-1111-111111111111
agent-framework-copilotstudio CopilotStudioAgent COPILOTSTUDIOAGENT__AGENTAPPID 22222222-2222-2222-2222-222222222222
agent-framework-core observability ENABLE_INSTRUMENTATION true
agent-framework-core observability ENABLE_SENSITIVE_DATA false
agent-framework-core observability ENABLE_CONSOLE_EXPORTERS true
agent-framework-core observability OTEL_EXPORTER_OTLP_ENDPOINT http://localhost:4317
agent-framework-core observability OTEL_EXPORTER_OTLP_TRACES_ENDPOINT http://localhost:4318/v1/traces
agent-framework-core observability OTEL_EXPORTER_OTLP_METRICS_ENDPOINT http://localhost:4318/v1/metrics
agent-framework-core observability OTEL_EXPORTER_OTLP_LOGS_ENDPOINT http://localhost:4318/v1/logs
agent-framework-core observability OTEL_EXPORTER_OTLP_PROTOCOL grpc
agent-framework-core observability OTEL_EXPORTER_OTLP_HEADERS api-key=demo
agent-framework-core observability OTEL_EXPORTER_OTLP_TRACES_HEADERS api-key=trace-demo
agent-framework-core observability OTEL_EXPORTER_OTLP_METRICS_HEADERS api-key=metric-demo
agent-framework-core observability OTEL_EXPORTER_OTLP_LOGS_HEADERS api-key=log-demo
agent-framework-core observability OTEL_SERVICE_NAME sample-agent
agent-framework-core observability OTEL_SERVICE_VERSION 1.0.0
agent-framework-core observability OTEL_RESOURCE_ATTRIBUTES deployment.environment=dev,service.namespace=agent-framework
agent-framework-devui DevUI server DEVUI_AUTH_TOKEN my-devui-token
agent-framework-foundry FoundryChatClient FOUNDRY_PROJECT_ENDPOINT https://my-project.services.ai.azure.com/api/projects/my-project
agent-framework-foundry FoundryChatClient FOUNDRY_MODEL gpt-4o
agent-framework-foundry FoundryAgent FOUNDRY_AGENT_NAME travel-planner
agent-framework-foundry FoundryAgent FOUNDRY_AGENT_VERSION v1
agent-framework-github-copilot GitHubCopilotAgent GITHUB_COPILOT_CLI_PATH copilot
agent-framework-github-copilot GitHubCopilotAgent GITHUB_COPILOT_MODEL gpt-5
agent-framework-github-copilot GitHubCopilotAgent GITHUB_COPILOT_TIMEOUT 60
agent-framework-github-copilot GitHubCopilotAgent GITHUB_COPILOT_LOG_LEVEL info
agent-framework-mem0 agent_framework_mem0 package import MEM0_TELEMETRY false
agent-framework-ollama OllamaChatClient OLLAMA_HOST http://localhost:11434
agent-framework-ollama OllamaChatClient OLLAMA_MODEL llama3.1:8b
agent-framework-openai OpenAIChatClient / OpenAIChatCompletionClient / OpenAIEmbeddingClient OPENAI_API_KEY sk-proj-...
agent-framework-openai OpenAIChatClient / OpenAIChatCompletionClient / OpenAIEmbeddingClient OPENAI_MODEL gpt-4o-mini
agent-framework-openai OpenAIChatClient OPENAI_CHAT_MODEL gpt-4.1-mini
agent-framework-openai OpenAIChatCompletionClient OPENAI_CHAT_COMPLETION_MODEL gpt-4o
agent-framework-openai OpenAIEmbeddingClient OPENAI_EMBEDDING_MODEL text-embedding-3-small
agent-framework-openai OpenAIChatClient / OpenAIChatCompletionClient / OpenAIEmbeddingClient OPENAI_BASE_URL https://api.openai.com/v1/
agent-framework-openai OpenAIChatClient / OpenAIChatCompletionClient / OpenAIEmbeddingClient OPENAI_ORG_ID org_123456789
agent-framework-openai OpenAIChatClient / OpenAIChatCompletionClient / OpenAIEmbeddingClient AZURE_OPENAI_ENDPOINT https://my-resource.openai.azure.com/
agent-framework-openai OpenAIChatClient / OpenAIChatCompletionClient / OpenAIEmbeddingClient AZURE_OPENAI_API_KEY sk-azure-...
agent-framework-openai OpenAIChatClient / OpenAIChatCompletionClient / OpenAIEmbeddingClient AZURE_OPENAI_API_VERSION 2024-10-21
agent-framework-openai OpenAIChatClient / OpenAIChatCompletionClient / OpenAIEmbeddingClient AZURE_OPENAI_BASE_URL https://my-resource.openai.azure.com/openai/v1/
agent-framework-openai OpenAIChatClient / OpenAIChatCompletionClient / OpenAIEmbeddingClient AZURE_OPENAI_MODEL gpt-4o
agent-framework-openai OpenAIChatClient AZURE_OPENAI_CHAT_MODEL gpt-4.1
agent-framework-openai OpenAIChatCompletionClient AZURE_OPENAI_CHAT_COMPLETION_MODEL gpt-4o-mini
agent-framework-openai OpenAIEmbeddingClient AZURE_OPENAI_EMBEDDING_MODEL text-embedding-3-large
agent-framework-openai OpenAIChatClient / OpenAIChatCompletionClient / OpenAIEmbeddingClient AZURE_OPENAI_RESOURCE_URL https://cognitiveservices.azure.com/

agent-framework-openai supports the Azure OpenAI client-specific deployment aliases listed above; keep packages/openai/README.md as the authoritative reference for the exact fallback order and package-specific behavior.

Note for production: In production environments, set environment variables through your deployment platform (e.g., Azure App Settings, Kubernetes ConfigMaps/Secrets) rather than using .env files. The load_dotenv() call in samples will have no effect when a .env file is not present, allowing environment variables to be loaded from the system.

For Azure authentication, run az login before running samples.

Note on XML tags

Some sample files include XML-style snippet tags (for example <snippet_name> and </snippet_name>). These are used by our documentation tooling and can be ignored or removed when you use the samples outside this repository.

Additional Resources