Using WebSocket Tools

This guide shows how to extend a basic WebSocket conversation to work with WebSocket tools.

While this guide runs through creating and using a sync WebSocket tool, the core workflow remains the same with async WebSocket tools.

Full working examples in both Node and Python are available in the Phonic examples repository.

Prerequisites

Before adding tools to your WebSocket conversation, you should have:

Adding Tool Support

To handle tool calls in your existing WebSocket server, you need to:

  1. Listen for tool_call messages from Phonic
  2. Process the tool call with your business logic
  3. Send back a tool_call_output message with the result

Step 1: Create Your Tools

First, create WebSocket tools that your agent can use:

1import { PhonicClient } from "phonic";
2
3const phonic = new PhonicClient({ apiKey: process.env.PHONIC_API_KEY });
4
5await phonic.tools.create({
6 name: "get_temperature",
7 description: "Get the current temperature for a specific city",
8 type: "custom_websocket",
9 execution_mode: "sync",
10 parameters: [
11 {
12 type: "string",
13 name: "city",
14 description: "The city to get the temperature for",
15 is_required: true,
16 },
17 ],
18});

Step 2: Create Your Agent

Add the tools to your agent’s configuration:

1await phonic.agents.create({
2 name: "weather-assistant",
3 tools: ["get_temperature"], // Add your tool here
4 // ... other agent configuration
5});

Step 3: Handle Tool Calls in Your WebSocket Server

Modify your existing WebSocket message handler to process tool_call messages:

1// Add to your existing phonicSocket message handler
2phonicSocket.on("message", async (message) => {
3 // Your existing handlers for audio_chunk, etc...
4
5 // Add: Handle tool calls
6 if (message.type === "tool_call") {
7 switch (message.tool_name) {
8 case "get_temperature": {
9 const { city } = message.parameters;
10
11 // Your implementation
12 const temperature = await getTemperature(city);
13
14 // Send result back to Phonic
15 await phonicSocket.sendToolCallOutput({
16 type: "tool_call_output",
17 tool_call_id: message.tool_call_id,
18 output: {
19 city: city,
20 temperature: "75°F"
21 },
22 });
23 break;
24 }
25 }
26 }
27});
See the complete examples in our examples repository.