页面简介
A walkthrough of how a Dialog-RSN-1 realtime conversation works: the connection, the session, and the shape of a turn, ending in one complete runnable example.
正文摘录
This page walks through connecting to Dialog-RSN-1, configuring the session and running one turn, then puts it together as a short Python script that saves the spoken reply to a WAV file. Prerequisites: an API key and a WebSocket client in any language. Getting an API key You create the key in Dialog Studio at studio.poly.ai: Go to studio.poly.ai and sign up, or log in if you already have an account. Open the API Keys tab in your workspace’s top bar, then select API key. Give the key a name. Leave Agents on All agents, and leave at least one Resource Access permission on. The form needs one, and Dialog-RSN-1 accepts the key whichever you pick. Select Create, then copy the key. It’s only shown once. Store it in an environment variable, such as POLY_API_KEY, or in a secret manager rather than in source control. Match the host to the Studio that issued the key. A key from studio.poly.ai only works on api.studio.poly.ai, which every sample in these docs uses. If your workspace lives on a regional Studio, such as studio.us.poly.ai, connect to that region’s host instead: wss://api.us.poly.ai/v1/realtime. A key on the wrong host gets a bare 401 with {"message":"Unauthorized"}, the same answer as a wrong key. In the samples below, change URL. Most guide repos read it from DIALOG_REALTIME_URL. Connecting One WebSocket carries the whole conversation. You authenticate once when you connect, and every turn travels over the same socket as JSON text frames. To open it, connect and send your API key in the X-API-KEY header: connectURL: wss://api.studio.poly.ai/v1/realtime Header: X-API-KEY: YOUR_API_KEY Authorization: Bearer YOUR_API_KEY works too, so an existing realtime client, including the official openai SDK, keeps its auth and only needs a new URL and key. Keep your key server-side. Treat it like any API credential: call it from a server or trusted backend, not from code that ships to a browser or a device you don’t control. A browser’s native WebSocket can’t set headers at all, so connecting from a page means putting a relay in front, as the browser guide covers. The moment the connection is accepted, before you’ve sent anything, the server sends you a session.created event. You’re already in a session with the default settings: 24 kHz PCM16 audio in, server turn detection, and spoken replies. Telling it how to behave Send session.update with your instructions, tools, and anything else you want to change. The server replies with session.updated, echoing back the full configuration in effect. you send: session.update{ "type": "session.update", "session": { "instructions": "You are a helpful assistant." } } A new session speaks its replies, so you get each reply as audio plus a transcript of what it says, with no text-to-speech of your own. To speak replies with your own voice instead, see bring your own text-to-speech below. You can send another session.update at any point in the conversation. The shape of a turn Adding something to the conversation and asking for a response to it are separate events: you send: conversation.item.create{ "type": "conversation.item.create", "item": { "type": "message", "role": "user", "content": [{ "type": "input_text", "text": "What's the capital of France?" }] } } you send: response.create{ "type": "response.create" } Because they’re separate, you can seed a conversation with prior history without firing a reply at each item. Tool results work the same way: you add the result, then send response.create for the follow-up. For a single question, send one straight after the other. Watching the answer arrive The reply comes back as a stream of events. You need three of them to hold a conversation: response.output_audio_transcript.delta carries the words of the reply. Append them to see what it says. response.output_audio.delta carries the speech: base64 PCM16 audio, 24 kHz mono. Play it, or collect it. response.done tells you the turn is over and how it ended. server sends: the responseresponse.created response.output_item.added response.content_part.added response.output_audio_transcript.delta delta: "The capital " response.output_audio_transcript.delta delta: "of France is Paris." response.output_audio.delta delta: "<base64 PCM16>" response.output_audio.delta delta: "<base64 PCM16>" response.output_audio.done response.output_audio_transcript.done response.content_part.done response.output_item.done response.done response.status: "completed" dialog-rsn-1: “The capital of France is Paris.” The audio streams at speaking pace, so response.done arrives once the reply has been spoken. The other events track which output item the server is writing and where its content part begins and ends, which a fuller integration uses. For a longer conversation, repeat the same steps: add an item, ask for a response, and collect the deltas until response.done. Each new message builds on the conversation so far, so you have no separate history to maintain. All of it, together The same sequence as one script, running on the standard websockets package. It prints the reply as it streams and saves the speech to reply.wav. You need Python 3.10 or later, pip install 'websockets>=14', and POLY_API_KEY set in your shell. The version floor matters: connect() took extra_headers before websockets 14 and additional_headers from 14 on, so the script below raises TypeError on an older install rather than failing to authenticate. python# pip install 'websockets>=14' import asyncio, base64, json, os, wave, websockets URL = "wss://api.studio.poly.ai/v1/realtime" API_KEY = os.environ["POLY_API_KEY"] async def main(): headers = {"X-API-KEY": API_KEY} async with websockets.connect(URL, additional_headers=headers) as ws: await ws.recv() # session.created await ws.send(json.dumps({ "type": "session.update", "session": {"instructions": "You are a helpful assistant."}, })) event = json.loads(await ws.recv()) if event["type"] != "session.updated": raise RuntimeError(event["error"]["message"]) await ws.send(json.dumps({ "type": "conversation.item.create", "item": { "type": "message", "role": "user", "content": [{"type": "input_text", "text": "What's the capital of France?"}], }, })) await ws.send(json.dumps({"type": "response.create"})) audio = bytearray() async for raw in ws: event = json.loads(raw) if event["type"] == "response.output_audio_transcript.delta": print(event["delta"], end="", flush=True) elif event["type"] == "response.output_audio.delta": audio += base64.b64decode(event["delta"]) elif event["type"] == "error": # The connection stays open after an error, so a turn can fail without the # socket closing. Without this branch the script exits with nothing said. raise RuntimeError(event["error"]["message"]) elif event["type"] == "response.done": status = event["response"]["status"] if status != "completed": raise RuntimeError(f"response {status}") print() break with wave.open("reply.wav", "wb") as wav: wav.setnchannels(1) wav.setsampwidth(2) # PCM16 wav.setframerate(24000) wav.writeframes(audio) print(f"Saved {len(audio) / 48000:.1f} s of audio to reply.wav") asyncio.run(main()) outputThe capital of France is Paris. Saved 2.5 s of audio to reply.wav Play reply.wav in any audio player, or with afplay reply.wav on macOS. Keep the error branch. Almost every failure on this API answers with an error event and leaves the connection open, so a turn that fails arrives as an event rather than a dropped socket. The few that close the socket, such as an oversized frame or an idle connection, are listed under close codes. Skip the branch and a failed generation prints nothing and exits zero. The same goes for session.update: a refused update answers with error instead of session.updated and applies nothing, which is why the script checks the reply. Bring your own text-to-speech The server’s voice is the quickest way to a spoken reply. When you want your own voice, your own TTS vendor, or control over playback, ask for text instead. Set output_modalities to ["text"]: you send: session.update{ "type": "session.update", "session": { "instructions": "You are a helpful assistant.", "output_modalities": ["text"] } } The reply then streams as response.output_text.delta, with no audio events, and you speak it however you like. In the script above, add "output_modalities": ["text"] to the session and read response.output_text.delta in place of response.output_audio_transcript.delta. The streaming text-to-speech guide takes it from there. Ask for one or the other: ["text", "audio"] is refused. Session setup by use case The script above sends text in. A voice agent streams the caller’s audio in with input_audio_buffer.append, and Dialog-RSN-1 decides when the caller has finished, transcribes the turn and answers it in the same response. From there, set up the session for what you’re building: You’re buildingSet upA voice agent with barge-inNothing to configure. A new session has server turn detection and spoken replies. Pick a voice with audio.output.voiceA push-to-talk UIturn_detection: null. Everything you append is one turn until your input_audio_buffer.commit, and nothing answers it until your response.create. No speech events are sent, and there’s no barge-inVoice in, with your own timing for repliescreate_response: false in turn_detection, then send response.create yourself after each turnA text chat UIoutput_modalities: ["text"]. Add each message with conversation.item.create, then send response.createAn agent with toolsDeclare tools in session.update. Answer each call with a function_call_output item, then a fresh response.create. See Tools and knowledgeAn agent that answers from your knowledge basePass retrieved passages as poly_knowledge, and read poly_cited_topics on response.done. See Tools and knowledgeAn agent in your own voice or TTS vendoroutput_modalities: ["text"], and send playback reports. See Using your own text-to-speechTranscription onlyA transcription session. See Speech to text Common mistakes Reading text deltas from