# Fishjam Docs > Fishjam is a low-latency video conferencing and live streaming API created by Software Mansion. It lets developers build real-time video, audio, and data streaming applications using WebRTC without needing any WebRTC expertise. This file contains all documentation content in a single document following the llmstxt.org standard. ## Agents # Fishjam Agent Introduction :::tip We recommend going through the steps in the [Backend Quick Start](../tutorials/backend-quick-start) before trying Fishjam agents, as you will need a working backend server to use them. ::: This page gives an introduction to Fishjam agents and how to use them. You can learn more about how Agents work on the [Agent Internals](../explanation/agent-internals) page. ## What is an Agent? An agent is a piece of software that allows your backend server to participate in a Fishjam room, similar to how the Fishjam client SDKs allow your client-side application to participate in a Fishjam room. They can be used to implement features such as real-time audio transcription, real-time content moderation, conversations with AI agents and more. You can simply think of an agent as a peer running within your backend application. ## Writing an Agent In this section we show how to implement an agent using the Fishjam server SDKs. If you are not using the SDKs, then you can check out the [Agent Internals](../explanation/agent-internals#agent-lifecycle), to learn how to integrate with Fishjam Agents. ### Prerequisites Before we create the actual agent, we need to [create a room](../tutorials/backend-quick-start#step-4-create-a-room) first, as agents are scoped to rooms. Additionally, we will also create a peer so that the agent has someone to listen to and talk to. ```ts const fishjamId = ""; const managementToken = ""; // ---cut--- const fishjamClient = new FishjamClient({ fishjamId, managementToken }); const room = await fishjamClient.createRoom(); const peer = await fishjamClient.createPeer(room.id); ``` ```python from fishjam import FishjamClient fishjam_client = FishjamClient(fishjam_id, management_token) room = fishjam_client.create_room() peer = fishjam_client.create_peer(room.id) ``` ### Creating a listening Agent If you are using the server SDKs, then creating an agent and defining its behavior is very simple. By default, agents receive all peers' audio streams. However, it's likely that in your scenario you'll want to use the [Selective Subscriptions API](../how-to/backend/selective-subscriptions.mdx) for fine-grained control over which peers/tracks they should receive audio from. ```ts const fishjamId = ''; const managementToken = ''; const fishjamClient = new FishjamClient({ fishjamId, managementToken }); const room = await fishjamClient.createRoom(); // ---cut--- const agentOptions = { subscribeMode: 'auto', output: { audioFormat: 'pcm16', audioSampleRate: 16000 } } satisfies PeerOptions; const agentCallbacks = { onError: console.error, onClose: (code, reason) => console.log('Agent closed', code, reason) } satisfies AgentCallbacks; // [!code highlight:1] const { agent } = await fishjamClient.createAgent(room.id, agentOptions, agentCallbacks); // Register a callback for incoming audio data agent.on('trackData', ({ track, peerId, data }) => { // process the incoming data }) ``` ```python from fishjam import FishjamClient, AgentOptions from fishjam.agent import IncomingTrackData fishjam_client = FishjamClient(fishjam_id, management_token) agent_options = AgentOptions(subscribe_mode="auto") agent = fishjam_client.create_agent(room_id, agent_options) async def run(): # the agent will disconnect once you exit the context async with agent.connect() as session: async for track_data in session.receive(): # process the incoming data pass asyncio.run(run()) ``` ### Multiple Agents in a Room You can create multiple agents inside a single room by creating agents with the same room ID multiple times. Each agent operates independently, with its own set of tracks and callbacks. ```ts const fishjamId = ''; const managementToken = ''; const fishjamClient = new FishjamClient({ fishjamId, managementToken }); const room = await fishjamClient.createRoom(); const agentOptions = { subscribeMode: 'auto', output: { audioFormat: 'pcm16', audioSampleRate: 16000 } } satisfies PeerOptions; const agentCallbacks = { onError: console.error, onClose: (code, reason) => console.log('Agent closed', code, reason) } satisfies AgentCallbacks; // ---cut--- const agentCallbacks1 = { onError: console.error, onClose: (code, reason) => console.log('Agent 1 closed', code, reason) } satisfies AgentCallbacks; const agentCallbacks2 = { onError: console.error, onClose: (code, reason) => console.log('Agent 2 closed', code, reason) } satisfies AgentCallbacks; const { agent: agent1 } = await fishjamClient.createAgent(room.id, agentOptions, agentCallbacks1); const { agent: agent2 } = await fishjamClient.createAgent(room.id, agentOptions, agentCallbacks2); ``` ```python from fishjam import FishjamClient fishjam_client = FishjamClient(fishjam_id, management_token) agent1 = fishjam_client.create_agent(room_id) agent2 = fishjam_client.create_agent(room_id) ``` ### Making the Agent speak Apart from just listening, agents can also send audio data to peers. Let's assume that in the previous section we forwarded the peer's audio to some audio chatbot. Now, the chatbot returns responses, and we want to play it back to the peer. :::tip You can interrupt the currently played audio chunk. See the example below. ::: ```ts const fishjamId = ''; const managementToken = ''; const fishjamClient = new FishjamClient({ fishjamId, managementToken }); const room = await fishjamClient.createRoom(); const { agent } = await fishjamClient.createAgent(room.id, {}); const chatbot: any = null; // ---cut--- const codecParameters = { encoding: 'pcm16', sampleRate: 16000, channels: 1, } satisfies AudioCodecParameters; const agentTrack = agent.createTrack(codecParameters); // that's a dummy chatbot, // you can bring your audio from anywhere chatbot.on('response', (response: Uint8Array) => { // [!code highlight:1] agent.sendData(agentTrack.id, response); // you're able to interrupt the currently played audio chunk // [!code highlight:1] agent.interruptTrack(agentTrack.id); }); ``` ```python from fishjam import FishjamClient, AgentOptions from fishjam.agent import OutgoingAudioTrackOptions from fishjam.events import TrackEncoding fishjam_client = FishjamClient(fishjam_id, management_token) agent_options = AgentOptions(subscribe_mode="auto") agent = fishjam_client.create_agent(room_id, agent_options) track_options = OutgoingAudioTrackOptions(encoding=TrackEncoding.TRACK_ENCODING_PCM16) async def run(): # the agent will disconnect once you exit the context async with agent.connect() as session: outgoing_track = await session.add_track(track_options) # that's a dummy chatbot async for chatbot_data in chatbot.receive(): await outgoing_track.send_chunk(chatbot_data) # you're able to interrupt the currently played audio chunk # [!code highlight:1] await outgoing_track.interrupt() asyncio.run(run()) ``` ### Making the Agent see Agents can also request video frames (JPEG images) from peers' video tracks. Unlike audio, which streams continuously, video frames must be explicitly requested and arrive asynchronously. :::important Video frame capture is rate-limited to one frame per second per track. ::: ```ts // @noErrors const fishjamId = ''; const managementToken = ''; const fishjamClient = new FishjamClient({ fishjamId, managementToken }); const room = await fishjamClient.createRoom(); const { agent } = await fishjamClient.createAgent(room.id, {}); const trackId: TrackId = '' as TrackId; // ---cut--- // Listen for incoming video frames agent.on('trackImage', (message: IncomingTrackImage) => { const { contentType, data } = message; // process the image data }); // Request a frame periodically setInterval(() => { // [!code highlight:1] agent.captureImage(trackId); }, 1000); ``` ```python from fishjam import FishjamClient from fishjam.agent import IncomingTrackImage fishjam_client = FishjamClient(fishjam_id, management_token) agent = fishjam_client.create_agent(room_id) async def run(): async with agent.connect() as session: # Request a frame # [!code highlight:1] await session.capture_image(track_id) # Captured frames arrive as IncomingTrackImage messages async for message in session.receive(): match message: case IncomingTrackImage() as msg if msg.track_id == track_id: data = msg.data # process the image data pass asyncio.run(run()) ``` ### Disconnecting After you're done using an agent, you can disconnect it from the room. ```ts const fishjamId = ''; const managementToken = ''; const fishjamClient = new FishjamClient({ fishjamId, managementToken }); const room = await fishjamClient.createRoom(); const { agent } = await fishjamClient.createAgent(room.id, {}); // ---cut--- agent.disconnect(); ``` ```python async def run(): # the agent will disconnect once you exit the context async with agent.connect() as session: pass asyncio.run(run()) ``` :::danger[Remember to disconnect your agents!] It's important to disconnect agents, because **every connected agent generates usage** just as a normal peer. ::: ## Pricing Agents are billed as if they were normal peers. For example, a room with 2 peers and 1 agent connected will be billed as if there were 3 peers connected to the room. Exact pricing values can be found on our [pricing page](https://fishjam.io/#pricing). ## Using agents without our SDKs If you are using Fishjam's REST API directly, then check out this [Agent Internals section](../explanation/agent-internals#step-1-creating-an-agent-in-fishjam). ## See also Learn more about how agents work: - [Agent Internals](../explanation/agent-internals) - [Selective Subscriptions API](../how-to/backend/selective-subscriptions.mdx) Writing a backend server with Fishjam: - [Backend Quick Start](../tutorials/backend-quick-start) - [How to Setup a Backend Server](../how-to/backend/server-setup) - [Going to Production](../how-to/backend/production-deployment) --- ## Backend Quick Start This tutorial will guide you through setting up a backend server that can create rooms and manage peers for your Fishjam application. By the end, you'll have a working backend and understand how to integrate it with your client apps. ## Choose your language Select your preferred backend language and all code examples will be shown for that language: We'll use **Node.js with TypeScript** and the `@fishjam-cloud/js-server-sdk` package. We'll use **Python** and the `fishjam-server-sdk` package. ## What you'll build A simple backend server that can create rooms, add peers, and generate tokens for client apps. ## What you'll learn - How to install and set up a Fishjam server SDK - How to create and manage rooms - How to create peers and generate tokens ## Prerequisites - Node.js environment set up - Access to [Fishjam Dashboard](https://fishjam.io/app) with your credentials - Python environment set up - Access to [Fishjam Dashboard](https://fishjam.io/app) with your credentials ## Step 1: Install the SDK Install the JavaScript server SDK using your preferred package manager: ```bash npm install @fishjam-cloud/js-server-sdk ``` ```bash yarn add @fishjam-cloud/js-server-sdk ``` ```bash pnpm add @fishjam-cloud/js-server-sdk ``` Install the Python server SDK using your preferred package manager: ```bash pip install fishjam-server-sdk ``` ```bash poetry add fishjam-server-sdk ``` ```bash uv add fishjam-server-sdk ``` ## Step 2: Get your credentials 1. Log in to [Fishjam Dashboard](https://fishjam.io/app) 2. Navigate to your app 3. Copy your **Fishjam ID** and **Management Token** 4. Store them as environment variables: ```bash export FISHJAM_ID="your-fishjam-id" export FISHJAM_MANAGEMENT_TOKEN="your-management-token" ``` ```bash export FISHJAM_ID="your-fishjam-id" export FISHJAM_MANAGEMENT_TOKEN="your-management-token" ``` ## Step 3: Set up the client Create your Fishjam client: ```ts process.env.FISHJAM_ID = ""; process.env.FISHJAM_MANAGEMENT_TOKEN = ""; // ---cut--- const fishjamId = process.env.FISHJAM_ID; const managementToken = process.env.FISHJAM_MANAGEMENT_TOKEN; const fishjamClient = new FishjamClient({ fishjamId, managementToken }); ``` ```python from fishjam import FishjamClient fishjam_id = os.environ["FISHJAM_ID"] management_token = os.environ["FISHJAM_MANAGEMENT_TOKEN"] fishjam_client = FishjamClient(fishjam_id, management_token) ``` ## Step 4: Create a room Create your first room: ```ts const fishjamId = ""; const managementToken = ""; const fishjamClient = new FishjamClient({ fishjamId, managementToken }); // ---cut--- async function createRoom() { const room = await fishjamClient.createRoom(); console.log('Room created:', room.id); return room; } ``` ```python def create_room(): room = fishjam_client.create_room() print(f'Room created: {room.id}') return room ``` ## Step 5: Add a peer to the room Create a peer and get a token for your client app: ```ts const fishjamId = ""; const managementToken = ""; const fishjamClient = new FishjamClient({ fishjamId, managementToken }); // ---cut--- async function addPeer(roomId: RoomId, peerName: string) { const { peer, peerToken } = await fishjamClient.createPeer(roomId, { metadata: { name: peerName }, }); console.log('Peer created:', peer.id); console.log('Peer token:', peerToken); return { peer, peerToken }; } ``` ```python from fishjam import PeerOptions def add_peer(room_id: str, peer_name: str): options = PeerOptions(metadata={"name": peer_name}) peer, peer_token = fishjam_client.create_peer(room_id, options=options) print(f'Peer created: {peer.id}') print(f'Peer token: {peer_token}') return peer, peer_token ``` ## Step 6: Create a simple API endpoint Build a simple HTTP endpoint that your client apps can call: ```ts process.env.FISHJAM_ID = ""; process.env.FISHJAM_MANAGEMENT_TOKEN = ""; // ---cut--- const app = express(); app.use(express.json()); const fishjamClient = new FishjamClient({ fishjamId: process.env.FISHJAM_ID!, managementToken: process.env.FISHJAM_MANAGEMENT_TOKEN! }); app.post('/join-room', async (req, res) => { try { const { roomName, peerName } = req.body; // Create room const room = await fishjamClient.createRoom(); // Add peer const { peer, peerToken } = await fishjamClient.createPeer(room.id, { metadata: { name: peerName }, }); res.json({ roomId: room.id, peerToken, }); } catch (error: any) { res.status(500).json({ error: error.message }); } }); app.listen(3000, () => { console.log('Server running on port 3000'); }); ``` Don't forget to install Express: ```bash npm install express @types/express ``` ```bash yarn add express @types/express ``` ```bash pnpm add express @types/express ``` ```python from fastapi import FastAPI, HTTPException from pydantic import BaseModel from fishjam import FishjamClient, PeerOptions app = FastAPI() fishjam_client = FishjamClient( os.environ["FISHJAM_ID"], os.environ["FISHJAM_MANAGEMENT_TOKEN"] ) class JoinRoomRequest(BaseModel): room_name: str peer_name: str @app.post("/join-room") async def join_room(request: JoinRoomRequest): try: # Create room room = fishjam_client.create_room() # Add peer options = PeerOptions(metadata={"name": request.peer_name}) peer, peer_token = fishjam_client.create_peer(room.id, options=options) return { "room_id": room.id, "peer_token": peer_token, } except Exception as e: raise HTTPException(status_code=500, detail=str(e)) ``` Don't forget to install FastAPI: ```bash pip install fastapi[standard] ``` ```bash poetry add fastapi[standard] ``` ```bash uv add fastapi[standard] ``` ## Step 7: Run your server Start your backend server: ```bash # If using TypeScript directly npx tsx server.ts # Or compile and run npx tsc server.ts && node server.js ``` ```bash fastapi run --port 3000 ``` ## Step 8: Test your backend Test your endpoint: ```bash curl -X POST http://localhost:3000/join-room \ -H "Content-Type: application/json" \ -d '{"roomName": "test-room", "peerName": "test-user"}' ``` ```bash curl -X POST http://localhost:3000/join-room \ -H "Content-Type: application/json" \ -d '{"room_name": "test-room", "peer_name": "test-user"}' ``` You should receive a response with: - `roomId` / `room_id` - The ID of the created room - `peerToken` / `peer_token` - Token for the client to join the room ## Complete example Here's a complete working backend: ```ts process.env.FISHJAM_ID = ""; process.env.FISHJAM_MANAGEMENT_TOKEN = ""; // ---cut--- const app = express(); app.use(express.json()); const fishjamClient = new FishjamClient({ fishjamId: process.env.FISHJAM_ID!, managementToken: process.env.FISHJAM_MANAGEMENT_TOKEN! }); app.post('/join-room', async (req, res) => { try { const { roomName, peerName } = req.body; const room = await fishjamClient.createRoom(); const { peer, peerToken } = await fishjamClient.createPeer(room.id, { metadata: { name: peerName }, }); res.json({ roomId: room.id, peerToken, }); } catch (error: any) { res.status(500).json({ error: error.message }); } }); app.listen(3000, () => { console.log('Fishjam backend running on port 3000'); }); ``` ```python from fastapi import FastAPI, HTTPException from pydantic import BaseModel from fishjam import FishjamClient, PeerOptions app = FastAPI() fishjam_client = FishjamClient( os.environ["FISHJAM_ID"], os.environ["FISHJAM_MANAGEMENT_TOKEN"] ) class JoinRoomRequest(BaseModel): room_name: str peer_name: str @app.post("/join-room") async def join_room(request: JoinRoomRequest): try: room = fishjam_client.create_room() options = PeerOptions(metadata={"name": request.peer_name}) peer, peer_token = fishjam_client.create_peer(room.id, options=options) return { "room_id": room.id, "peer_token": peer_token } except Exception as e: raise HTTPException(status_code=500, detail=str(e)) ``` ## Next steps Now that you have a working backend, explore these guides: - [How to set up a production deployment](../how-to/backend/production-deployment) - [How to handle webhooks and events](../how-to/backend/server-setup#webhooks) - [How to implement a FastAPI backend](../how-to/backend/fastapi-example) - [How to implement a Fastify backend](../how-to/backend/fastify-example) Or learn more about Fishjam concepts: - [Understanding security and tokens](../explanation/security-tokens) - [Rooms](../explanation/rooms) --- ## Add background blur to your camera Mobile # Add background blur to your camera Mobile :::note This tutorial is exclusively for **Mobile** (React Native) applications. ::: This tutorial continues from the [React Native Quick Start](./react-native-quick-start). You'll take the video call app you built there and add a button that blurs the background of your camera, for you and for everyone else in the room. ## What you'll build The Quick Start video call app with a **Blur on / Blur off** button. When blur is on, other participants see you sharp in front of a blurred background. ## What you'll learn - How to install and configure `@fishjam-cloud/video-effects` - How to load the bundled segmentation model - How to turn an effect into a camera middleware and switch it on and off with `useCamera` ## Prerequisites - The finished app from the [React Native Quick Start](./react-native-quick-start), on Expo SDK 57 (React Native 0.86) with the New Architecture enabled - `@fishjam-cloud/react-native-client` **0.30.2** or newer, `@fishjam-cloud/video-effects` **0.1.5** or newer and `react-native-webgpu` **0.10.1** or newer - A physical device (iOS 16.4+ or Android 8.0+), or the iOS Simulator with a virtual camera from [SimCam](../how-to/client/ios-simulator-camera.mdx) - A second device or simulator to join the room and see the result ## Step 1: Install and configure ### Install the packages ```bash npm2yarn npm install @fishjam-cloud/video-effects @fishjam-cloud/react-native-worklets react-native-worklets react-native-webgpu expo-asset expo-file-system expo-build-properties npm install --save-dev unplugin-typegpu @babel/plugin-transform-class-static-block ``` - `@fishjam-cloud/video-effects` contains the blur effect and the model that finds you in the picture. - `@fishjam-cloud/react-native-worklets` and `react-native-worklets` run the effect on every camera frame, off the JS thread. - `react-native-webgpu` gives the effect a GPU to draw with. - `expo-asset` and `expo-file-system` load the model file that ships inside `@fishjam-cloud/video-effects`. - `expo-build-properties` raises the Android minimum SDK version. ### Update the Babel config The effect code needs the worklets Babel plugin, and TypeGPU (the GPU library it is written with) needs its own plugin, class static blocks and `import.meta`. Replace your `babel.config.js`, keeping `react-native-worklets/plugin` last: ```js title='babel.config.js' module.exports = function (api) { api.cache(true); return { presets: [["babel-preset-expo", { unstable_transformImportMeta: true }]], plugins: [ "@babel/plugin-transform-class-static-block", "unplugin-typegpu/babel", "react-native-worklets/plugin", ], }; }; ``` ### Let Metro bundle the model The model ships as a `.ssgbin` file, which Metro doesn't bundle by default. Create `metro.config.js` in your project root: ```js title='metro.config.js' const { getDefaultConfig } = require("expo/metro-config"); const config = getDefaultConfig(__dirname); config.resolver.assetExts = [...config.resolver.assetExts, "ssgbin"]; module.exports = config; ``` ### Raise the minimum OS versions Expo SDK 57 needs iOS 16.4, and `react-native-webgpu` needs Android 8.0 (API 26), while Expo builds for API 24 by default. Set both in `app.json`: the iOS version in the Fishjam config plugin, the Android one with `expo-build-properties`: ```json title='app.json' { "expo": { "plugins": [ [ "@fishjam-cloud/react-native-client", { "ios": { "iphoneDeploymentTarget": "16.4" } } ], [ "expo-build-properties", { "android": { "minSdkVersion": 26 } } ] ] } } ``` If you already configure the Fishjam plugin, add `iphoneDeploymentTarget` to its existing `ios` options. Without the Android setting, the Android build fails with `'AHardwareBuffer_allocate' is unavailable: introduced in Android 26`. ### Rebuild the app The new packages contain native code, so a JS reload is not enough: ```bash npx expo prebuild npx expo run:ios # or run:android ``` ```bash cd ios && pod install ``` Start Metro with a cleared cache afterwards (`npx expo start --clear`), so the new Babel config is picked up. ## Step 2: Load the segmentation model To blur the background, the effect first has to find you in every frame. A segmentation model does that on the GPU. Create `effects.ts` next to `App.tsx` and set up the model: ```ts title='effects.ts' const segmentationModel = Asset.fromModule( require("@fishjam-cloud/video-effects/assets/selfie_segmenter.ssgbin"), ); // Android release builds can't fetch a bundled asset by URL, so read it from a local copy. async function loadSegmentationModel(): Promise { await segmentationModel.downloadAsync(); if (!segmentationModel.localUri) { throw new Error("The segmentation model is not available."); } return new File(segmentationModel.localUri).arrayBuffer(); } const segmentation = typeGpuPersonSegmentation({ loadModel: loadSegmentationModel, }); ``` Nothing is loaded yet: `typeGpuPersonSegmentation` only describes where the model comes from. The model is loaded the first time you switch blur on. ## Step 3: Create the blur middleware Fishjam lets you put a [middleware](../how-to/client/camera-effects/stream-middleware.mdx) between your camera and the room: a function that receives the camera track and returns the track to publish instead. `createCameraEffectMiddleware` turns an effect into such a middleware. Add the blur to the end of `effects.ts`: ```ts title='effects.ts' declare const segmentation: PersonSegmentationProvider; // ---cut--- export const backgroundBlur = createCameraEffectMiddleware( createBackgroundBlurEffect(() => ({ segmentation, radius: 24 })), ); ``` `radius` sets how strong the blur is, from `0` to `40`. The middleware is created once, at module scope, so it keeps the same identity for the whole app. You'll use that in the next step to tell whether blur is on. ## Step 4: Add a blur button `useCamera` gives you two things for middleware: `setCameraTrackMiddleware` to set it, and `currentCameraMiddleware` to read what is set. Blur is on when the current middleware is `backgroundBlur`. Add a button component to `App.tsx`: ```tsx declare const backgroundBlur: NonNullable; // ---cut--- function BlurButton() { const { currentCameraMiddleware, setCameraTrackMiddleware } = useCamera(); const isBlurOn = currentCameraMiddleware === backgroundBlur; const toggleBlur = async () => { try { await setCameraTrackMiddleware(isBlurOn ? null : backgroundBlur); } catch (error) { console.warn("Background blur failed", error); await setCameraTrackMiddleware(null); // go back to the plain camera } }; return ( ; } ``` ## Step 3: Display other participants Show video from other peers: ```tsx function VideoPlayer({ stream }: { stream: MediaStream | null | undefined }) { const videoRef = useRef(null); useEffect(() => { if (!videoRef.current) return; videoRef.current.srcObject = stream ?? null; }, [stream]); return