Tool calling and dispatch

Tool calling is how your agents run functions/ get access to your internal systems. Examples include things like:

  • Looking up a customer in your CRM system
  • Closing a support ticket
  • Getting weather information

This guide will quickly teach you how to expose tools from any of the SDKs.

Your first tool

Here's a minimal weather lookup example:

Node.js
import { Client } from "@stream-io/stream-agents";
import { z } from "zod";

// Reads STREAM_ACCELERATION_URL, STREAM_API_KEY and STREAM_API_SECRET from the environment.
const client = new Client();

// Registered once for the app. Each agent whose agent.yaml names it in a tool group gets it.
client.tools.register({
  name: "weather_lookup",
  description: "Look up the current weather for a location",
  parameters: z.object({
    location: z.string().describe("a city or region"),
  }),
  run: async ({ location }) => {
    const response = await fetch(
      `https://wttr.in/${encodeURIComponent(location)}?format=3`,
    );
    if (!response.ok) throw new Error(`wttr.in answered ${response.status}`);
    return response.text();
  },
});

// Run every call of weather_lookup here, from any agent's session, wherever it was opened.
await client.runDispatch();
Python
import asyncio

import httpx
from vision_agents.plugins import stream

# Reads STREAM_ACCELERATION_URL, STREAM_API_KEY and STREAM_API_SECRET from the environment.
client = stream.Client()


# Registered once for the app. Each agent whose agent.yaml names it in a tool group gets it.
@client.tools.register()
async def weather_lookup(location: str) -> str:
    """Look up the current weather for a location.

    Args:
        location: a city or region.
    """
    async with httpx.AsyncClient() as http:
        response = await http.get(f"https://wttr.in/{location}", params={"format": "3"})
        response.raise_for_status()
        return response.text


async def main() -> None:
    # Run every call of weather_lookup here, from any agent's session, wherever it was opened.
    await client.run_dispatch()


if __name__ == "__main__":
    asyncio.run(main())
Ruby
require "net/http"
require "getstream/vision_agents"

# Reads STREAM_ACCELERATION_URL, STREAM_API_KEY and STREAM_API_SECRET from the environment.
client = GetStream::VisionAgents::Client.new

# Registered once for the app. Each agent whose agent.yaml names it in a tool group gets it.
client.tools.register(
  "weather_lookup",
  description: "Look up the current weather for a location",
  params: { location: "a city or region" },
) do |location:|
  response = Net::HTTP.get_response(URI("https://wttr.in/#{URI.encode_uri_component(location)}?format=3"))
  raise "wttr.in answered #{response.code}" unless response.is_a?(Net::HTTPSuccess)

  response.body
end

# Run every call of weather_lookup here, from any agent's session, wherever it was opened.
client.run_dispatch
PHP
<?php

declare(strict_types=1);

use GetStream\VisionAgents\Client;
use GetStream\VisionAgents\Tools;

require __DIR__ . '/vendor/autoload.php';

// Reads STREAM_ACCELERATION_URL, STREAM_API_KEY and STREAM_API_SECRET from the environment.
$client = new Client();

// Registered once for the app. Each agent whose agent.yaml names it in a tool group gets it.
$client->tools->register(
    name: 'weather_lookup',
    description: 'Look up the current weather for a location',
    parameters: Tools::strings(['location' => 'a city or region']),
    run: function (array $args): string {
        $weather = file_get_contents('https://wttr.in/' . rawurlencode($args['location']) . '?format=3');
        if ($weather === false) {
            throw new RuntimeException('wttr.in did not answer');
        }
        return $weather;
    },
);

// Run every call of weather_lookup here, from any agent's session, wherever it was opened.
$client->runDispatch();
Go
package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"

	"github.com/GetStream/Vision-Agents/sdks/go/client"
	"github.com/GetStream/Vision-Agents/sdks/go/stream"
	"github.com/GetStream/Vision-Agents/sdks/go/tools"
)

type WeatherLookup struct {
	Location string `json:"location" jsonschema:"description=a city or region"`
}

func weatherLookup(ctx context.Context, in WeatherLookup) (any, error) {
	address := "https://wttr.in/" + url.PathEscape(in.Location) + "?format=3"
	request, err := http.NewRequestWithContext(ctx, http.MethodGet, address, nil)
	if err != nil {
		return nil, err
	}
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()
	if response.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("wttr.in answered %s", response.Status)
	}
	body, err := io.ReadAll(response.Body)
	return string(body), err
}

func main() {
	// Reads STREAM_ACCELERATION_URL, STREAM_API_KEY and STREAM_API_SECRET from the environment.
	api, err := client.New(stream.Backend{})
	if err != nil {
		log.Fatal(err)
	}

	// Registered once for the app. Each agent whose agent.yaml names it in a tool group gets it.
	err = tools.Register(api.Tools(), "weather_lookup", "Look up the current weather for a location", weatherLookup)
	if err != nil {
		log.Fatal(err)
	}

	// Run every call of weather_lookup here, from any agent's session, wherever it was opened.
	log.Fatal(api.RunDispatch(context.Background()))
}
.NET
using System.ComponentModel;
using GetStream.VisionAgents;

using var http = new HttpClient();
// Reads STREAM_ACCELERATION_URL, STREAM_API_KEY and STREAM_API_SECRET from the environment.
using var client = new VisionAgentsClient();

// Registered once for the app. Each agent whose agent.yaml names it in a tool group gets it.
client.Tools.Register<WeatherLookup, string>("weather_lookup",
    "Look up the current weather for a location",
    (lookup, cancellationToken) => http.GetStringAsync(
        $"https://wttr.in/{Uri.EscapeDataString(lookup.Location)}?format=3", cancellationToken));

// Run every call of weather_lookup here, from any agent's session, wherever it was opened.
await client.RunDispatchAsync();

record WeatherLookup([Description("a city or region")] string Location);
Rust
use serde::Deserialize;
use vision_agents::schemars::JsonSchema;
use vision_agents::Client;

#[derive(Deserialize, JsonSchema)]
#[schemars(crate = "vision_agents::schemars")]
struct WeatherLookup {
    /// a city or region
    location: String,
}

#[tokio::main]
async fn main() -> vision_agents::Result<()> {
    // Reads STREAM_ACCELERATION_URL, STREAM_API_KEY and STREAM_API_SECRET from the environment.
    let client = Client::from_env()?;

    // Registered once for the app. Each agent whose agent.yaml names it in a tool group gets it.
    client.tools().register_typed(
        "weather_lookup",
        "Look up the current weather for a location",
        async |args: WeatherLookup| {
            let mut address = reqwest::Url::parse("https://wttr.in/?format=3").map_err(|error| error.to_string())?;
            address.path_segments_mut().map_err(|_| "wttr.in has no path")?.pop_if_empty().push(&args.location);
            let response = reqwest::get(address)
                .await
                .and_then(|response| response.error_for_status())
                .map_err(|error| error.to_string())?;
            response.text().await.map_err(|error| error.to_string())
        },
    );

    // Run every call of weather_lookup here, from any agent's session, wherever it was opened.
    client.run_dispatch().await
}

The dispatch above makes your tool available to agents. Update agent.yaml to have your agent use the tool.

name: my-agent
tools:
  - name: weather
    tools: [weather_lookup]
    loading: full

loading is full (the whole tool up front), summary (its first description line and argument names) or deferred (found by search when the model needs it). Choosing how a tool loads covers which option is best to pick.

With the code above running, sync your agent and talk to it:

getstream agents test my-agent --sync

Ask "What's the weather in Amsterdam?" to see the agent call weather_lookup.

When a tool fails

The model is told the message of the error a tool throws. When wttr.in is down, the agent says it couldn't get the weather instead of guessing, so throw words the model can pass on.

The model may repeat that message to the person, and the conversation keeps it. An error from a library your tool calls can name an internal host, a table or a value from a record, so catch those in the tool and throw your own words.

Info:

In JavaScript, setOnError does this for every tool at once. We recommend passing on only an error class of your own, thrown with words meant for the model:

class ToolError extends Error {}

client.tools.setOnError((error, call) =>
  error instanceof ToolError ? error.message : `${call.name} failed`,
);

Where tools run

There are 4 places where you can provide tools to your agent

Connectors and MCP servers

Connectors and MCPs also expose tools. You can filter the tool list and set how they load. This is important for keeping your agent's tool usage under control:

connectors:
  - name: github
    connection: company
    tools: [list_issues, get_*]
    loading: summary

See the connector catalog, MCP servers and Choosing tools.

Tool call state

The SDKs make it easy to render the tool call. Title, tool call status and duration are available as shown below. You can either get the tool calls for a specific message, or all running tool calls for the entire session.

React
import {
  toolCallTitle,
  type Session,
  type ToolCallState,
} from "@stream-io/stream-agents";
import { useTurnToolCalls } from "@stream-io/stream-agents/react";

// Counted from started_at while the call runs; once it finished, how long it took.
function elapsedSeconds(toolCall: ToolCallState): number {
  const ms =
    toolCall.status === "in_progress"
      ? Date.now() - Date.parse(toolCall.started_at)
      : toolCall.duration_ms;
  return Math.round(ms / 1000);
}

// Style each status (waiting, in_progress, success, failed, cancelled) with your own spinner and icons.
function ToolCallRow({ toolCall }: { toolCall: ToolCallState }) {
  return (
    <li className={toolCall.status}>
      {toolCallTitle(toolCall)} <span>{elapsedSeconds(toolCall)}s</span>
      {toolCall.error && <span className="error">{toolCall.error}</span>}
    </li>
  );
}

// Render it under the agent's message for that turn.
export function TurnToolCalls({
  session,
  turnId,
}: {
  session: Session;
  turnId: string;
}) {
  const toolCalls = useTurnToolCalls(session, turnId);
  return (
    <ul>
      {toolCalls.map((toolCall) => (
        <ToolCallRow key={toolCall.tool_call_id} toolCall={toolCall} />
      ))}
    </ul>
  );
}
React Native
import { ActivityIndicator, Text, View } from "react-native";
import {
  toolCallTitle,
  type Session,
  type ToolCallState,
} from "@stream-io/stream-agents";
import { useTurnToolCalls } from "@stream-io/stream-agents/react";

// Counted from started_at while the call runs; once it finished, how long it took.
function elapsedSeconds(toolCall: ToolCallState): number {
  const ms =
    toolCall.status === "in_progress"
      ? Date.now() - Date.parse(toolCall.started_at)
      : toolCall.duration_ms;
  return Math.round(ms / 1000);
}

function ToolCallRow({ toolCall }: { toolCall: ToolCallState }) {
  return (
    <View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
      {toolCall.status === "in_progress" && <ActivityIndicator size="small" />}
      {toolCall.status === "success" && <Text>Done</Text>}
      <Text>{toolCallTitle(toolCall)}</Text>
      <Text>{elapsedSeconds(toolCall)}s</Text>
      {toolCall.error ? (
        <Text style={{ color: "red" }}>{toolCall.error}</Text>
      ) : null}
    </View>
  );
}

// Render it under the agent's message for that turn.
export function TurnToolCalls({
  session,
  turnId,
}: {
  session: Session;
  turnId: string;
}) {
  return (
    <View>
      {useTurnToolCalls(session, turnId).map((toolCall) => (
        <ToolCallRow key={toolCall.tool_call_id} toolCall={toolCall} />
      ))}
    </View>
  );
}
Kotlin
import io.getstream.agents.android.core.AgentEvent
import io.getstream.agents.android.core.AgentEvent.ToolCallState.Status
import kotlin.time.Clock

@Composable
fun ToolCallRow(toolCall: AgentEvent.ToolCallState) {
    Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
        when (toolCall.status) {
            Status.InProgress -> CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
            Status.Success -> Icon(Icons.Default.Check, contentDescription = null)
            Status.Failed, Status.Cancelled -> Icon(Icons.Default.Close, contentDescription = null)
            else -> {}
        }
        Text(toolCall.title)
        // Counted from startedAt while the call runs; once it finished, how long it took.
        val seconds = toolCall.startedAt?.takeIf { toolCall.status == Status.InProgress }
            ?.let { (Clock.System.now() - it).inWholeSeconds } ?: (toolCall.durationMs / 1000)
        Text("${seconds}s")
        if (toolCall.error.isNotEmpty()) Text(toolCall.error, color = MaterialTheme.colorScheme.error)
    }
}

// Show it under the agent's message for that turn.
@Composable
fun TurnToolCalls(session: AgentSession, turnId: String) {
    val toolCalls by remember(session, turnId) { session.toolCallsForTurn(turnId) }.collectAsState(emptyList())
    Column { toolCalls.forEach { ToolCallRow(it) } }
}
Swift
import StreamAgents
import SwiftUI

struct ToolCallRow: View {
    let toolCall: ToolCallState

    var body: some View {
        HStack {
            switch toolCall.status {
            case .inProgress: ProgressView()
            case .success: Image(systemName: "checkmark")
            case .failed, .cancelled: Image(systemName: "xmark")
            default: EmptyView()
            }
            Text(toolCall.title)
            // A timer that counts up while the call runs; once it finished, how long it took.
            if toolCall.status == .inProgress, let startedAt = toolCall.startedAt {
                Text(startedAt, style: .timer)
            } else {
                Text("\(toolCall.durationMS / 1000)s")
            }
            if !toolCall.error.isEmpty { Text(toolCall.error).foregroundStyle(.red) }
        }
    }
}

/// Show it under the agent's message for that turn.
struct TurnToolCalls: View {
    @ObservedObject var session: AgentSession
    let turnID: String

    var body: some View {
        ForEach(session.toolCalls(forTurn: turnID)) { ToolCallRow(toolCall: $0) }
    }
}
Dart
import 'package:flutter/material.dart';
import 'package:stream_agents/stream_agents.dart';

class ToolCallRow extends StatelessWidget {
  const ToolCallRow(this.toolCall, {super.key});
  final ToolCallState toolCall;

  // Counted from startedAt while the call runs; once it finished, how long it took.
  Duration get elapsed => switch (toolCall.startedAt) {
        final startedAt? when toolCall.status == ToolCallStatus.inProgress => DateTime.now().difference(startedAt),
        _ => toolCall.duration,
      };

  @override
  Widget build(BuildContext context) => ListTile(
        dense: true,
        leading: switch (toolCall.status) {
          ToolCallStatus.inProgress => const SizedBox.square(dimension: 16, child: CircularProgressIndicator(strokeWidth: 2)),
          ToolCallStatus.success => const Icon(Icons.check),
          ToolCallStatus.failed || ToolCallStatus.cancelled => const Icon(Icons.close),
          _ => null,
        },
        title: Text(toolCall.title),
        subtitle: toolCall.error.isEmpty ? null : Text(toolCall.error),
        trailing: Text('${elapsed.inSeconds}s'),
      );
}

// Show it under the agent's message for that turn.
class TurnToolCalls extends StatelessWidget {
  const TurnToolCalls({super.key, required this.session, required this.turnId});
  final AgentSession session;
  final String turnId;

  @override
  Widget build(BuildContext context) => StreamBuilder(
        stream: session.toolCalls.stream,
        builder: (context, _) => Column(
          children: [for (final toolCall in session.toolCallsForTurn(turnId)) ToolCallRow(toolCall)],
        ),
      );
}

Note that tool_call.display_title and tool_call.custom can be updated through events. So while the tool is running you can send events like "Searching for flights...", "Found 3 directs flights to NYC" etc.

Each tool call moves through these statuses:

Status When
waiting The call waits for the person's approval. Its title is the question
in_progress It's running. approved_at is set once someone allowed it
success It returned a result
failed It returned an error or ran out of time. error says why
cancelled It was declined, its approval timed out or the person interrupted it. A declined call has rejected_at

A call also has started_at and duration_ms. The socket sends the tool_call.started event once, tool_call.progress for each change and tool_call.finished once.

Show tool calls on the reply

In a conversation kept in Stream Chat, a reply carries a step for some of its tool calls, as an ai_tool_call attachment, which Stream's AI components show with the reply. Every other call runs without one. A call has a step when:

  • the tool asks the person before it runs, with an approval,
  • it's a client tool, run on the person's device,
  • the agent config's visible_tools names it, or
  • the router holds it for the person: a connector call that needs their approval or their sign-in, or a change to a repeating scheduled task.

A tool you give a session runs on the device either way, but the router takes it for one of its own unless the tool says otherwise: executor: "client" in JavaScript, executor = AgentTool.Executor.Client in Kotlin, executor: .client in Swift and executor: ToolExecutor.client in Dart. Give it a displayTitle for its step too, such as "Finding restaurants", as the client-side tools below do. Without the client executor, its step shows only if it has an approval or visible_tools names it. A client tool's step carries the call's arguments, which every member of the channel can see.

visible_tools shows the calls of any other tool, such as a connector's or your server's: tool names, or patterns such as athena_*. Left empty, it shows the router's search and web_search. A step it shows carries only the call's name, status and timing, never its arguments or result. agent.yaml has no key for it yet, so set it on the agent's config after the first sync. A sync leaves it as it is, since the folder doesn't name it:

id=$(getstream agents api ListAgentConfigs --jq '.[] | select(.name=="my-agent") | .id' | tr -d '"')
getstream agents api PatchAgentConfig --id "$id" --request '{"visible_tools":["lookup_order","athena_*"]}'

Tool title Updates

Let's show a full example of how to update the title, or any custom data while a tool runs.

Node.js
client.tools.register({
  name: "weather_lookup",
  description: "Look up the current weather for a location",
  displayTitle: "Checking the weather",
  parameters: z.object({
    location: z.string().describe("a city or region"),
  }),
  run: async ({ location }, toolCallContext) => {
    toolCallContext.update(`Checking the weather in ${location}`);
    const response = await fetch(
      `https://wttr.in/${encodeURIComponent(location)}?format=3`,
    );
    if (!response.ok) throw new Error(`wttr.in answered ${response.status}`);
    const report = await response.text();
    toolCallContext.update({ custom: { location, report } });
    return report;
  },
});
Python
from vision_agents.plugins.stream import ToolCallContext


@client.tools.register(display_title="Checking the weather")
async def weather_lookup(tool_call_context: ToolCallContext, location: str) -> str:
    """Look up the current weather for a location.

    Args:
        location: a city or region.
    """
    await tool_call_context.update(f"Checking the weather in {location}")
    async with httpx.AsyncClient() as http:
        response = await http.get(f"https://wttr.in/{location}", params={"format": "3"})
        response.raise_for_status()
    await tool_call_context.update(custom={"location": location, "report": response.text})
    return response.text
Ruby
client.tools.register(
  "weather_lookup",
  description: "Look up the current weather for a location",
  display_title: "Checking the weather",
  params: { location: "a city or region" },
) do |tool_call_context, location:|
  tool_call_context.update("Checking the weather in #{location}")
  response = Net::HTTP.get_response(URI("https://wttr.in/#{URI.encode_uri_component(location)}?format=3"))
  raise "wttr.in answered #{response.code}" unless response.is_a?(Net::HTTPSuccess)

  tool_call_context.update(custom: { location: location, report: response.body })
  response.body
end
PHP
$client->tools->register(
    name: 'weather_lookup',
    description: 'Look up the current weather for a location',
    parameters: Tools::strings(['location' => 'a city or region']),
    displayTitle: 'Checking the weather',
    run: function (ToolCallContext $toolCallContext, array $args): string {
        $toolCallContext->update('Checking the weather in ' . $args['location']);
        $weather = file_get_contents('https://wttr.in/' . rawurlencode($args['location']) . '?format=3');
        if ($weather === false) {
            throw new RuntimeException('wttr.in did not answer');
        }
        $toolCallContext->update(custom: ['location' => $args['location'], 'report' => $weather]);
        return $weather;
    },
);
Go
func weatherLookup(ctx context.Context, in WeatherLookup) (any, error) {
	call := tools.ToolCallContextFrom(ctx)
	if err := call.Update(ctx, "Checking the weather in "+in.Location); err != nil {
		return nil, err
	}
	address := "https://wttr.in/" + url.PathEscape(in.Location) + "?format=3"
	request, err := http.NewRequestWithContext(ctx, http.MethodGet, address, nil)
	if err != nil {
		return nil, err
	}
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()
	if response.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("wttr.in answered %s", response.Status)
	}
	body, err := io.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}
	report := string(body)
	custom := map[string]any{"location": in.Location, "report": report}
	if err := call.SendUpdate(ctx, tools.Update{Custom: custom}); err != nil {
		return nil, err
	}
	return report, nil
}

err = tools.Register(api.Tools(), "weather_lookup", "Look up the current weather for a location",
	weatherLookup, tools.DisplayTitle("Checking the weather"))
.NET
client.Tools.Register<WeatherLookup, string>("weather_lookup",
    "Look up the current weather for a location",
    async (toolCallContext, lookup, cancellationToken) =>
    {
        await toolCallContext.UpdateAsync($"Checking the weather in {lookup.Location}", cancellationToken);
        var report = await http.GetStringAsync(
            $"https://wttr.in/{Uri.EscapeDataString(lookup.Location)}?format=3", cancellationToken);
        await toolCallContext.UpdateAsync(
            new ToolCallUpdate(Custom: new JsonObject { ["location"] = lookup.Location, ["report"] = report }),
            cancellationToken);
        return report;
    },
    displayTitle: "Checking the weather");
Rust
client.tools().register_with_tool_call_context(
    types::SessionTool {
        name: "weather_lookup".into(),
        description: "Look up the current weather for a location".into(),
        display_title: Some("Checking the weather".into()),
        parameters: json!({"type": "object", "properties": {"location": {"type": "string"}}})
            .as_object()
            .cloned()
            .unwrap_or_default(),
        ..Default::default()
    },
    async |tool_call_context: ToolCallContext, args: Value| {
        let location = args["location"].as_str().unwrap_or_default().to_string();
        tool_call_context
            .update(format!("Checking the weather in {location}"))
            .await
            .map_err(|error| error.to_string())?;
        let mut address = reqwest::Url::parse("https://wttr.in/?format=3").map_err(|error| error.to_string())?;
        address.path_segments_mut().map_err(|_| "wttr.in has no path")?.pop_if_empty().push(&location);
        let report = reqwest::get(address)
            .await
            .and_then(|response| response.error_for_status())
            .map_err(|error| error.to_string())?
            .text()
            .await
            .map_err(|error| error.to_string())?;
        tool_call_context
            .send_update(ToolCallUpdate {
                custom: json!({"location": location, "report": report}).as_object().cloned(),
                ..Default::default()
            })
            .await
            .map_err(|error| error.to_string())?;
        Ok::<_, String>(report)
    },
)?;

Loading tools and caching

Three loading options are supported for tools. full, summary and deferred.

This is a bit of a simplication. But typically:

  • If a tool is used in 100% of agent sessions, load it up front so you benefit from LLM caching
  • If a tool is used infrequently and large in terms of token usage, set it to summary
  • If you have many tools, which are not used often, consider putting some of them to "deferred"
tools:
  - name: bookings
    tools: [lookup_booking, change_booking]
  - name: sentry
    loading: summary
    tools: [search_traces]
  - name: exports
    loading: deferred
    tools: [export_invoices]
loading What the model sees up front When it's used
full (the default) The whole description and schema It's called straight away
summary The description's first line and the argument names The first call runs nothing and returns the full description, and the model calls again
deferred Nothing The model finds it with search_tool, loads it with load_tool, then calls it

Choosing how a tool loads

Cached tokens are typically 95% cheaper than regular input tokens. Most providers will keep the cache around for 5 minutes to an hour.

Let's go over two examples so you see the differences between full and deferred tool loading.

Scenario 1: no tools used

In this example the user asks the agent 3 questions

  • "Hi, what is the size of your deluxe room?",
  • "Does it have a crib for babies, or can you provide one?" and
  • "Is there a kettle in the room?"

These questions can all be answered from knowledge without additional tools.

Full Deferred
Turn 1 100 input, 1,000 cached 100 input, 100 cached
Turn 2 100 input, 1,200 cached 100 input, 300 cached
Turn 3 100 input, 1,400 cached 100 input, 500 cached
Total 300 input, 3,600 cached 300 input, 900 cached
Cost in input tokens 480 345

Scenario 2: a booking tool

The two questions are

  • "I'd like to change my reservation to Wednesday, is that possible?" (this needs tool usage)
  • "Thanks! Is there a crib in the room?"
Full Deferred
Turn 1 100 input, 1,000 cached 1,100 input (the question and the tool), 100 cached
Turn 2 100 input, 1,200 cached 100 input, 1,300 cached
Total 200 input, 2,200 cached 1,200 input, 1,400 cached
Cost in input tokens 310 1,270

Loading the tool late bills it's 1,000 tokens as input (not cached). From cache the cost would be 95% lower.

So we track two numbers for each tool:

  • how many turns a session has on average before the tool is called
  • and what percentage of sessions uses the tool
  • token usage

As a concrete example. Sentry's search_traces tool uses 461 tokens in full and 84 as a summary. If it's called after 33 turns on average, in 50% of the sessions:

loading Tokens per session Cost in input tokens
full 33 x 461 = 15,213 cached 760
summary 33 x 84 = 2,772 cached, plus 461 input in half the sessions 139 + 230 = 369
deferred 461 input in half the sessions 230

Deferred is the cheapest here, but the model has to find the tool first, which can fail. As a general guideline, full is best when you only have a few tools, summary when you have several and deferred when you have many.

Tool stats

Stats are stored on tool usage. This is important for optimizing LLM performance and costs. This is how you can read the tools stats, they are also shown in the dashboard.

api, err := client.New(stream.Backend{})
if err != nil {
	return err
}
from := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)
stats, err := api.Agent("my-agent").Stats(ctx, from, from.AddDate(0, 1, 0))
if err != nil {
	return err
}
for _, tool := range stats.Tools {
	fmt.Printf("%s: %d calls, %d failed\n", tool.Tool, tool.Calls, tool.Failed)
}
Field What it is
sessions, session_share Sessions that called the tool, and their share of all sessions, from 0 to 1
avg_turns_before_use Turns a session took before its first call; 0 is a call on the first turn
definition_tokens, summary_tokens What the tool costs every turn that carries it, in full and as a summary
loading How the latest call had the tool loaded
calls, failed Calls, and the calls that ended in an error. failed / calls is the error rate
avg_ms, p99_ms From a call starting to its result
avg_tokens What a call's arguments and result put in front of the model

Token usage is estimated.

Client-side tools

Client side tools can be helpful for user location, their calendar etc. The example below shows a tool for sharing your location with the agent.

React
import { useEffect, useState } from "react";
import { Client, Session, Tools } from "@stream-io/stream-agents";
import { z } from "zod";

const tools = new Tools().register({
  name: "get_location",
  description:
    "Where the person is. Only call it when the answer depends on it.",
  parameters: z.object({
    reason: z.string().describe("why you need it, in a few words"),
  }),
  displayTitle: "Checking where you are",
  approval: {
    title: "Share your location?",
    reasonArgument: "reason",
    allowTitle: "Share",
    declineTitle: "Not now",
  },
  run: async () => {
    // The browser asks for the permission the first time.
    const { coords } = await new Promise<GeolocationPosition>(
      (resolve, reject) =>
        navigator.geolocation.getCurrentPosition(resolve, reject),
    );
    return `They are at latitude ${coords.latitude}, longitude ${coords.longitude}.`;
  },
});

// `client` holds your apiKey and a user from setUser.
export function useAgentSession(client: Client) {
  const [session, setSession] = useState<Session>();
  useEffect(() => {
    const opening = client.agent("support").sessions.create({ tools });
    opening.then(setSession);
    return () => {
      opening.then((opened) => opened.close());
    };
  }, [client]);
  return session;
}
React Native
import { useEffect, useState } from "react";
import * as Location from "expo-location";
import { Client, Session, Tools } from "@stream-io/stream-agents";
import { z } from "zod";

const tools = new Tools().register({
  name: "get_location",
  description:
    "Where the person is. Only call it when the answer depends on it.",
  parameters: z.object({
    reason: z.string().describe("why you need it, in a few words"),
  }),
  displayTitle: "Checking where you are",
  approval: {
    title: "Share your location?",
    reasonArgument: "reason",
    allowTitle: "Share",
    declineTitle: "Not now",
  },
  run: async () => {
    // The phone asks for the permission the first time, once the person allowed the call.
    const { status } = await Location.requestForegroundPermissionsAsync();
    if (status !== "granted") {
      throw new Error("The person hasn't let the app see where they are.");
    }
    const { coords } = await Location.getCurrentPositionAsync({});
    return `They are at latitude ${coords.latitude}, longitude ${coords.longitude}.`;
  },
});

// `client` holds your apiKey and a user from setUser.
export function useAgentSession(client: Client) {
  const [session, setSession] = useState<Session>();
  useEffect(() => {
    const opening = client.agent("support").sessions.create({ tools });
    opening.then(setSession);
    return () => {
      opening.then((opened) => opened.close());
    };
  }, [client]);
  return session;
}
Kotlin
import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import androidx.core.content.ContextCompat
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.Priority
import io.getstream.agents.android.core.AgentTool
import io.getstream.agents.android.core.SessionOptions
import kotlinx.coroutines.tasks.await

// `context` is your Application, not an Activity, since the tool outlives the screen.
val locations = LocationServices.getFusedLocationProviderClient(context)

@SuppressLint("MissingPermission") // Checked before the location is read.
val location = AgentTool(
    name = "get_location",
    description = "Where the person is. Only call it when the answer depends on it.",
    parameters = AgentTool.strings(mapOf("reason" to "why you need it, in a few words"), required = listOf("reason")),
    displayTitle = "Checking where you are",
    approval = AgentTool.Approval(
        title = "Share your location?",
        reasonArgument = "reason",
        allowTitle = "Share",
        declineTitle = "Not now",
    ),
) {
    // Ask for ACCESS_COARSE_LOCATION from an activity before the session opens.
    val granted = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) ==
        PackageManager.PERMISSION_GRANTED
    if (!granted) throw IllegalStateException("The person hasn't let the app see where they are.")
    val here = locations.getCurrentLocation(Priority.PRIORITY_BALANCED_POWER_ACCURACY, null).await()
        ?: throw IllegalStateException("The phone couldn't tell where it is just now.")
    "They are at latitude ${here.latitude}, longitude ${here.longitude}."
}

// `agents` is the StreamAgents the user signed in with.
val session = agents.agent("support").sessions.create(SessionOptions(tools = listOf(location)))
Swift
import CoreLocation
import StreamAgents

struct ToolFailure: LocalizedError {
    let errorDescription: String?
}

let location = AgentTool(
    name: "get_location",
    description: "Where the person is. Only call it when the answer depends on it.",
    parameters: .strings(["reason": "why you need it, in a few words"], required: ["reason"]),
    displayTitle: "Checking where you are",
    approval: .init(
        title: "Share your location?",
        reasonArgument: "reason",
        allowTitle: "Share",
        declineTitle: "Not now")
) { _ in
    // Ask for the permission once, such as when the app starts:
    // CLLocationManager().requestWhenInUseAuthorization()
    // CLLocationUpdate needs iOS 18 for authorizationDenied.
    for try await update in CLLocationUpdate.liveUpdates() {
        if update.authorizationDenied {
            throw ToolFailure(errorDescription: "The person hasn't let the app see where they are.")
        }
        if let here = update.location {
            return "They are at latitude \(here.coordinate.latitude), longitude \(here.coordinate.longitude)."
        }
    }
    throw ToolFailure(errorDescription: "The phone couldn't tell where it is just now.")
}

// `agents` is the StreamAgents the user signed in with.
let session = try await agents.agent("support").sessions.create(SessionOptions(tools: [location]))
Dart
import 'package:geolocator/geolocator.dart';
import 'package:stream_agents/stream_agents.dart';

final location = AgentTool(
  name: 'get_location',
  description: 'Where the person is. Only call it when the answer depends on it.',
  parameters: AgentTool.strings({'reason': 'why you need it, in a few words'}, required: ['reason']),
  displayTitle: 'Checking where you are',
  approval: const ToolApproval(
    title: 'Share your location?',
    reasonArgument: 'reason',
    allowTitle: 'Share',
    declineTitle: 'Not now',
  ),
  run: (_) async {
    // The phone asks for the permission the first time, once the person allowed the call.
    final permission = await Geolocator.requestPermission();
    if (permission == LocationPermission.denied || permission == LocationPermission.deniedForever) {
      throw StateError("The person hasn't let the app see where they are.");
    }
    final here = await Geolocator.getCurrentPosition();
    return 'They are at latitude ${here.latitude}, longitude ${here.longitude}.';
  },
);

// `agents` is the StreamAgents the user signed in with.
final session = await agents.agent('support').sessions.create(SessionOptions(tools: [location]));

The Swift assistant and Android assistant show a full example.