Lesson 2 of 39 · Getting Started
Installation, Settings and Chat Clients
Install Microsoft Agent Framework, keep API keys safe and connect chat clients for OpenAI, Azure OpenAI, Foundry, Claude, Gemini, Mistral, Bedrock and Ollama.
- 18 min read
- Intermediate
- Reviewed
- Install Agent Framework and give it an API key without putting the key in your code
- Explain how settings are found: arguments, .env files and environment variables
- Create a chat client for OpenAI, Azure OpenAI, Microsoft Foundry, Anthropic, Gemini, Mistral, Bedrock, Ollama or Foundry Local
- Call a chat client directly with messages and options, including provider-specific options
- Explain raw clients and layers, and write a small chat client of your own
What a chat client is
Every agent needs a way to talk to a language model. In Agent Framework that's a chat client.
Because all clients look the same from the outside, you can switch from a paid cloud model to a free local one by changing one line. Here is that idea in plain Python:
# The idea behind chat clients, in plain Python: every provider's client offers the same
# method, so the code that uses it never changes when you switch providers.
class FakeCloudClient:
name = "cloud model"
def get_response(self, question):
return "Pump the tyres to the pressure printed on their sidewalls."
class FakeLocalClient:
name = "local model"
def get_response(self, question):
return "Check the tyre pressure first; soft tyres feel slow."
def ask(client, question): # knows nothing about the provider, only get_response()
return f"[{client.name}] {client.get_response(question)}"
for client in [FakeCloudClient(), FakeLocalClient()]:
print(ask(client, "My bike feels slow. Any tip?"))Install and set your key
pip install agent-frameworkMost providers need an API key: a secret password for their service, created in your account on the provider's website. Calls are billed by the number of tokens, so set a spending limit in your account. Two free options run models on your own computer instead: Ollama and Foundry Local, shown below.
Never write a key in your code: code gets shared, committed to Git and pasted into chats. Put it in an environment variable instead:
# macOS and Linux
export OPENAI_API_KEY="sk-..."
export OPENAI_MODEL="MODEL_NAME"
# Windows PowerShell
$env:OPENAI_API_KEY="sk-..."
$env:OPENAI_MODEL="MODEL_NAME"MODEL_NAME stands for a model name copied from your provider's documentation; names change often, so this course never hard-codes one.
Where settings come from
from agent_framework.openai import OpenAIChatClient
client = OpenAIChatClient() # key and model from OPENAI_API_KEY and OPENAI_MODEL
print(client.model)
client = OpenAIChatClient(model="MODEL_NAME") # model in code, key still from the environment
print(client.model)
client = OpenAIChatClient(env_file_path=".env") # read settings from a .env file first
print(client.model)model-from-environment MODEL_NAME model-from-dotenv
Each client looks for every setting in this order, and the first value found wins:
- Arguments you pass in code, such as
model="MODEL_NAME". - A .env file, but only when you name it with
env_file_path=".env". - Environment variables with the provider's prefix, such as
OPENAI_MODEL.
OpenAI and Azure OpenAI
The agent_framework.openai module has two clients for the two OpenAI APIs:
| Client | API | Use it for |
|---|---|---|
OpenAIChatClient | Responses API | OpenAI's newer API, with hosted tools and stored conversations. The default choice |
OpenAIChatCompletionClient | Chat Completions API | The older, simpler API that many other servers copy |
Both also work with Azure OpenAI, Microsoft's hosting of OpenAI models in your own Azure subscription. Pass the endpoint and the name of your deployment (the name you gave the model in Azure), and sign in with a credential instead of a key:
from azure.identity.aio import AzureCliCredential
from agent_framework.openai import OpenAIChatClient
client = OpenAIChatClient(
azure_endpoint="https://YOUR-RESOURCE.openai.azure.com",
model="YOUR-DEPLOYMENT", # in Azure, the model is the name of your deployment
credential=AzureCliCredential(), # signs in with your `az login`, no key in code
)AzureCliCredential comes from the azure-identity package (pip install azure-identity) and uses the account you signed in with az login, so there's no key to leak. You can also use a key with AZURE_OPENAI_API_KEY.
| Environment variable | Meaning |
|---|---|
OPENAI_API_KEY, OPENAI_MODEL | Key and model for OpenAI. OPENAI_CHAT_MODEL or OPENAI_CHAT_COMPLETION_MODEL override the model for one client type |
OPENAI_BASE_URL, OPENAI_ORG_ID | Another server address; your organisation, if you belong to several |
AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_MODEL | Your Azure resource address and deployment name |
AZURE_OPENAI_API_KEY, AZURE_OPENAI_API_VERSION | Key-based sign-in and API version for Azure |
If OPENAI_API_KEY is set, the clients use OpenAI; they only fall back to the Azure variables when it isn't. To force Azure, pass azure_endpoint or credential in code. OpenAISettings lists every OpenAI setting.
Many other servers, including local model servers, copy the Chat Completions API. Point OpenAIChatCompletionClient at them with base_url:
from agent_framework.openai import OpenAIChatCompletionClient
client = OpenAIChatCompletionClient(
base_url="http://localhost:1234/v1", # any server that speaks the Chat Completions API
api_key="not-needed", # local servers usually ignore the key
model="MODEL_NAME",
)Every provider
Each provider has its own package and client, and they all work the same way:
from azure.identity.aio import AzureCliCredential
from agent_framework.amazon import BedrockChatClient
from agent_framework.anthropic import AnthropicClient
from agent_framework.foundry import FoundryChatClient, FoundryLocalClient
from agent_framework.gemini import GeminiChatClient
from agent_framework.mistral import MistralChatClient
from agent_framework.ollama import OllamaChatClient
claude = AnthropicClient(model="MODEL_NAME") # ANTHROPIC_API_KEY
gemini = GeminiChatClient(model="MODEL_NAME") # GOOGLE_API_KEY
mistral = MistralChatClient(model="MODEL_NAME") # MISTRAL_API_KEY
bedrock = BedrockChatClient(model="MODEL_NAME", region="us-east-1") # your AWS credentials
foundry = FoundryChatClient( # a Microsoft Foundry project
project_endpoint="https://YOUR-PROJECT.services.ai.azure.com",
model="YOUR-DEPLOYMENT",
credential=AzureCliCredential(),
)
ollama = OllamaChatClient(model="MODEL_NAME") # free: Ollama on your computer
local = FoundryLocalClient(model="MODEL_NAME") # free: Foundry Local on your computer # @fake| Provider | Client | Package | Settings | Cost |
|---|---|---|---|---|
| OpenAI | OpenAIChatClient, OpenAIChatCompletionClient | agent-framework-openai | OPENAI_API_KEY, OPENAI_MODEL | Paid |
| Azure OpenAI | the same two clients | agent-framework-openai | AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_MODEL | Paid Azure subscription |
| Microsoft Foundry | FoundryChatClient | agent-framework-foundry | FOUNDRY_PROJECT_ENDPOINT, FOUNDRY_MODEL | Paid Azure subscription |
| Anthropic (Claude) | AnthropicClient | agent-framework-anthropic | ANTHROPIC_API_KEY, ANTHROPIC_CHAT_MODEL | Paid |
| Claude on other clouds | AnthropicBedrockClient, AnthropicVertexClient, AnthropicFoundryClient | agent-framework-anthropic | that cloud's sign-in | Paid |
| Google Gemini | GeminiChatClient | agent-framework-gemini | GOOGLE_API_KEY, GOOGLE_MODEL | Paid (check for a free tier) |
| Mistral | MistralChatClient | agent-framework-mistral | MISTRAL_API_KEY, MISTRAL_CHAT_MODEL | Paid (check for a free tier) |
| Amazon Bedrock | BedrockChatClient | agent-framework-bedrock | BEDROCK_REGION, BEDROCK_CHAT_MODEL, or your AWS credentials | Paid AWS account |
| Ollama | OllamaChatClient | agent-framework-ollama | OLLAMA_MODEL, OLLAMA_HOST (default http://127.0.0.1:11434) | Free, runs on your computer |
| Foundry Local | FoundryLocalClient | agent-framework-foundry-local | FOUNDRY_LOCAL_MODEL | Free, runs on your computer |
A few details:
AnthropicBedrockClient,AnthropicVertexClientandAnthropicFoundryClientrun Claude models through Amazon Bedrock, Google Vertex AI and Microsoft Foundry, using that cloud's account and billing.GeminiChatClientcan also use Vertex AI (vertexai=Truewith a project and location) instead of an API key.- Ollama is a free program that downloads and runs open models on your computer. Install it from ollama.com, run
ollama pullwith a model name, then useOllamaChatClient. Small models are slower and less capable than cloud models, but they cost nothing and keep your data on your machine. - Foundry Local is Microsoft's free equivalent.
FoundryLocalClientdownloads the model and starts the local service when you create it, which can take a while the first time. - Each provider has a settings class listing its environment variables:
OpenAISettings,GoogleGeminiSettings,MistralSettings,OllamaSettings,BedrockSettingsandFoundryLocalSettings.
Calling a chat client directly
You don't need an agent to use a client. get_response takes a list of messages:
import asyncio
from agent_framework import ChatOptions, Message
from agent_framework.openai import OpenAIChatClient
async def main():
client = OpenAIChatClient(model="MODEL_NAME")
options: ChatOptions = {"temperature": 0.2, "max_tokens": 120}
response = await client.get_response(
[
Message("system", ["You are a friendly bike mechanic. Answer in one sentence."]),
Message("user", ["Why does my chain squeak?"]),
],
options=options,
)
print(response.text)
print(response.messages[0].role, "|", response.model)
asyncio.run(main())A squeaky chain is usually dry or dirty, so clean it and add a few drops of chain oil. assistant | scripted-model
Message(role, contents) builds one message: "system" for instructions, "user" for the person, "assistant" for the model. The next lessons cover messages in detail.
options is a ChatOptions dictionary. These keys work with every provider that supports them:
| Option | Meaning |
|---|---|
temperature, top_p | How random the answer is. Low values give steadier answers |
max_tokens | Upper limit on the length of the answer |
stop, seed | Text that ends the answer; a number for more repeatable sampling |
frequency_penalty, presence_penalty, logit_bias | Discourage repetition, or push particular tokens up or down |
tools, tool_choice, allow_multiple_tool_calls | Tools the model may call (lesson Function Tools) |
response_format | Ask for structured output (lesson Structured Output) |
instructions | Extra system instructions for this call |
model, user, metadata, store, conversation_id | Another model for this call; who the end user is; tags; whether the service stores the conversation |
Provider-specific options
Providers have extra features, and each has its own options type with extra keys:
from agent_framework.gemini import GeminiChatOptions, ThinkingConfig
from agent_framework.openai import OpenAIChatOptions
gemini_options: GeminiChatOptions = {
"temperature": 0.3,
"thinking_config": ThinkingConfig(thinking_budget=1024), # how many tokens the model may think with
}
openai_options: OpenAIChatOptions = {"max_tokens": 300, "reasoning": {"effort": "low"}}
print(gemini_options)
print(openai_options){'temperature': 0.3, 'thinking_config': {'thinking_budget': 1024}}
{'max_tokens': 300, 'reasoning': {'effort': 'low'}}| Options type | Some extra keys |
|---|---|
OpenAIChatOptions | reasoning, include, background, service_tier, truncation, max_tool_calls |
OpenAIChatCompletionOptions | logprobs, top_logprobs, prediction |
AnthropicChatOptions | thinking, top_k, container |
GeminiChatOptions | thinking_config (a ThinkingConfig with thinking_budget, thinking_level or include_thoughts), top_k, response_schema |
MistralChatOptions | safe_prompt, reasoning_effort, guardrails |
OllamaChatOptions | num_ctx (context length), keep_alive, num_predict, think |
BedrockChatOptions | guardrailConfig, performanceConfig, additionalModelRequestFields |
FoundryChatOptions, FoundryLocalChatOptions | Foundry uses the OpenAI options; Foundry Local adds extra_body and top_k |
The types are TypedDicts: at run time they're ordinary dictionaries, but your editor can autocomplete the keys and spot typos.
Settings and secrets
Clients load their settings with load_settings, and you can use it for your own settings too. Secrets come back as a SecretString, which hides itself when printed:
import os
from typing import TypedDict
from agent_framework import SecretString, load_settings
from agent_framework.exceptions import SettingNotFoundError
from agent_framework.openai import OpenAISettings
os.environ["OPENAI_API_KEY"] = "sk-demo-123456" # normally set outside your code
settings = load_settings(OpenAISettings, env_prefix="OPENAI_", model="MODEL_NAME")
key = settings["api_key"]
print(settings["model"], key, repr(key), len(key))
print(f"Authorization: Bearer {key}")
print(key.get_secret_value()[:7] + "...")
class ShopSettings(TypedDict, total=False): # your own settings, same mechanism
api_url: str | None
api_token: SecretString | None
max_refund: float | None
os.environ["SHOP_API_URL"] = "https://shop.example.com/api"
os.environ["SHOP_MAX_REFUND"] = "250"
shop = load_settings(ShopSettings, env_prefix="SHOP_", required_fields=["api_url"])
print(shop)
try:
load_settings(ShopSettings, env_prefix="SHOP_", required_fields=["api_token"])
except SettingNotFoundError as error:
print(error)MODEL_NAME ********** SecretString('**********') 14
Authorization: Bearer **********
sk-demo...
{'api_url': 'https://shop.example.com/api', 'api_token': None, 'max_refund': 250.0}
Required setting 'api_token' was not provided. Set it via the 'api_token' parameter or the 'SHOP_API_TOKEN' environment variable.load_settings(SettingsType, env_prefix=..., **overrides)reads each field from the overrides, then a.envfile if you passenv_file_path, thenPREFIX+FIELDin capitals. It converts text to the field's type, so"250"became250.0.- A
SecretStringprints**********inprint, f-strings,reprand logs. Callget_secret_value()only where a library needs the real string. required_fieldsmakes a setting compulsory. A missing one raisesSettingNotFoundErrorwith a message naming the parameter and the environment variable to set.
Raw clients and layers
from agent_framework.openai import OpenAIChatClient, RawOpenAIChatClient
for layer in OpenAIChatClient.__mro__[:5]:
print(layer.__name__)
print(issubclass(OpenAIChatClient, RawOpenAIChatClient))OpenAIChatClient FunctionInvocationLayer ChatMiddlewareLayer ChatTelemetryLayer RawOpenAIChatClient True
OpenAIChatClient is built from layers stacked on a raw client:
FunctionInvocationLayerruns the tool-calling loop: when the model asks for a tool, it calls your function and sends the result back.ChatMiddlewareLayerruns your chat and function middleware (lesson Middleware).ChatTelemetryLayerrecords OpenTelemetry traces and metrics (lesson Observability With OpenTelemetry).RawOpenAIChatClientonly talks to the API.
Every provider has a raw version, such as RawOpenAIChatCompletionClient, RawAnthropicClient, RawGeminiChatClient, RawMistralChatClient and RawFoundryChatClient. Use the normal classes; raw ones are for people building their own layer stack.
Your own chat client
You can connect any model by subclassing BaseChatClient and writing one method, _inner_get_response. A client that answers from a dictionary is also handy for tests: no network, no key, no cost.
import asyncio
from agent_framework import (Agent, BaseChatClient, ChatMiddlewareLayer, ChatResponse, ChatResponseUpdate,
Content, FunctionInvocationLayer, Message, SupportsChatGetResponse)
from agent_framework.observability import ChatTelemetryLayer
class RawCannedClient(BaseChatClient):
"""A pretend model for tests: answers from a dictionary. No network, no cost."""
def __init__(self, *, answers: dict[str, str], **kwargs):
super().__init__(**kwargs)
self.answers = answers
def _inner_get_response(self, *, messages, stream, options, **kwargs):
question = messages[-1].text.lower()
reply = next((answer for word, answer in self.answers.items() if word in question), "I don't know.")
if stream:
async def updates():
for word in reply.split(" "):
yield ChatResponseUpdate(role="assistant", contents=[Content.from_text(word + " ")])
return self._build_response_stream(updates())
async def complete():
return ChatResponse(messages=[Message("assistant", [reply])], model="canned")
return complete()
class CannedClient(FunctionInvocationLayer, ChatMiddlewareLayer, ChatTelemetryLayer, RawCannedClient):
"""The same client with the standard layers: tool calling, middleware and telemetry."""
async def main():
client = CannedClient(answers={"chain": "Clean the chain, then oil it.", "tyre": "Pump it to the pressure on the sidewall."})
print(isinstance(client, SupportsChatGetResponse))
agent = Agent(client=client, instructions="You are a bike mechanic.")
print((await agent.run("My chain squeaks")).text)
print((await agent.run("How hard should my tyre be?")).text)
asyncio.run(main())True Clean the chain, then oil it. Pump it to the pressure on the sidewall.
_inner_get_responsereceives the prepared messages, the options andstream. It returns an awaitableChatResponse, or, when streaming, a stream ofChatResponseUpdatepieces built with_build_response_stream.CannedClientadds the same three layers thatOpenAIChatClientuses, so tools and middleware work with it too. Without the layers, an agent still runs but logs that the client doesn't support function invoking.SupportsChatGetResponseis the protocol (the shape) that agents accept. Anything with a matchingget_responsemethod qualifies, whichisinstanceconfirms.
Closing clients
A client may hold network connections. Use async with so they're closed even if an error happens:
import asyncio
from agent_framework import Agent, Message
from agent_framework.openai import OpenAIChatClient
async def main():
async with OpenAIChatClient(model="MODEL_NAME") as client: # closed when the block ends
response = await client.get_response([Message("user", ["Say hi in three words."])])
print(response.text)
async with Agent(client=OpenAIChatClient(model="MODEL_NAME"), instructions="Be brief.") as agent:
print((await agent.run("Say bye in two words.")).text)
asyncio.run(main())Hi there, rider! Bye, rider!
async with on an agent opens and closes its client for you. Without it, call await client.close() when you're done.
Common mistakes
Work out which value wins when the same setting comes from several places.
explicit = {"model": None, "api_key": None} # arguments passed in code
dotenv = {"model": "small-model"} # values from a .env file
environ = {"OPENAI_MODEL": "big-model", "OPENAI_API_KEY": "sk-abc123"}
# Resolve each setting like load_settings does: the explicit value first, then the .env value,
# then the environment variable "OPENAI_" + the name in capitals. None counts as missing.
# Print "model=<value>", then "api_key=**********" if a key was found (never print the key itself).
OPENAI_MODEL is set to big-model in the environment, a .env file says small-model, and your code calls OpenAIChatClient() with no arguments and no env_file_path. Which model is used?
Summary
- A chat client connects to one model provider; all clients share
get_response, so agents work with any of them. - Keep keys out of code: settings come from arguments, then a .env file you name, then environment variables.
OpenAIChatClient(Responses API) andOpenAIChatCompletionClient(Chat Completions API) cover OpenAI, Azure OpenAI and compatible servers; Foundry, Anthropic, Gemini, Mistral, Bedrock, Ollama and Foundry Local have their own clients.ChatOptionsholds common options; each provider's options type adds its own keys.load_settingsandSecretStringwork for your own settings; clients are layers on a raw client, andBaseChatClientlets you write your own.
Next: Your First Agent.
Finished reading? Tick it off to track your progress.