Velamuvi AIAcademy

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
In this lesson you will learn
  • 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:

Try it yourselfPython
# 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-framework

Most 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)
Output
model-from-environment
MODEL_NAME
model-from-dotenv

Each client looks for every setting in this order, and the first value found wins:

  1. Arguments you pass in code, such as model="MODEL_NAME".
  2. A .env file, but only when you name it with env_file_path=".env".
  3. 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:

ClientAPIUse it for
OpenAIChatClientResponses APIOpenAI's newer API, with hosted tools and stored conversations. The default choice
OpenAIChatCompletionClientChat Completions APIThe 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 variableMeaning
OPENAI_API_KEY, OPENAI_MODELKey and model for OpenAI. OPENAI_CHAT_MODEL or OPENAI_CHAT_COMPLETION_MODEL override the model for one client type
OPENAI_BASE_URL, OPENAI_ORG_IDAnother server address; your organisation, if you belong to several
AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_MODELYour Azure resource address and deployment name
AZURE_OPENAI_API_KEY, AZURE_OPENAI_API_VERSIONKey-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
ProviderClientPackageSettingsCost
OpenAIOpenAIChatClient, OpenAIChatCompletionClientagent-framework-openaiOPENAI_API_KEY, OPENAI_MODELPaid
Azure OpenAIthe same two clientsagent-framework-openaiAZURE_OPENAI_ENDPOINT, AZURE_OPENAI_MODELPaid Azure subscription
Microsoft FoundryFoundryChatClientagent-framework-foundryFOUNDRY_PROJECT_ENDPOINT, FOUNDRY_MODELPaid Azure subscription
Anthropic (Claude)AnthropicClientagent-framework-anthropicANTHROPIC_API_KEY, ANTHROPIC_CHAT_MODELPaid
Claude on other cloudsAnthropicBedrockClient, AnthropicVertexClient, AnthropicFoundryClientagent-framework-anthropicthat cloud's sign-inPaid
Google GeminiGeminiChatClientagent-framework-geminiGOOGLE_API_KEY, GOOGLE_MODELPaid (check for a free tier)
MistralMistralChatClientagent-framework-mistralMISTRAL_API_KEY, MISTRAL_CHAT_MODELPaid (check for a free tier)
Amazon BedrockBedrockChatClientagent-framework-bedrockBEDROCK_REGION, BEDROCK_CHAT_MODEL, or your AWS credentialsPaid AWS account
OllamaOllamaChatClientagent-framework-ollamaOLLAMA_MODEL, OLLAMA_HOST (default http://127.0.0.1:11434)Free, runs on your computer
Foundry LocalFoundryLocalClientagent-framework-foundry-localFOUNDRY_LOCAL_MODELFree, runs on your computer

A few details:

  • AnthropicBedrockClient, AnthropicVertexClient and AnthropicFoundryClient run Claude models through Amazon Bedrock, Google Vertex AI and Microsoft Foundry, using that cloud's account and billing.
  • GeminiChatClient can also use Vertex AI (vertexai=True with 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 pull with a model name, then use OllamaChatClient. 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. FoundryLocalClient downloads 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, BedrockSettings and FoundryLocalSettings.

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())
Output
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:

OptionMeaning
temperature, top_pHow random the answer is. Low values give steadier answers
max_tokensUpper limit on the length of the answer
stop, seedText that ends the answer; a number for more repeatable sampling
frequency_penalty, presence_penalty, logit_biasDiscourage repetition, or push particular tokens up or down
tools, tool_choice, allow_multiple_tool_callsTools the model may call (lesson Function Tools)
response_formatAsk for structured output (lesson Structured Output)
instructionsExtra system instructions for this call
model, user, metadata, store, conversation_idAnother 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)
Output
{'temperature': 0.3, 'thinking_config': {'thinking_budget': 1024}}
{'max_tokens': 300, 'reasoning': {'effort': 'low'}}
Options typeSome extra keys
OpenAIChatOptionsreasoning, include, background, service_tier, truncation, max_tool_calls
OpenAIChatCompletionOptionslogprobs, top_logprobs, prediction
AnthropicChatOptionsthinking, top_k, container
GeminiChatOptionsthinking_config (a ThinkingConfig with thinking_budget, thinking_level or include_thoughts), top_k, response_schema
MistralChatOptionssafe_prompt, reasoning_effort, guardrails
OllamaChatOptionsnum_ctx (context length), keep_alive, num_predict, think
BedrockChatOptionsguardrailConfig, performanceConfig, additionalModelRequestFields
FoundryChatOptions, FoundryLocalChatOptionsFoundry 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)
Output
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 .env file if you pass env_file_path, then PREFIX + FIELD in capitals. It converts text to the field's type, so "250" became 250.0.
  • A SecretString prints ********** in print, f-strings, repr and logs. Call get_secret_value() only where a library needs the real string.
  • required_fields makes a setting compulsory. A missing one raises SettingNotFoundError with 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))
Output
OpenAIChatClient
FunctionInvocationLayer
ChatMiddlewareLayer
ChatTelemetryLayer
RawOpenAIChatClient
True

OpenAIChatClient is built from layers stacked on a raw client:

  • FunctionInvocationLayer runs the tool-calling loop: when the model asks for a tool, it calls your function and sends the result back.
  • ChatMiddlewareLayer runs your chat and function middleware (lesson Middleware).
  • ChatTelemetryLayer records OpenTelemetry traces and metrics (lesson Observability With OpenTelemetry).
  • RawOpenAIChatClient only 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())
Output
True
Clean the chain, then oil it.
Pump it to the pressure on the sidewall.
  • _inner_get_response receives the prepared messages, the options and stream. It returns an awaitable ChatResponse, or, when streaming, a stream of ChatResponseUpdate pieces built with _build_response_stream.
  • CannedClient adds the same three layers that OpenAIChatClient uses, 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.
  • SupportsChatGetResponse is the protocol (the shape) that agents accept. Anything with a matching get_response method qualifies, which isinstance confirms.

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())
Output
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

Practice exercise

Work out which value wins when the same setting comes from several places.

Your solutionPython
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).
Knowledge check

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) and OpenAIChatCompletionClient (Chat Completions API) cover OpenAI, Azure OpenAI and compatible servers; Foundry, Anthropic, Gemini, Mistral, Bedrock, Ollama and Foundry Local have their own clients.
  • ChatOptions holds common options; each provider's options type adds its own keys.
  • load_settings and SecretString work for your own settings; clients are layers on a raw client, and BaseChatClient lets you write your own.

Next: Your First Agent.

Finished reading? Tick it off to track your progress.