Auth

Every request to Stream Agents is authenticated in one of two ways:

Side Runs in Holds Can reach
Server side Your server, workers, scripts API key and API secret Everything in your Stream app
Client side The browser, Android, iOS and Flutter API key and a user token That user's own sessions

The API key is public. Your server uses the secret to mint a token for each signed-in user, and the app connects with the key and that token.

Danger:

The secret is not public: never ship it in an app or a web page.

Server side

On your server, set your key and secret in the environment:

export STREAM_API_KEY=your_api_key
export STREAM_API_SECRET=your_api_secret

The client reads them, so it needs no arguments:

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

const client = new Client();
Python
from vision_agents.plugins import stream

client = stream.Client()
Ruby
require "getstream/vision_agents"

client = GetStream::VisionAgents::Client.new
PHP
use GetStream\VisionAgents\Client;

$client = new Client();
Go
api, err := client.New(stream.Backend{})
if err != nil {
	log.Fatal(err)
}
.NET
using GetStream.VisionAgents;

using var client = new VisionAgentsClient();
Rust
use vision_agents::Client;

let client = Client::from_env()?;

The SDK signs a short-lived server token with the secret on every request. Your server can configure and sync agents, and read and manage every session in your Stream app.

Client side

An app holds only the public API key. Once the user has signed in, hand the SDK a token your server minted for them (Generating a token shows the route):

React Native
import { Client } from "@stream-io/stream-agents";

const client = new Client({ apiKey: "your_api_key" });
await client.setUser("jlahey", async () => {
  // An app has no origin, so name your server in full.
  const response = await fetch("https://your-app.example.com/api/agent-token");
  if (!response.ok) throw new Error(`token: ${response.status}`);
  return response.text();
});
React
import { Client } from "@stream-io/stream-agents";

const client = new Client({ apiKey: "your_api_key" });
await client.setUser("jlahey", async () => {
  const response = await fetch("/api/agent-token");
  if (!response.ok) throw new Error(`token: ${response.status}`);
  return response.text();
});
Kotlin
val agents = StreamAgents(apiKey = "your_api_key")
agents.setUser(User(id = "jlahey")) { yourBackend.agentToken() }
Swift
let agents = StreamAgents(apiKey: "your_api_key")
agents.setUser(User(id: "jlahey")) { try await yourBackend.agentToken() }
Dart
final agents = StreamAgents(
  apiKey: 'your_api_key',
  userId: 'jlahey',
  token: yourBackend.agentToken,
);

The token can be a string, or a function that fetches one from your server. The Kotlin and Swift SDKs ask the function once and keep the token, then ask again when the router refuses it with a 401 and send the request once more, and when Stream Chat or Stream Video says the token expired. The JavaScript SDK does the same, and also asks again shortly before the token's exp and when a session's socket is refused. The Flutter SDK takes only a function. It asks it once and keeps the token too, and asks again when the router refuses it with a 401, sending the request once more, and when Stream Chat or Stream Video says the token expired.

When the user signs out, call clearUser(): the SDK forgets them and their token, and asks for a user again before its next request.

Kotlin only

In Kotlin, it's agents.backend.clearUser(). Call agents.disconnect() too, which disconnects the Stream Chat and Video clients the SDK connected as that user.

Flutter only

The Flutter SDK has no clearUser(): call disconnect() and close() on that StreamAgents, and make a new one when the next user signs in.

A client only reaches its signed-in user's own sessions. It can open, watch, ask, search, fork, rewind, rename, pin, close and delete them. Configuring agents, syncing, and reading call records are server-side only. Each page lists what a client may call, such as Sessions.

Guests

A guest lets somebody talk to an agent before they sign up. The app asks for one with the public API key alone, and acts as it with setUser(guest), which takes the token the guest was minted with:

React Native
// npx expo install expo-secure-store
import { Client, type GuestStore } from "@stream-io/stream-agents";
import * as SecureStore from "expo-secure-store";

const client = new Client({ apiKey: "your_api_key" });

// An app has no cookies or localStorage: keep the guest in the keychain, so the next launch is
// the same guest with the same conversations. An expired guest is refreshed rather than replaced.
const store: GuestStore = {
  read: () => SecureStore.getItem("agents-guest") ?? undefined,
  write: (value) => SecureStore.setItem("agents-guest", value),
  clear: () => void SecureStore.deleteItemAsync("agents-guest"),
};
const guest = await client.guestUser({ name: "Guest" }, store);
await client.setUser(guest);

const session = await client.agent("support").sessions.create();
React
import { Client } from "@stream-io/stream-agents";

const client = new Client({ apiKey: "your_api_key" });

// Remembered in localStorage, so a reload is the same guest with the same conversations.
// A cookie only stands in where localStorage is blocked or full. An expired guest is refreshed
// rather than replaced.
const guest = await client.guestUser({ name: "Guest" });
await client.setUser(guest);

const session = await client.agent("support").sessions.create();
Kotlin
val agents = StreamAgents(apiKey = "your_api_key")

// Remembered in a file, so the next launch is the same guest with the same conversations.
// An expired guest is refreshed rather than replaced.
val store = FileGuestStore(File(context.filesDir, "agents-guest"))
val guest = agents.guestUser(GuestOptions(name = "Guest"), store)
agents.setUser(guest)

val session = agents.agent("support").sessions.create()
Swift
import Foundation
import StreamAgents

let agents = StreamAgents(apiKey: "your_api_key")

// Remembered in a file, so the next launch is the same guest with the same conversations.
// An expired guest is refreshed rather than replaced.
let store = FileGuestStore(
    url: FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
        .appendingPathComponent("stream-agents-guest.json")
)

func continueAsGuest() async throws -> AgentSession {
    let guest = try await agents.guestUser(GuestOptions(name: "Guest"), store: store)
    agents.setUser(guest)
    return try await agents.agent("support").sessions.create()
}
Dart
final agents = StreamAgents(apiKey: 'your_api_key');

// Remembered for as long as the app runs. Implement GuestStore over the platform's keystore,
// such as flutter_secure_storage, to keep the same guest, with the same conversations, across
// launches: it holds the guest's token.
// An expired guest is refreshed rather than replaced.
final store = MemoryGuestStore();
final guest = await agents.guestUser(name: 'Guest', store: store);
final asGuest = agents.withGuest(guest);

final session = await asGuest.agent('support').sessions.create();
Flutter only

The Flutter SDK has no setUser: agents.withGuest(guest) returns a StreamAgents that acts as the guest, and guestUser(store: store, fresh: true) starts over as a new one. Once the guest signs in, agents.withUser(userId, token: ...) acts as the account.

guestUser({ fresh: true }) starts over as a new guest, for a "not me" button, as GuestOptions(fresh = true) does in Kotlin and GuestOptions(fresh: true) in Swift. Without a store, the Kotlin and Swift SDKs remember nothing, and each launch is a new guest. When the guest signs up or signs in, your server moves their conversations onto the account, and the app forgets the guest and sets the real user:

Not documented for Python yet. Showing Node.js.

Not documented for Ruby yet. Showing Node.js.

Not documented for PHP yet. Showing Node.js.

Not documented for Go yet. Showing Node.js.

Not documented for .NET yet. Showing Node.js.

Not documented for Rust yet. Showing Node.js.

Node.js
// On your backend, with STREAM_API_KEY and STREAM_API_SECRET in the environment,
// once it has authenticated the account the guest turned out to be.
import { Client } from "@stream-io/stream-agents";

const server = new Client();
await server.claimGuestUser(guestId, "jlahey");

In JavaScript, client.forgetGuest() clears the remembered guest before setUser names the account, in Kotlin, agents.forgetGuest(store), in Swift, agents.forgetGuest(store:), and in Dart, agents.forgetGuest(store). Claiming is server-side only: a client able to claim could take anybody's conversations by guessing a guest id. A Stream app that has turned guests off refuses guestUser with a 403, from a client and from your server alike. A router that admits no anonymous callers refuses only the client: guestUser throws a ConfigurationError (AgentsException.Configuration in Kotlin, AgentsError.configuration in Swift, a StateError in Dart), and your server mints the guest with guestUser and hands it to the client for setUser.

Generating a token

For testing, mint one with the CLI:

getstream token jlahey --ttl 2h

In production, your server mints the token after it has signed the user in, and returns it to the app. A token is a JWT signed with your API secret (HS256), naming the user in user_id.

Stream's server SDKs mint one for you. In JavaScript, this is the /api/agent-token route the client samples fetch:

Not documented for Ruby yet. Showing Node.js.

Not documented for PHP yet. Showing Node.js.

Not documented for .NET yet. Showing Node.js.

Not documented for Rust yet. Showing Node.js.

Node.js · app/api/agent-token/route.ts
// STREAM_API_KEY and STREAM_API_SECRET are in the environment.
import { Client } from "@stream-io/stream-agents";

const stream = new Client();

export async function GET(request: Request): Promise<Response> {
  const user = await getSignedInUser(request); // your own sign-in
  if (!user) {
    return new Response("Unauthorized", { status: 401 });
  }
  const token = await stream.createUserToken(user.id, {
    validitySeconds: 3600,
  });
  return new Response(token);
}
Python
from getstream import Stream

stream = Stream(api_key=os.environ["STREAM_API_KEY"], api_secret=os.environ["STREAM_API_SECRET"])

token = stream.create_token("jlahey", expiration=3600)
Go
stream, err := getstream.NewClient(os.Getenv("STREAM_API_KEY"), os.Getenv("STREAM_API_SECRET"))
if err != nil {
	log.Fatal(err)
}

token, err := stream.CreateToken("jlahey", getstream.WithExpiration(time.Hour))

The same token signs that user in to Stream Chat and Video, so one endpoint on your server serves all three. In JavaScript, createUserToken also takes the user's team and usageCategories, fixed in the token so the device can't move its work elsewhere (Spend limits).