Velamuvi AIAcademy

Lesson 4 of 39 · Getting Started

Messages, Content and Streaming

Work with messages in Microsoft Agent Framework: roles, content types, sending images and files, streaming responses, finish reasons and reading citations.

  • 12 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Build messages with the right roles and pass text, one message or a whole list to an agent
  • Name the main content types a message can contain
  • Send images and files to a model that understands them
  • Stream a response piece by piece and still get the complete response
  • Check why a model stopped and read the citations in a reply

Messages and roles

Everything an agent sends to or receives from a model is a list of messages.

RoleWhoExample
systemInstructions for the model“You are Velo's shop assistant.”
userThe person using your app“Do you sell helmets?”
assistantThe model (or agent)“Yes, from 39 EUR.”
toolThe result of a tool the model called{"price": 39}

agent.run() accepts several kinds of input, described by the type AgentRunInputs: a string, one Message, a Content, or a list of them.

import asyncio
from agent_framework import Agent, AgentRunInputs, Message, Role
from agent_framework.openai import OpenAIChatClient

async def main():
    agent = Agent(client=OpenAIChatClient(model="MODEL_NAME"), instructions="You are Velo's shop assistant. Be brief.")

    # 1. A string becomes one user message
    print((await agent.run("Do you sell helmets?")).text)

    # 2. A list of messages: an earlier exchange, then the new question
    conversation: AgentRunInputs = [
        Message("user", ["I'm looking at the Commuter 3 e-bike."]),
        Message("assistant", ["Good choice! It has a range of about 70 km."]),
        Message("user", ["Does it come with lights?"]),
    ]
    print((await agent.run(conversation)).text)

    note = Message(Role("user"), ["Thanks!"], author_name="ana")    # a role is a plain string
    print(note.role, note.author_name, note.text)

asyncio.run(main())
Output
Yes, from 39 EUR, in four sizes.
Yes: the Commuter 3 has built-in front and rear lights powered by its battery.
user ana Thanks!
  • A string becomes one user message.
  • A list of messages lets you pass an earlier exchange. That's how you'd hand over a conversation stored somewhere else, or give the model a few worked examples before the real question.
  • A role is a plain string; Role is its type. author_name records who wrote a message, which matters when several people or agents share a conversation.

Content: what a message is made of

A message holds a list of contents, each with a type:

from agent_framework import Content, Message

question = Message("user", [
    "Which part is broken?",                                                    # a string becomes text content
    Content.from_uri("https://velo.example/photos/brake.jpg", media_type="image/jpeg"),
])
for part in question.contents:
    print(part.type, "|", part.text or part.uri)

answer = Message("assistant", [
    Content.from_text_reasoning(text="The pad in the photo is thinner than 1 mm."),   # reasoning, if the model shares it
    Content.from_text("Your front brake pad is worn out: replace it before your next ride."),
    Content.from_usage({"input_token_count": 812, "output_token_count": 16, "total_token_count": 828}),
])
print([part.type for part in answer.contents])
print(answer.text)                                     # .text joins only the text parts
Output
text | Which part is broken?
uri | https://velo.example/photos/brake.jpg
['text_reasoning', 'text', 'usage']
Your front brake pad is worn out: replace it before your next ride.
typeCreated withHolds
textContent.from_text(...) or a plain stringText
uriContent.from_uri(url, media_type=...)A link to an image, audio file or document
dataContent.from_data(bytes, media_type)A file's bytes, stored as a data URI
hosted_fileContent.from_hosted_file(file_id)A file already uploaded to the provider
text_reasoningContent.from_text_reasoning(text=...)The model's reasoning, when a provider shares it
function_call, function_resultContent.from_function_call(...), Content.from_function_result(...)A tool call requested by the model, and its result (lesson Function Tools)
function_approval_request, function_approval_responsecreated by the frameworkA tool call waiting for a person's approval (lesson Tool Approval and User Input)
usageContent.from_usage(...)Token counts
errorContent.from_error(message=...)An error reported by the service

There are more types for hosted tools, such as code_interpreter_tool_call, search_tool_result, mcp_server_tool_call and shell_tool_call; later lessons show them. message.text joins only the text contents, so reasoning and usage don't end up in your output.

Sending images and files

Models that understand images (often called vision or multimodal models) accept them as content. Here the photo is a file on your computer:

import asyncio
from pathlib import Path
from agent_framework import Agent, Content, Message, detect_media_type_from_base64
from agent_framework.openai import OpenAIChatClient

async def main():
    agent = Agent(client=OpenAIChatClient(model="MODEL_NAME"), instructions="You are a bike mechanic. One sentence.")

    photo = Path("bike.png").read_bytes()                            # a photo on your computer
    media_type = detect_media_type_from_base64(data_bytes=photo)     # worked out from the file's first bytes
    print("sending", media_type, f"({len(photo)} bytes)")
    question = Message("user", ["What should I fix first?", Content.from_data(photo, media_type)])
    print((await agent.run(question)).text)

asyncio.run(main())
Output
sending image/png (135 bytes)
The rear tyre looks flat, so pump it up and check it for a puncture first.
  • Content.from_data(bytes, media_type) sends the file's bytes. The media type, such as image/png or application/pdf, is required.
  • detect_media_type_from_base64 works the type out from the first bytes of the file (it also accepts base64 text or a data URI). It recognises images, audio, video and documents, not text formats.
  • For a file that's already online, Content.from_uri(url, media_type=...) sends just the link, which keeps the request small.

Check your model's documentation for what it supports: most current models read images, many read PDFs, fewer read audio. Images also cost tokens, often hundreds per picture.

Streaming a response

A long answer can take many seconds. With streaming, your app shows the answer while it's being written, which feels much faster. Here is the idea in plain Python:

Try it yourselfPython
# Streaming in plain Python: the model's answer arrives in small pieces (updates).
# You show each piece as soon as it comes, and join them at the end into the full response.
def fake_model_stream(answer):
    for word in answer.split(" "):
        yield word + " "                 # a real model sends a piece every few milliseconds
    yield ""                             # the last update often carries no text, only usage data

updates = []
for piece in fake_model_stream("Take the riverside path to Foz and watch the sunset."):
    print(piece, end="|")                # | marks where each piece ends
    updates.append(piece)
print()
final_text = "".join(updates).strip()
print(f"{len(updates)} updates, final response: {final_text!r}")

With an agent, pass stream=True:

import asyncio
from agent_framework import Agent, AgentResponseUpdate, ResponseStream
from agent_framework.openai import OpenAIChatClient

async def main():
    agent = Agent(client=OpenAIChatClient(model="MODEL_NAME"), instructions="You suggest bike routes in Porto.")
    stream: ResponseStream = agent.run("Suggest a relaxed evening ride.", stream=True)
    async for update in stream:                       # pieces arrive while the model is still writing
        print(update.text, end="|", flush=True)       # | shows where each piece ends
    print()
    final = await stream.get_final_response()         # the whole AgentResponse, built from the pieces
    print(final.text)
    first: AgentResponseUpdate = stream.updates[0]
    print(len(stream.updates), "updates; the first was", repr(first.text), "from the", first.role)

asyncio.run(main())
Output
Ride |the |riverside |path |to |Foz |at |sunset.||
Ride the riverside path to Foz at sunset.
9 updates; the first was 'Ride ' from the assistant
  • With stream=True, run() returns a ResponseStream straight away, without await. You loop over it with async for.
  • Each piece is an AgentResponseUpdate with a role, its contents and its text. Some updates carry no text: the last one here only closes the stream.
  • await stream.get_final_response() returns the normal AgentResponse, built from all the updates; stream.updates lists them. If you never loop, get_final_response() reads the whole stream for you.
  • A stream can only be read once. A second async for gets nothing.

A chat client streams the same way, with ChatResponseUpdate pieces and a ChatResponse at the end:

import asyncio
from agent_framework import ChatResponse, ChatResponseUpdate, Message
from agent_framework.openai import OpenAIChatClient

async def main():
    client = OpenAIChatClient(model="MODEL_NAME")
    stream = client.get_response([Message("user", ["Name three parts of a bike."])], stream=True)
    async for update in stream:
        assert isinstance(update, ChatResponseUpdate)
        print(update.text, end="")
    print()
    response: ChatResponse = await stream.get_final_response()
    print("finish reason:", response.finish_reason, "| tokens:", response.usage_details["total_token_count"])

asyncio.run(main())
Output
Frame, chain and handlebars.
finish reason: stop | tokens: 21

Why the model stopped

Every response has a finish_reason, a FinishReason value: stop (the answer is complete), length (it hit max_tokens), tool_calls (the model wants to call tools) or content_filter (the provider's safety filter blocked it).

import asyncio
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient

async def main():
    agent = Agent(client=OpenAIChatClient(model="MODEL_NAME"), instructions="You explain bike tech.")
    response = await agent.run("Explain gear ratios.", options={"max_tokens": 20})
    print(response.finish_reason, "->", response.text)
    if response.finish_reason == "length":            # cut off: the answer hit max_tokens
        response = await agent.run("Explain gear ratios.", options={"max_tokens": 200})
        print(response.finish_reason, "->", response.text)

asyncio.run(main())
Output
length -> A gear ratio compares the teeth on the front chainring with
stop -> A gear ratio compares the teeth on the front chainring with those on the rear sprocket: 40/20 = 2 turns of the wheel per pedal turn.

A length answer is cut off in the middle, so never show it as if it were complete: retry with a higher limit, or ask for a shorter answer.

Citations

When a model answers from sources, for example after a web or file search, its text can carry annotations: citations saying where a part of the answer came from. Each Annotation has a title, a url or file_id, a snippet, and annotated_regions with TextSpanRegion positions in the text:

from agent_framework import Annotation, Content, Message, TextSpanRegion

text = "E-bikes cost 35 EUR a day at Velo."
reply = Message("assistant", [Content.from_text(text, annotations=[Annotation(
    type="citation",
    title="Velo prices",
    url="https://velo.example/prices",
    snippet="E-bike rental: 35 EUR per day",
    annotated_regions=[TextSpanRegion(type="text_span", start_index=0, end_index=len(text) - 1)],
)])])

for content in reply.contents:                          # how to show sources under an answer
    for note in content.annotations or []:
        region = note["annotated_regions"][0]
        quoted = content.text[region["start_index"]:region["end_index"]]
        print(f'"{quoted}" -> {note["title"]} ({note["url"]})')
Output
"E-bikes cost 35 EUR a day at Velo" -> Velo prices (https://velo.example/prices)

Here the citation is built by hand to show its shape; in the lesson Hosted Tools: Code, Web, Files and Images it comes from a real search. Showing sources lets readers check the answer, which matters most when it gives prices, rules or facts.

Common mistakes

Practice exercise

Rebuild a streamed answer from its updates.

Your solutionPython
updates = ["Clean ", "", "the chain, ", None, "then ", "oil it", "."]   # None or "" = no text

# Join the text pieces into the final answer and count the updates that carried text.
# Print the answer, then "<n> text updates".
Knowledge check

An agent's response has finish_reason 'length'. What happened?

Summary

  • A Message has a role (system, user, assistant, tool) and a list of contents; agent.run() accepts a string, a message or a list (AgentRunInputs).
  • Content types include text, uri, data, hosted files, reasoning, function calls and results, usage and errors; message.text joins only the text.
  • Send images and files with Content.from_data or Content.from_uri; detect_media_type_from_base64 finds the media type.
  • run(..., stream=True) returns a ResponseStream of updates; get_final_response() gives the complete response.
  • Check finish_reason, and read annotations to show where an answer came from.

Next: Other Agent Types: Foundry, Copilot and Claude.

Finished reading? Tick it off to track your progress.