> This is a page from the ElevenLabs documentation. For a complete page index, fetch https://elevenlabs.io/docs/llms.txt. For the full documentation in a single file, fetch https://elevenlabs.io/docs/llms-full.txt.

# WebSocket

> **Note**
>
> यह दस्तावेज़ सीधे ElevenLabs WebSocket API इंटीग्रेट करने वाले डेवलपर्स के लिए है। सुविधा के लिए,
> [ElevenLabs के आधिकारिक SDKs](/docs/hi/eleven-agents/libraries/python) इस्तेमाल करने पर विचार करें।

[ElevenAgents](https://elevenlabs.io/agents) WebSocket API, AI एजेंट्स के साथ रीयल-टाइम और इंटरैक्टिव वॉइस बातचीत संभव बनाती है। WebSocket कनेक्शन बनाकर, आप ऑडियो इनपुट भेज सकते हैं और रीयल-टाइम में ऑडियो जवाब पा सकते हैं, जिससे इंसानों जैसी बातचीत का अनुभव बनता है।

> **Note**
>
> एंडपॉइंट: `wss://api.elevenlabs.io/v1/convai/conversation?agent_id={agent_id}`

## ऑथेंटिकेशन

### Agent ID का इस्तेमाल

सार्वजनिक एजेंट्स के लिए, आप बिना अतिरिक्त ऑथेंटिकेशन के सीधे WebSocket URL में `agent_id` इस्तेमाल कर सकते हैं:

```bash
wss://api.elevenlabs.io/v1/convai/conversation?agent_id=<your-agent-id>
```

### साइन किए गए URL का इस्तेमाल

निजी एजेंट्स या ऑथराइज़ेशन वाली बातचीत के लिए, अपने सर्वर से एक साइन किया हुआ URL लें, जो आपकी API key के साथ ElevenLabs API से सुरक्षित रूप से संवाद करता है।

### cURL का उदाहरण

**रिक्वेस्ट:**

```bash
curl -X GET "https://api.elevenlabs.io/v1/convai/conversation/get-signed-url?agent_id=<your-agent-id>" \
     -H "xi-api-key: <your-api-key>"
```

**रिस्पॉन्स:**

```json
{
  "signed_url": "wss://api.elevenlabs.io/v1/convai/conversation?agent_id=<your-agent-id>&token=<token>"
}
```

> **Warning**
>
> अपनी ElevenLabs API key को कभी भी क्लाइंट साइड पर एक्सपोज़ न करें।

## WebSocket इवेंट्स

### क्लाइंट से सर्वर इवेंट्स

क्लाइंट से सर्वर को ये इवेंट्स भेजे जा सकते हैं:

#### कॉन्टेक्स्चुअल अपडेट्स

बातचीत की स्थिति अपडेट करने के लिए बिना रुकावट वाली प्रासंगिक जानकारी भेजें। इससे आप चल रही बातचीत के प्रवाह को बाधित किए बिना अतिरिक्त संदर्भ दे सकते हैं।

```javascript
{
  "type": "contextual_update",
  "text": "User clicked on pricing page"
}
```

**इस्तेमाल के मामले:**

* यूज़र की स्थिति या पसंद अपडेट करना
* परिवेश का संदर्भ देना
* बैकग्राउंड जानकारी जोड़ना
* यूज़र इंटरफ़ेस इंटरैक्शन ट्रैक करना

**मुख्य बातें:**

* मौजूदा बातचीत के प्रवाह को बाधित नहीं करता
* अपडेट्स को बातचीत के इतिहास में टूल कॉल्स के रूप में शामिल किया जाता है
* प्राकृतिक संवाद को बाधित किए बिना संदर्भ बनाए रखने में मदद करता है

> **Note**
>
> कॉन्टेक्स्चुअल अपडेट्स असिंक्रोनस तरीके से प्रोसेस होते हैं और इनके लिए सर्वर से सीधे जवाब की ज़रूरत नहीं होती।

#### [WebSocket API रेफरेंस](/docs/hi/eleven-agents/api-reference/eleven-agents/websocket)

विस्तृत मैसेज स्ट्रक्चर, पैरामीटर्स और उदाहरणों के लिए ElevenLabs Agents WebSocket API रेफरेंस दस्तावेज़ देखें।

## Next.js इम्प्लीमेंटेशन का उदाहरण

यह उदाहरण दिखाता है कि ElevenLabs WebSocket API का इस्तेमाल करके Next.js में WebSocket-आधारित कन्वर्सेशनल एजेंट क्लाइंट कैसे इम्प्लीमेंट करें।

> **Note**
>
> हालांकि इस उदाहरण में माइक्रोफ़ोन इनपुट को संभालने के लिए `voice-stream` पैकेज का इस्तेमाल किया गया है, आप
> ऑडियो कैप्चर और एन्कोड करने के लिए अपना समाधान इम्प्लीमेंट कर सकते हैं। यहां फोकस
> ElevenLabs API के साथ WebSocket कनेक्शन और इवेंट हैंडलिंग दिखाने पर है।

#### ज़रूरी डिपेंडेंसीज़ इंस्टॉल करें

पहले, ज़रूरी पैकेज इंस्टॉल करें:

```bash
npm install voice-stream
```

`voice-stream` पैकेज माइक्रोफ़ोन एक्सेस और ऑडियो स्ट्रीमिंग संभालता है और ElevenLabs API की आवश्यकता के अनुसार ऑडियो को अपने-आप base64 फ़ॉर्मैट में एन्कोड करता है।

> **Note**
>
> इस उदाहरण में स्टाइलिंग के लिए Tailwind CSS का इस्तेमाल किया गया है। अपने Next.js प्रोजेक्ट में Tailwind जोड़ने के लिए:
>
> ```bash
> npm install -D tailwindcss postcss autoprefixer
> npx tailwindcss init -p
> ```
>
> फिर [Next.js के लिए आधिकारिक Tailwind CSS सेटअप गाइड](https://tailwindcss.com/docs/guides/nextjs) फॉलो करें।
>
> वैकल्पिक रूप से, आप className एट्रिब्यूट्स को अपनी CSS स्टाइल्स से बदल सकते हैं।

#### WebSocket टाइप्स बनाएं

WebSocket इवेंट्स के लिए टाइप्स तय करें:

**`app/types/websocket.ts`**

```typescript app/types/websocket.ts
type BaseEvent = {
  type: string;
};

type UserTranscriptEvent = BaseEvent & {
  type: "user_transcript";
  user_transcription_event: {
    user_transcript: string;
  };
};

type AgentResponseEvent = BaseEvent & {
  type: "agent_response";
  agent_response_event: {
    agent_response: string;
  };
};

type AgentResponseCorrectionEvent = BaseEvent & {
  type: "agent_response_correction";
  agent_response_correction_event: {
    original_agent_response: string;
    corrected_agent_response: string;
  };
};

type AudioResponseEvent = BaseEvent & {
  type: "audio";
  audio_event: {
    audio_base_64: string;
    event_id: number;
    alignment: {
      chars: string[];
      char_durations_ms: number[];
      char_start_times_ms: number[];
    };
  };
};

type InterruptionEvent = BaseEvent & {
  type: "interruption";
  interruption_event: {
    reason: string;
  };
};

type PingEvent = BaseEvent & {
  type: "ping";
  ping_event: {
    event_id: number;
    ping_ms?: number;
  };
};

type AgentChatResponsePartEvent = BaseEvent & {
  type: "agent_chat_response_part";
  text_response_part: {
    type: "start" | "delta" | "stop";
    text: string;
    event_id: number;
    response_id: string;
  };
};

export type ElevenLabsWebSocketEvent =
  | UserTranscriptEvent
  | AgentResponseEvent
  | AgentResponseCorrectionEvent
  | AudioResponseEvent
  | InterruptionEvent
  | PingEvent
  | AgentChatResponsePartEvent;
```

#### WebSocket हुक बनाएं

WebSocket कनेक्शन मैनेज करने के लिए एक कस्टम हुक बनाएं:

**`app/hooks/useAgentConversation.ts`**

```typescript app/hooks/useAgentConversation.ts
'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import { useVoiceStream } from 'voice-stream';
import type { ElevenLabsWebSocketEvent } from '../types/websocket';

const sendMessage = (websocket: WebSocket, request: object) => {
  if (websocket.readyState !== WebSocket.OPEN) {
    return;
  }
  websocket.send(JSON.stringify(request));
};

export const useAgentConversation = () => {
  const websocketRef = useRef<WebSocket>(null);
  const [isConnected, setIsConnected] = useState<boolean>(false);

  const { startStreaming, stopStreaming } = useVoiceStream({
    onAudioChunked: (audioData) => {
      if (!websocketRef.current) return;
      sendMessage(websocketRef.current, {
        user_audio_chunk: audioData,
      });
    },
  });

  const startConversation = useCallback(async () => {
    if (isConnected) return;

    const websocket = new WebSocket("wss://api.elevenlabs.io/v1/convai/conversation");

    websocket.onopen = async () => {
      setIsConnected(true);
      sendMessage(websocket, {
        type: "conversation_initiation_client_data",
      });
      await startStreaming();
    };

    websocket.onmessage = async (event) => {
      const data = JSON.parse(event.data) as ElevenLabsWebSocketEvent;

      // Handle ping events to keep connection alive
      if (data.type === "ping") {
        setTimeout(() => {
          sendMessage(websocket, {
            type: "pong",
            event_id: data.ping_event.event_id,
          });
        }, data.ping_event.ping_ms);
      }

      if (data.type === "user_transcript") {
        const { user_transcription_event } = data;
        console.log("User transcript", user_transcription_event.user_transcript);
      }

      if (data.type === "agent_response") {
        const { agent_response_event } = data;
        console.log("Agent response", agent_response_event.agent_response);
      }

      if (data.type === "agent_response_correction") {
        const { agent_response_correction_event } = data;
        console.log("Agent response correction", agent_response_correction_event.corrected_agent_response);
      }

      if (data.type === "interruption") {
        // Handle interruption
      }

      if (data.type === "audio") {
        const { audio_event } = data;
        // Implement your own audio playback system here
        // Note: You'll need to handle audio queuing to prevent overlapping
        // as the WebSocket sends audio events in chunks
      }

      if (data.type === "agent_chat_response_part") {
        const { text_response_part } = data;
        const { type: partType, text, response_id } = text_response_part;
        // Handle the agent's response text as it is generated. Enable
        // agent_chat_response_part in the agent's client_events to receive
        // this during voice conversations.
        console.log("Chat response part:", partType, text, response_id);
      }
    };

    websocketRef.current = websocket;

    websocket.onclose = async () => {
      websocketRef.current = null;
      setIsConnected(false);
      stopStreaming();
    };
  }, [startStreaming, isConnected, stopStreaming]);

  const stopConversation = useCallback(async () => {
    if (!websocketRef.current) return;
    websocketRef.current.close();
  }, []);

  useEffect(() => {
    return () => {
      if (websocketRef.current) {
        websocketRef.current.close();
      }
    };
  }, []);

  return {
    startConversation,
    stopConversation,
    isConnected,
  };
};
```

#### बातचीत का कंपोनेंट बनाएं

WebSocket हुक इस्तेमाल करने के लिए एक कंपोनेंट बनाएं:

**`app/components/Conversation.tsx`**

```typescript app/components/Conversation.tsx
'use client';

import { useCallback } from 'react';
import { useAgentConversation } from '../hooks/useAgentConversation';

export function Conversation() {
  const { startConversation, stopConversation, isConnected } = useAgentConversation();

  const handleStart = useCallback(async () => {
    try {
      await navigator.mediaDevices.getUserMedia({ audio: true });
      await startConversation();
    } catch (error) {
      console.error('Failed to start conversation:', error);
    }
  }, [startConversation]);

  return (
    <div className="flex flex-col items-center gap-4">
      <div className="flex gap-2">
        <button
          onClick={handleStart}
          disabled={isConnected}
          className="px-4 py-2 bg-blue-500 text-white rounded disabled:bg-gray-300"
        >
          Start Conversation
        </button>
        <button
          onClick={stopConversation}
          disabled={!isConnected}
          className="px-4 py-2 bg-red-500 text-white rounded disabled:bg-gray-300"
        >
          Stop Conversation
        </button>
      </div>
      <div className="flex flex-col items-center">
        <p>Status: {isConnected ? 'Connected' : 'Disconnected'}</p>
      </div>
    </div>
  );
}
```

## अगले चरण

1. **ऑडियो प्लेबैक**: Web Audio API या किसी लाइब्रेरी का इस्तेमाल करके अपना ऑडियो प्लेबैक सिस्टम इम्प्लीमेंट करें। WebSocket ऑडियो इवेंट्स को चंक्स में भेजता है, इसलिए ओवरलैपिंग रोकने के लिए ऑडियो क्यूइंग संभालना याद रखें।
2. **एरर हैंडलिंग**: रीट्राई लॉजिक और एरर रिकवरी मैकेनिज़्म जोड़ें
3. **UI फ़ीडबैक**: वॉइस गतिविधि और कनेक्शन स्थिति के लिए विज़ुअल इंडिकेटर्स जोड़ें

## लेटेंसी मैनेजमेंट

सुचारू बातचीत सुनिश्चित करने के लिए ये रणनीतियां अपनाएं:

* **एडैप्टिव बफ़रिंग:** नेटवर्क की स्थितियों के आधार पर ऑडियो बफ़रिंग समायोजित करें।
* **जिटर बफ़र:** पैकेट आने के समय में उतार-चढ़ाव को सहज बनाने के लिए जिटर बफ़र इम्प्लीमेंट करें।
* **पिंग-पोंग मॉनिटरिंग:** राउंड-ट्रिप समय मापने और उसके अनुसार समायोजन करने के लिए पिंग और पोंग इवेंट्स इस्तेमाल करें।

## सुरक्षा के सर्वोत्तम तरीके

* API keys को नियमित रूप से रोटेट करें और उन्हें स्टोर करने के लिए एनवायरनमेंट वेरिएबल्स इस्तेमाल करें।
* गलत इस्तेमाल रोकने के लिए रेट लिमिटिंग इम्प्लीमेंट करें।
* माइक्रोफ़ोन एक्सेस मांगते समय यूज़र्स को इसका उद्देश्य साफ़ तौर पर बताएं।
* ऑप्टिमाइज़्ड चंकिंग: लेटेंसी और दक्षता में संतुलन के लिए ऑडियो चंक की अवधि एडजस्ट करें।

## अतिरिक्त संसाधन

* [ElevenLabs Agents दस्तावेज़](/docs/hi/eleven-agents/overview)
* [ElevenLabs Agents SDKs](/docs/hi/eleven-agents/libraries/python)