Azure OpenAI Realtime API, Prompt Caching and Fine-Tuning in Microsoft Foundry: Build Faster, Cheaper AI Apps

Azure AI/ML

Share Post Now :

HOW TO GET HIGH PAYING JOBS IN AWS CLOUD

Even as a beginner with NO Experience Coding Language

Explore Free course Now

Table of Contents

Loading

Two things decide whether an AI app feels good to use: how fast it answers and how much it costs to run. A voice assistant that pauses for two seconds before replying feels broken. A chatbot that sends the same long instructions with every request quietly burns money.

Microsoft Foundry gives you four tools to fix both problems. The Realtime API lets users talk to a model and hear it answer almost instantly. Prompt caching stops you from paying full price to reprocess the same instructions again and again. Vision fine-tuning teaches a model to understand your own images. Model distillation moves the knowledge of a large model into a smaller, cheaper one.

In this guide, you’ll learn what each feature does, when to use it, and how to try it yourself with working steps. No deep AI background is needed. If you can read basic Python, you can follow along.

Azure AI

1. Azure OpenAI Realtime API: Talk to Your AI in Real Time

Traditional voice apps work in three slow steps. First, speech-to-text turns the user’s voice into words. Then a language model writes a reply. Finally, text-to-speech reads it out. Every hand-off adds delay, and the conversation feels stiff.

The Realtime API removes those hand-offs. You stream audio or text in, and the model streams audio or text back as it thinks. It can also call your functions mid-conversation, for example to look up an order, and it remembers what was said earlier in the session. The result feels much closer to talking to a person.

Key features

Feature What it means for you
Real-time audio streaming Audio goes in and comes out continuously, so replies start almost immediately
Multimodal input and output Work with speech and text in the same session
Low-latency delivery Choose WebRTC, WebSocket or SIP depending on your app
Function calling The model can trigger your tools and APIs during the conversation
Context retention The session remembers earlier turns, so users do not repeat themselves

Which realtime model should you use?

Microsoft Foundry offers several realtime models for global deployments. Pick one based on quality, cost and the kind of audio task you have:

Model Best for
gpt-realtime-2.1 The newest full-size voice agent model, for the best conversation quality
gpt-realtime-2.1-mini Lower cost and lower latency for high-volume voice experiences
gpt-realtime-1.5 and gpt-realtime-2 Earlier voice agent models that remain available
gpt-realtime and gpt-realtime-mini The first generation of GA realtime models
gpt-realtime-translate Live speech translation sessions
gpt-realtime-whisper and gpt-live-transcribe Streaming transcription, priced by duration

Tip: Model versions change often. Before you deploy, open the Models page in Microsoft Foundry and check which realtime models and regions are available to you today.

WebRTC, WebSocket or SIP?

Connection Typical latency Use it when
WebRTC About 100 ms Your users are in a browser or mobile app and you want the lowest delay
WebSocket About 200 ms Your backend talks to the model and relays audio from another system
SIP Varies You are connecting phone calls, call centres or IVR systems

Real-world use cases

  • Voice assistants: Hands-free help in cars, kiosks and smart devices.
  • Customer support: A voice agent that answers questions and looks up account details while the caller is still talking.
  • Language learning: Practice conversations with instant spoken feedback.
  • Healthcare and enterprise copilots: Spoken note-taking, scheduling and internal help desks, with the right access controls in place.
  • Gaming: Non-player characters that actually hold a conversation.

Good to know before you build

  • Use the GA endpoint, which has /openai/v1 in the URL and no api-version parameter.
  • Use an OpenAI-provided SDK (Python 1.54.0 or later, JavaScript 4.77.0 or later, .NET 2.9.0 or later).
  • A session can run for up to 60 minutes. Plan to reconnect for longer conversations.
  • Audio is sent as 16-bit PCM, mono, at 24 kHz, in small chunks of about 100 ms.
  • If you use the older preview event names, switch to the current ones, such as response.output_text.delta and response.output_audio.delta.

RealTime API

2. Prompt Caching: Stop Paying Twice for the Same Instructions

Most real apps send a large block of the same text with every request: a long system prompt, a set of tools, a policy document. The model has to read all of it again each time.

Prompt caching fixes that. When the start of your prompt matches a recent request, Azure reuses the work it already did. You get faster responses, and the cached part of the input is billed at a discount on Standard deployments.

How Prompt Caching Works

Step Process Outcome
Cache Lookup The system checks whether a similar prompt already exists in cache Reduces unnecessary computation
Cache Hit Matching prompt context is reused Faster response generation
Cache Miss Prompt is processed normally New context gets cached
Prefix Caching Frequently repeated prompt segments are stored Improves future request efficiency

What you need to know

Topic Details
Minimum size The prompt must be at least 1,024 tokens, and the first 1,024 tokens must be identical across requests
Switching it on Automatic. It is enabled by default for supported models, so basic caching needs no code change
Supported models GPT-4o and newer chat, completion, responses and realtime models
How long it lasts In-memory caches usually clear after 5 to 10 minutes of inactivity. Selected GPT-5 family models can keep cached prompts for up to 24 hours
Checking hits Look at cached_tokens inside prompt_tokens_details in the response usage

How to get more cache hits

  • Put stable content first. System prompt, tool definitions and reference documents go at the start. The user’s question goes last.
  • Keep the beginning identical. A single changed character in the first 1,024 tokens causes a miss.
  • Keep conversations append-only. Add new messages at the end instead of rewriting earlier ones.
  • Send requests steadily. Caches expire when idle, so steady traffic with the same prefix keeps them warm.
  • Use a cache key on newer models. On GPT-5.6 and later, prompt_cache_key helps related requests land on the same cache.

A real example: an HR assistant for a large company sends the same 3,000-token policy handbook with every question. With caching, the handbook is processed once and reused for the many questions that follow, so every employee gets a faster answer and the company pays less for input tokens.

Tip: The exact savings depend on your model, deployment type and how repetitive your prompts are. Measure your own cache hit rate using cached_tokens instead of relying on a general percentage.

Prompt Catching

 

3. Vision Fine-Tuning: Teach the Model to Read Your Images

Out of the box, a vision-capable model can describe photos, read text from images and answer questions about charts. But it does not know your products, your forms or your equipment. If a general model keeps misreading the images that matter to your business, vision fine-tuning is the fix.

You show the model many examples of your own images paired with the right answers, and it adjusts to match. Even a modest, well-prepared dataset can make a clear difference on narrow, repeatable tasks.

When vision fine-tuning makes sense

  • Reading or classifying a specific kind of document, label or form.
  • Spotting defects or damage in photos of your own products.
  • Understanding diagrams, maps or screenshots from your own software.
  • Getting consistent, structured output from images, such as JSON fields.

How the process works

A single training example looks like this (shortened for readability):

{“messages”: [

  {“role”: “system”, “content”: “You read product labels and return JSON.”},

  {“role”: “user”, “content”: [

    {“type”: “text”, “text”: “Extract the batch number and expiry date.”},

    {“type”: “image_url”, “image_url”: {“url”: “https://example.com/label-001.jpg”}}

  ]},

  {“role”: “assistant”, “content”: “{\”batch\”: \”B2291\”, \”expiry\”: \”2027-03\”}”}

]}

Challenges to plan for

  • Data quality: Blurry, mislabelled or unrepresentative images lead to a worse model.
  • Labelling effort: Someone has to supply the right answer for every image.
  • Bias: If your examples miss certain conditions, the model will struggle with them.
  • Content screening: Images that break usage policies, or that contain certain sensitive content, can be excluded from training. Always check how many examples were actually used.
  • Evaluation: Keep a separate test set so you can prove the fine-tuned model is really better.

Steps Vision fine tuning

 

4. Model Distillation: Big-Model Quality at Small-Model Cost

Large models give excellent answers, but they cost more and respond more slowly. Small models are fast and cheap, but they can be less accurate on hard tasks.

Model distillation closes that gap. A large “teacher” model produces high-quality answers for your real tasks. You then use those answers to fine-tune a smaller “student” model, so it learns to respond like the teacher on your specific job.

How it works in practice

Distillation compared with other ways to shrink a model

Technique What it does Best for
Distillation Trains a small model to imitate a large one on your task Cutting cost while keeping quality on a specific job
Quantization Stores model numbers with fewer bits Running a model on smaller hardware
Pruning Removes parts of the model that matter least Reducing size for self-hosted models

The benefits are faster responses, lower cost per request, and less compute for the same workload. Evaluate carefully, because a distilled model only learns what is in your examples.

Step-by-Step: Try These Features in Microsoft Foundry

Prerequisites

  • An active Azure subscription (a free account works for learning).
  • Access to Azure OpenAI in Microsoft Foundry.
  • Python 3.9 or later and basic Python skills.
  • Familiarity with REST and JSON.
  • Visual Studio Code or another editor.

Services you will use

Service Purpose
Microsoft Foundry (Azure OpenAI) Model deployments, the Realtime API, prompt caching and fine-tuning
Azure Machine Learning Optional: experiment tracking and MLOps around your models
Foundry Tools (Vision) Optional: prebuilt vision capabilities for your images
Azure Monitor Tracking usage, latency and cost

Step 1: Create your Foundry resource and project

Before starting the deployment, make sure you have already created a Microsoft Foundry resource and a project.

If not, you can follow this Step-by-Step Guide to create the resource.

Step 2: Install the libraries

pip install openai azure-identity azure-ai-ml requests

Use a recent version of the openai package. Older versions do not support the newer parameters and events.

Step 3: Call a model with the v1 API

Create a client that points to your resource’s /openai/v1/ endpoint. Notice there is no api-version, and the deployment name goes in the model field.

import os

from openai import OpenAI

from azure.identity import DefaultAzureCredential, get_bearer_token_provider

token_provider = get_bearer_token_provider(

    DefaultAzureCredential(), “https://ai.azure.com/.default”

)

client = OpenAI(

    base_url=”https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/”,

    api_key=token_provider,

)

response = client.chat.completions.create(

    model=”YOUR-CHAT-DEPLOYMENT-NAME”,

    messages=[

        {“role”: “system”, “content”: “You are a helpful assistant.”},

        {“role”: “user”, “content”: “Explain prompt caching in one sentence.”},

    ],

)

print(response.choices[0].message.content)

Step 4: Connect to the Realtime API

The Realtime API keeps a live connection open instead of making one-off requests. This example uses a WebSocket connection with the OpenAI SDK and sends a text message to keep it simple. The same session can carry audio.

import asyncio, os

from openai import AsyncOpenAI

client = AsyncOpenAI(

    websocket_base_url=”wss://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1″,

    api_key=os.environ[“AZURE_OPENAI_API_KEY”],

)

async def main():

    async with client.realtime.connect(model=”YOUR-REALTIME-DEPLOYMENT-NAME”) as conn:

        await conn.session.update(session={

            “type”: “realtime”,

            “instructions”: “You are a friendly voice assistant.”,

        })

        await conn.conversation.item.create(item={

            “type”: “message”,

            “role”: “user”,

            “content”: [{“type”: “input_text”, “text”: “Say hello in one sentence.”}],

        })

        await conn.response.create()

        async for event in conn:

            if event.type == “response.output_text.delta”:

                print(event.delta, end=””)

            elif event.type == “response.done”:

                break

asyncio.run(main())

Tip: For browser or mobile apps, use WebRTC instead. Your backend requests a short-lived key from /openai/v1/realtime/client_secrets, and the browser connects with it. For phone calls, use SIP. Follow the matching Microsoft Learn quickstart for each.

Step 5: Structure your prompt for caching

Caching needs no special call. It depends on how you build the prompt. Keep the long, unchanging text at the start, and the changing user input at the end, then check the usage data.

LONG_INSTRUCTIONS = open(“policy_handbook.txt”).read()  # at least 1,024 tokens, never changes

def ask(question):

    return client.chat.completions.create(

        model=”YOUR-CHAT-DEPLOYMENT-NAME”,

        messages=[

            {“role”: “system”, “content”: LONG_INSTRUCTIONS},

            {“role”: “user”, “content”: question},

        ],

    )

first = ask(“How many leave days do I get?”)

second = ask(“What is the travel policy?”)

print(second.usage.prompt_tokens_details.cached_tokens)

On the second call, cached_tokens should be greater than zero. If it stays at zero, check that the first 1,024 tokens are identical and that the requests are close together in time.

Step 6: Prepare vision fine-tuning data

Create a .jsonl file where each line is one example, as shown in the vision fine-tuning section above. Include a variety of images and keep a separate set aside for testing. Then upload the file and start a fine-tuning job from the Foundry portal or the SDK.

training_file = client.files.create(

    file=open(“vision_train.jsonl”, “rb”),

    purpose=”fine-tune”,

)

print(training_file.id)

Step 7: Fine-tune a smaller model with distillation data

Save the best answers from your larger model as a JSONL file, upload it, and create a supervised fine-tuning job on the smaller model. Use the model and training type that Microsoft Foundry lists as supported for your region.

job = client.fine_tuning.jobs.create(

    model=”SUPPORTED-STUDENT-MODEL-ID”,

    training_file=training_file.id,

    suffix=”k21-distilled”,

    method={“type”: “supervised”, “supervised”: {“hyperparameters”: {

        “batch_size”: “auto”,

        “learning_rate_multiplier”: “auto”,

        “n_epochs”: “auto”,

    }}},

    extra_body={“trainingType”: “GlobalStandard”},

)

print(job.id)

Step 8: Verify everything works

  • The chat call in Step 3 returns an answer without errors.
  • The Realtime session in Step 4 connects and streams text back.
  • cached_tokens is above zero on repeat calls in Step 5.
  • Your fine-tuning jobs show a status of succeeded, and the fine-tuned model answers better than the base model on your test set.

A good test prompt for your fine-tuned model is one from your held-out test set, so you can compare its answer with the base model’s answer side by side.

Troubleshooting

Problem What to check
Authentication errors Confirm the endpoint, that your account has the Foundry User role, and that your token scope is https://ai.azure.com/.default
Realtime connection fails Use the /openai/v1/realtime GA endpoint, remove any api-version and OpenAI-Beta header, and use a current OpenAI SDK
Cached tokens always zero Make sure the prompt is at least 1,024 tokens, the start is identical, and requests are close in time
Unknown parameter errors Upgrade the openai package with pip install –upgrade openai
Fine-tuning file rejected Validate that every line is valid JSON in chat format, with enough examples and supported image types
Slow responses Pick a closer region, use a smaller model, or use WebRTC for client-side audio

A tip for your configuration: keep your endpoint and deployment names in environment variables, not in your code.

AZURE_OPENAI_ENDPOINT=”https://YOUR-RESOURCE-NAME.openai.azure.com”

CHAT_DEPLOYMENT=”YOUR-CHAT-DEPLOYMENT-NAME”

REALTIME_DEPLOYMENT=”YOUR-REALTIME-DEPLOYMENT-NAME”

Model Distillations

Understanding the Cost of These Features

Costs depend on the model, deployment type and region, so always check the current Azure OpenAI pricing page before you plan a budget. These are the things that drive your bill:

  • Model size and version: Larger models cost more per token.
  • Input and output tokens: Long prompts and long answers add up.
  • Audio: Realtime sessions use audio tokens, and transcription models are priced by duration.
  • Cached input: Cache reads on Standard deployments are billed at a discount on input pricing. Newer models can also charge for cache writes, so check the model’s details.
  • Fine-tuning: You pay for training, then for hosting the fine-tuned deployment.
  • Deployment type and region: Global Standard, Data Zone and Provisioned deployments are priced differently.
  • Concurrency: More simultaneous sessions need more quota.

Tip: Use Azure Cost Management and set budgets and alerts from day one. Delete test deployments, especially fine-tuned ones, when you finish a lab.

Certifications and Career Impact

Hands-on skills with realtime voice, caching and fine-tuning are in demand for AI engineer roles. These Microsoft certifications are the ones to look at:

Certification Why it helps
AI-901: Azure AI Fundamentals A friendly start with core AI concepts and Foundry
AI-103: Azure AI Apps and Agents Developer Associate Building generative AI apps, agents and multimodal solutions
AI-300: MLOps Engineer Associate Training, deploying, monitoring and optimising models in production

Certifications open doors, but projects get you hired. Build a small voice assistant or a document reader with the steps above and add it to your portfolio.

When to Use Which Feature

If your goal is… Use…
Natural voice conversations or live translation Realtime API
Lower cost and faster replies when prompts repeat Prompt caching
Better accuracy on your own images or forms Vision fine-tuning
A cheaper, faster model for a specific task Model distillation

They also work well together. A voice agent can use a cached system prompt for speed, call tools for live data, and run on a distilled model to keep costs under control.

Safety and Responsible Use

Voice and image features bring extra responsibility. Plan for these risks before you launch:

  • Voice impersonation: Do not use a synthetic voice to pretend to be a real person. Tell users when they are talking to an AI.
  • Harmful live conversations: Use content filters and monitoring, and give users a way to reach a human.
  • Misleading media: Label AI-generated audio and images clearly.
  • Data exposure: Do not train on personal data without permission, and apply least-privilege access.
  • Human review: Keep a person in the loop for high-stakes decisions.

Azure AI Content Safety and the safety tools in Microsoft Foundry can help you enforce these rules.

Conclusion

The latest innovations from Azure AI, Realtime API, Prompt Caching, Vision Fine-Tuning, and Model Distillation—offer developers powerful tools to enhance the performance and scalability of AI applications. These features help developers create more immersive, efficient, and cost-effective solutions while maintaining the flexibility to fine-tune and optimize models for specific use cases. Whether you are working on multimodal conversations, reducing costs with prompt caching, or enhancing your models’ performance, these tools will provide you with the resources to elevate your AI projects within Azure.

Frequently Asked Questions

What is the Azure OpenAI Realtime API?

The Azure OpenAI Realtime API is an API that allows applications to stream audio or text to an AI model and receive streamed responses with very low latency. It supports function calling and session memory, making it suitable for building voice assistants, real-time AI agents, and interactive conversational applications.

Why use the Realtime API instead of speech-to-text, a chat model, and text-to-speech?

The Realtime API reduces latency compared to the traditional chained approach of speech-to-text, a chat model, and text-to-speech. Since it handles speech input and response generation through a single connection, conversations feel faster, smoother, and more natural.

How do I connect to the Azure OpenAI Realtime API?

You can connect to the Azure OpenAI Realtime API using WebRTC for browser and mobile applications, WebSocket for server-to-server connections, or SIP for phone calls. These connection methods use the GA /openai/v1/realtime endpoint to establish real-time communication with the AI model.

Do I need to change my code to use prompt caching?

No, you do not need to make code changes to enable prompt caching for supported models because caching is enabled by default. However, you should structure prompts so that stable and reusable text appears first and contains at least 1,024 tokens to improve caching effectiveness.

How do I know if prompt caching is working?

You can check whether prompt caching is working by inspecting the cached_tokens field inside prompt_tokens_details in the API response. If the cached_tokens value is greater than zero, it means that a portion of your prompt was successfully served from the cache.

When should I use vision fine-tuning?

You should use vision fine-tuning when a general-purpose vision model repeatedly misinterprets images that are important to your business. Examples include specialized documents, product labels, and business-specific images. Having a sufficient number of high-quality labelled examples is important for achieving better model performance.

What is model distillation?

Model distillation is a technique for training a smaller AI model using the outputs and knowledge of a larger model on specific tasks. It helps organizations achieve similar performance for targeted applications while reducing computational costs, response latency, and overall AI deployment expenses.

Which Azure certification should I take for these skills?

AI-103 is the closest match for professionals interested in building AI applications and agents. AI-901 is a good starting point for beginners who want to understand AI fundamentals, while AI-300 is suitable for professionals interested in MLOps and production AI workflows.

Next Task: Enhance Your Azure AI/ML Skills

Ready to elevate your Azure AI/ML expertise? Join our free class and gain hands-on experience with expert guidance.

Register Now: Free Azure AI/ML-Class

Take this opportunity to learn from industry experts and advance your AI career. Click the image below to enroll:

Azure AI

Picture of Atul Kumar

Atul Kumar

Share Post Now :

HOW TO GET HIGH PAYING JOBS IN AWS CLOUD

Even as a beginner with NO Experience Coding Language

Explore Free course Now