Lesson 8 of 39 · Tools
Hosted Tools: Code, Web, Files and Images
Use hosted tools in Microsoft Agent Framework: code interpreter, web search with citations, file search, image generation, computer use and client support.
- 13 min read
- Intermediate
- Reviewed
- Explain what hosted tools are and how they differ from function tools
- Check which tools a chat client supports with the Supports* protocols
- Let an agent run Python with the code interpreter and search the web with citations
- Search your own documents with file search, and generate images
- Handle the safety checks of computer use
Tools that run at the provider
With function tools, your program runs the code. Some providers also run tools on their servers. You switch such a tool on and the model uses it, without any function from you.
| Function tool | Hosted tool | |
|---|---|---|
| Who runs it | Your program | The provider |
| What you write | A Python function | One line that switches it on |
| What the framework does | Runs the tool loop | Passes the tool to the provider, then reads the results |
| Works with | Every chat client with tool calling | Only clients whose provider offers that tool |
Which client supports which tool
Each hosted tool has a protocol, a description of the method a client needs to offer it. isinstance(client, SupportsWebSearchTool) checks that the client has a get_web_search_tool() method. Here's that idea in plain Python:
# How isinstance(client, SupportsWebSearchTool) decides: it only checks that the client HAS the
# right method, here get_web_search_tool. Plain-Python stand-ins for two chat clients:
class ResponsesClient: # like OpenAIChatClient
@staticmethod
def get_web_search_tool():
return {"type": "web_search"}
@staticmethod
def get_code_interpreter_tool():
return {"type": "code_interpreter"}
class LocalModelClient: # like OllamaChatClient: no hosted tools
pass
def supports(client, method_name):
return callable(getattr(client, method_name, None))
for client in [ResponsesClient(), LocalModelClient()]:
found = [name for name in ("web_search", "code_interpreter") if supports(client, f"get_{name}_tool")]
print(f"{type(client).__name__}: {found or 'no hosted tools'}")
if supports(client, "get_web_search_tool"):
print(" tool to pass to Agent:", client.get_web_search_tool())With real clients:
from agent_framework import (SupportsCodeInterpreterTool, SupportsFileSearchTool,
SupportsImageGenerationTool, SupportsWebSearchTool)
from agent_framework.openai import OpenAIChatClient, OpenAIChatCompletionClient
for client in [OpenAIChatClient(model="MODEL_NAME"), OpenAIChatCompletionClient(model="MODEL_NAME")]:
supported = [protocol.__name__ for protocol in (SupportsCodeInterpreterTool, SupportsWebSearchTool,
SupportsFileSearchTool, SupportsImageGenerationTool) if isinstance(client, protocol)]
print(type(client).__name__, supported)
client = OpenAIChatClient(model="MODEL_NAME")
if isinstance(client, SupportsWebSearchTool): # safe to ask for the tool
print(client.get_web_search_tool())OpenAIChatClient ['SupportsCodeInterpreterTool', 'SupportsWebSearchTool', 'SupportsFileSearchTool', 'SupportsImageGenerationTool']
OpenAIChatCompletionClient ['SupportsWebSearchTool']
{'type': 'web_search'}The get_..._tool() methods return a tool configuration, a small dictionary or provider object that you put in tools=[...] next to your function tools. They're static methods, so OpenAIChatClient.get_web_search_tool() works without a client object too. In version 1.26.0:
| Client | SupportsCodeInterpreterTool | SupportsWebSearchTool | SupportsFileSearchTool | SupportsImageGenerationTool |
|---|---|---|---|---|
OpenAIChatClient, FoundryChatClient | yes | yes | yes | yes |
AnthropicClient (and its Bedrock, Vertex and Foundry versions) | yes | yes | - | - |
GeminiChatClient | yes | yes | yes | - |
OpenAIChatCompletionClient, FoundryLocalClient | - | yes | - | - |
MistralChatClient, OllamaChatClient, BedrockChatClient | - | - | - | - |
Clients offer more tools than these four. FoundryChatClient adds, for example, get_bing_grounding_tool, get_azure_ai_search_tool, get_sharepoint_tool and get_browser_automation_tool, and GeminiChatClient adds get_maps_grounding_tool. In Microsoft Foundry you can also bundle tools into a toolbox and connect an agent to it with FoundryToolbox, which works like the MCP tools in the lesson MCP Tools.
Code interpreter
The code interpreter gives the model a Python sandbox at the provider. The model writes code, runs it and reads the output. Models are bad at exact arithmetic in their heads, so this matters for anything with numbers:
import asyncio
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient
async def main():
client = OpenAIChatClient(model="MODEL_NAME")
agent = Agent(
client=client,
instructions="You are Velo's data analyst. Use Python for every calculation.",
tools=[client.get_code_interpreter_tool()],
default_options={"include": ["code_interpreter_call.outputs"]}, # OpenAI: also return the output
)
response = await agent.run("E-bike rentals this week: 12, 15, 9, 22, 30, 41, 38. Average and best day?")
for message in response.messages:
for content in message.contents:
if content.type == "code_interpreter_tool_call":
print("code:", content.inputs[0].text)
elif content.type == "code_interpreter_tool_result":
print("output:", [output.text for output in content.outputs if output.type == "text"])
print(response.text)
asyncio.run(main())code: rentals = [12, 15, 9, 22, 30, 41, 38] print(sum(rentals) / len(rentals), rentals.index(max(rentals)) + 1) output: ['23.857142857142858 6'] The average was about 23.9 rentals a day, and the best day was day 6 (Saturday) with 41.
client.get_code_interpreter_tool()switches the tool on. With OpenAI,file_ids=[...]makes files you uploaded available to the code, for example a spreadsheet to analyse.- The response holds a
code_interpreter_tool_callcontent (the code, ininputs) and acode_interpreter_tool_resultcontent (theoutputs). - OpenAI only returns the outputs when you ask with the OpenAI option
include, as indefault_optionsabove. Without it you still get the answer, but not the printed output.
Web search
Web search lets the model look up current information, with citations:
import asyncio
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient
async def main():
client = OpenAIChatClient(model="MODEL_NAME")
agent = Agent(
client=client,
instructions="You tell cyclists about events in Porto. Always cite your sources.",
tools=[client.get_web_search_tool(user_location={"city": "Porto", "country": "PT"})],
)
response = await agent.run("Are there any cycling events in Porto this month?")
print(response.text)
searches = [c for m in response.messages for c in m.contents if c.type == "search_tool_call"]
print(len(searches), "search(es)")
for content in response.messages[-1].contents:
for citation in content.annotations or []: # where each part of the answer came from
print("-", citation["title"], citation["url"])
asyncio.run(main())Yes: the Porto Bike Tour rides through the city on the 14th, and the Douro Gravel meet-up starts in Gaia on the 21st. 1 search(es) - Porto Bike Tour 2026 https://bike-tour.example.pt/ - Douro Gravel meet-ups https://douro-gravel.example.com/events
user_locationmakes results local: “events near me” means Porto. OpenAI also acceptssearch_context_size("low","medium"or"high": how much found text the model reads) andfilters.- Each search appears as a
search_tool_callcontent withtool_name"web_search", plus asearch_tool_result. - The citations are annotations on the text, as in the lesson Messages, Content and Streaming: each has a
title, aurland the part of the text it supports. Show them, so readers can check the answer.
File search
File search answers from your own documents. You upload files to a vector store, a provider-side index that finds the passages most similar in meaning to the question (the lesson Embeddings, Vector Stores and RAG explains how). Then the model searches it:
import asyncio
from pathlib import Path
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient
async def main():
client = OpenAIChatClient(model="MODEL_NAME")
sdk = client.client # the OpenAI SDK client inside
store = await sdk.vector_stores.create(name="velo-manuals")
with Path("commuter3-manual.pdf").open("rb") as manual: # split into chunks and indexed
await sdk.vector_stores.files.upload_and_poll(vector_store_id=store.id, file=manual)
agent = Agent(
client=client,
instructions="Answer from Velo's bike manuals and say which manual you used.",
tools=[client.get_file_search_tool(vector_store_ids=[store.id], max_num_results=3)],
)
response = await agent.run("How should I store the Commuter 3 battery in winter?")
print(response.text)
for content in response.messages[-1].contents:
for citation in content.annotations or []:
print("source:", citation["url"], "|", citation["file_id"]) # file name and file ID
await sdk.vector_stores.delete(store.id) # stored files are billed per day
asyncio.run(main())Store it indoors between 10 and 20 °C, charged to about 60%, and top it up every two months (Commuter 3 manual, page 18). source: commuter3-manual.pdf | file_m1
client.clientis the official OpenAI SDK client insideOpenAIChatClient. Itsvector_storesAPI creates the store and uploads files;upload_and_pollwaits until a file is indexed.get_file_search_tool(vector_store_ids=[...], max_num_results=3)lets the model search those stores and read at most 3 passages per search.- For files, a citation's
urlholds the file name andfile_idthe provider's ID. - Create the store once and reuse it; uploading on every run is slow and costs money. Delete stores you no longer need.
A related helper: ContentUnderstandingContextProvider can upload analysed documents to a vector store for you, configured with a FileSearchConfig and a FileSearchBackend (lesson Context Providers and Long-Term Memory). Don't confuse hosted file search with FileSearchMatch and FileSearchResult: those describe matches of the harness's local file tools (lesson Harness Agents: Todos, Modes and File Memory).
Image generation
Image generation lets the model create pictures as part of its answer:
import asyncio
import base64
from pathlib import Path
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient
async def main():
client = OpenAIChatClient(model="MODEL_NAME")
agent = Agent(
client=client,
instructions="You design posters for Velo, a bike shop in Porto.",
tools=[client.get_image_generation_tool(size="1024x1536", quality="medium")],
)
response = await agent.run("Make a poster for our Sunday group ride along the Douro river.")
for message in response.messages:
for content in message.contents:
if content.type == "image_generation_tool_result":
image = content.outputs # a data content: the image itself
image_bytes = base64.b64decode(image.uri.split(",", 1)[1]) # the part after "base64,"
Path("poster.png").write_bytes(image_bytes)
print("saved poster.png, type", image.media_type)
print(response.text)
asyncio.run(main())saved poster.png, type image/png Here's your poster: riders on the riverside path at sunrise, with the date and the meeting point at Velo.
get_image_generation_tool()takes options such assize,quality,output_formatandbackground("transparent"for logos).- The image arrives in an
image_generation_tool_resultcontent. Itsoutputsis adatacontent whoseuriis a data URI: the textdata:image/png;base64,followed by the image in base64. Decoding the part after the comma gives the file's bytes.
Computer use and safety checks
Computer use lets a model operate a screen: it asks for clicks and key presses, your program carries them out, for example in a browser, and sends back a screenshot. It's experimental in 1.26.0 (feature COMPUTER_USE), and it needs a model trained for it.
The provider checks each step. When something looks risky, such as a web page that contains instructions aimed at the model, it attaches a safety check, a ComputerSafetyCheck with an id, a code and a message. The framework never accepts these for you: a person must review them, and only the checks they accepted go back with the result.
import asyncio
from agent_framework import Agent, ComputerSafetyCheck, Content, Message
from agent_framework.openai import OpenAIChatClient
def take_actions(actions: list[dict]) -> bytes:
"""Your part: do the clicks and typing in a browser (for example with Playwright), return a PNG screenshot."""
raise NotImplementedError
async def main():
client = OpenAIChatClient(model="MODEL_NAME") # a model trained for computer use
agent = Agent(client=client, instructions="You help Velo's staff use the booking website.",
tools=[client.get_computer_tool()])
session = agent.create_session()
response = await agent.run("Open the bookings page and list Thursday's free slots.", session=session)
while calls := [r for r in response.user_input_requests if r.type == "computer_tool_call"]:
results = []
for request in calls:
checks: list[ComputerSafetyCheck] = request.pending_safety_checks or []
for check in checks: # a person must review every warning
print("WARNING:", check["code"], "-", check["message"])
if checks and input("Continue anyway? (y/n) ") != "y":
return
results.append(Content.from_computer_tool_result(
call_id=request.call_id,
screenshot=Content.from_data(take_actions(request.actions), "image/png"),
acknowledged_safety_checks=checks, # only checks a person accepted
))
response = await agent.run(Message("user", results), session=session)
print(response.text)
asyncio.run(main())WARNING: malicious_instructions - The page contains text that tries to give the model instructions. Continue anyway? (y/n) y Thursday's free slots are 10:00 and 15:00.
- Each step is a
computer_tool_callinresponse.user_input_requests, with theactionsto perform and thepending_safety_checks. Content.from_computer_tool_result(call_id=..., screenshot=..., acknowledged_safety_checks=...)sends the screenshot and the accepted checks back, in the same session.- Run computer use in an isolated browser or virtual machine without your passwords, because the model clicks whatever it decides to click.
Common mistakes
Build the list of sources that an app shows under a web search answer.
citations = [
{"title": "Porto Bike Tour 2026", "url": "https://bike-tour.example.pt/"},
{"title": "Douro Gravel meet-ups", "url": "https://douro-gravel.example.com/events"},
{"title": "Porto Bike Tour 2026", "url": "https://bike-tour.example.pt/"},
{"title": "Porto city events", "url": "https://visit.example.pt/events"},
]
# A web search answer often cites the same page twice. Print each source once, in the order
# it first appears, numbered from 1, as: [1] title - url
What is the main difference between a hosted tool and a function tool?
Summary
- Hosted tools run at the provider: you add a tool configuration from
client.get_..._tool()totools=[...]and read the results in the response. SupportsCodeInterpreterTool,SupportsWebSearchTool,SupportsFileSearchToolandSupportsImageGenerationTooltell you whether a client offers a tool.- The code interpreter runs Python; web search and file search return answers with citation annotations; file search needs a vector store.
- Image generation returns the picture as a data content; computer use returns actions with
ComputerSafetyCheckwarnings that a person must accept. - Hosted tools cost extra per use, so check pricing, and try them on a free tier first.
Next: Shell and Sandboxed Code Execution.
Finished reading? Tick it off to track your progress.