A simple chat example demonstrating how to use the OpenAI SDK with Microsoft Foundry Local for local AI inference.
This sample shows how to:
- Use the OpenAI Python SDK with Foundry Local
- Handle both Azure OpenAI and local Foundry configurations
- Implement proper error handling and fallback strategies
- Use the FoundryLocalManager for service management
- Foundry Local: Installed and available on PATH
- Python: 3.8 or later
- Model: A model loaded in Foundry Local (e.g.,
phi-4-mini)
-
Set up Python environment:
cd Module08 py -m venv .venv .venv\Scripts\activate -
Install dependencies:
pip install -r requirements.txt
-
Start Foundry Local service and load a model:
foundry model run phi-4-mini
# Using FoundryLocalManager (recommended)
python samples\01\chat_quickstart.py "Explain what Foundry Local is"
# Using manual configuration
set BASE_URL=http://localhost:8000
set MODEL=phi-4-mini
set API_KEY=
python samples\01\chat_quickstart.py "Write a welcome message"set AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com
set AZURE_OPENAI_API_KEY=your-api-key
set AZURE_OPENAI_API_VERSION=2024-08-01-preview
set MODEL=your-deployment-name
python samples\01\chat_quickstart.py "Hello from Azure OpenAI"The sample uses the official Foundry Local SDK for proper service management:
from foundry_local import FoundryLocalManager
from openai import OpenAI
# Initialize Foundry Local
manager = FoundryLocalManager(alias)
model_info = manager.get_model_info(alias)
# Configure OpenAI client
client = OpenAI(
base_url=manager.endpoint,
api_key=manager.api_key
)Robust error handling with fallback to manual configuration:
- Automatic service discovery
- Graceful degradation if SDK is unavailable
- Clear error messages for troubleshooting
| Variable | Description | Default | Required |
|---|---|---|---|
MODEL |
Model alias or name | phi-4-mini |
No |
BASE_URL |
Foundry Local base URL | http://localhost:8000 |
No |
API_KEY |
API key (usually not needed for local) | "" |
No |
AZURE_OPENAI_ENDPOINT |
Azure OpenAI endpoint | - | For Azure |
AZURE_OPENAI_API_KEY |
Azure OpenAI API key | - | For Azure |
AZURE_OPENAI_API_VERSION |
Azure API version | 2024-08-01-preview |
No |
-
"Could not use Foundry SDK" warning:
- Install foundry-local-sdk:
pip install foundry-local-sdk - Or set environment variables for manual configuration
- Install foundry-local-sdk:
-
Connection refused:
- Ensure Foundry Local is running:
foundry service status - Check if a model is loaded:
foundry service ps
- Ensure Foundry Local is running:
-
Model not found:
- List available models:
foundry model list - Load a model:
foundry model run phi-4-mini
- List available models:
# Check Foundry Local status
foundry service status
# List loaded models
foundry service ps
# Test API endpoint
curl http://localhost:8000/v1/models