Text Chat Embedding - Hızlı Başlangıç

AI asistanınızı metin sohbet arayüzü olarak web sitenize entegre edin

Text Chat Embedding Nedir?

Text Chat Embedding, Wespoke AI asistanlarınızı web sitenize metin tabanlı sohbetarayüzü olarak entegre etmenizi sağlar. Sesli aramalardan farklı olarak, kullanıcılarmikrofon gerektirmeden yazarak asistanınızla iletişim kurabilir.

REST API ve SSE (Server-Sent Events) kullanarak gerçek zamanlı streaming yanıtlaralırsınız. Sadece LLM maliyeti olduğu için sesli aramalardan %40-50 daha ucuzdur.

Sesli Arama vs Text Chat

ÖzellikSesli AramaText Chat
BağlantıWebRTCREST + SSE
BileşenlerSTT + LLM + TTSSadece LLM
Python AgentGerekliGerekli Değil
Maliyet (5 dk)~$0.20~$0.12
Gecikme~500-800ms~200-400ms
Kullanım SenaryosuSesli konuşmalarMetin sohbet arayüzleri

Kurulum Adımları

1

API Anahtarı Oluşturun

Kontrol panelinden bir API anahtarı oluşturun ve sitenizin domain adresiniizin verilenler listesine ekleyin.

API Anahtarları Sayfasına Git
2

Sohbet Oturumu Başlatın

/api/v1/embed/chat endpoint'inePOST isteği göndererek yeni bir sohbet oturumu oluşturun.

Sohbet Oturumu Başlatma
const response = await fetch('https://api.wespoke.ai/api/v1/embed/chat', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer pk_live_abc123...'
  },
  body: JSON.stringify({
    assistantId: 'asst_xyz789',
    metadata: {
      userId: 'user-123',
      sessionId: 'session-456'
    }
  })
});

const data = await response.json();
const chatId = data.data.chatId;  // Store this ID
console.log('Chat started:', chatId);
Yanıt:
Başarılı Yanıt
{
  "success": true,
  "data": {
    "chatId": "cm1abc123",
    "assistant": {
      "id": "asst_xyz789",
      "name": "Customer Service Assistant",
      "version": 1
    },
    "startedAt": "2025-01-02T10:00:00.000Z"
  }
}
3

Mesaj Gönderin (SSE Streaming)

POST isteği ile mesaj gönderin ve EventSource ile gerçek zamanlı yanıtları alın.

Mesaj Gönderme ve SSE Dinleme
// 1. Send the message
await fetch(`https://api.wespoke.ai/api/v1/embed/chat/${chatId}/messages`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer pk_live_abc123...'
  },
  body: JSON.stringify({
    content: 'Hello, I need help'
  })
});

// 2. SSE eventlerini dinleyin
// Note: In a real application you should use EventSource
// This is a simplified example

// SSE Event Types:
// - message:start     → Assistant response started
// - message:chunk     → Text chunk (word by word)
// - message:complete  → Message completed
// - tool:started      → Tool is executing
// - tool:completed    → Tool completed
// - knowledge:used    → Knowledge base used
// - done              → Stream bitti

console.log('Assistant response streaming...');

Tam Çalışan Örnek

Basit bir HTML sayfası ile text chat entegrasyonu:

index.html - Basit Text Chat
<!DOCTYPE html>
<html>
<head>
  <title>Wespoke Text Chat</title>
  <style>
    body {
      font-family: system-ui, -apple-system, sans-serif;
      max-width: 600px;
      margin: 50px auto;
      padding: 20px;
    }
    #messages {
      border: 1px solid #ddd;
      height: 400px;
      overflow-y: auto;
      padding: 15px;
      margin-bottom: 15px;
      border-radius: 8px;
    }
    .message {
      margin: 10px 0;
      padding: 10px;
      border-radius: 6px;
    }
    .user {
      background: #e3f2fd;
      text-align: right;
    }
    .assistant {
      background: #f1f8e9;
    }
    #input-area {
      display: flex;
      gap: 10px;
    }
    input {
      flex: 1;
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 6px;
    }
    button {
      padding: 10px 20px;
      background: #2196f3;
      color: white;
      border: none;
      border-radius: 6px;
      cursor: pointer;
    }
    button:disabled {
      background: #ccc;
      cursor: not-allowed;
    }
  </style>
</head>
<body>
  <h1>Wespoke Text Chat</h1>
  <div id="messages"></div>
  <div id="input-area">
    <input type="text" id="message-input" placeholder=={t('mesajınızıYazın')} />
    <button id="send-btn">{t('gönder')}</button>
    <button id="end-btn">End</button>
  </div>

  <script>
    const API_KEY = 'pk_YOUR_API_KEY';
    const ASSISTANT_ID = 'asst_YOUR_ASSISTANT_ID';
    const API_BASE = 'https://api.wespoke.ai/api/v1/embed';

    let chatId = null;

    const messagesDiv = document.getElementById('messages');
    const input = document.getElementById('message-input');
    const sendBtn = document.getElementById('send-btn');
    const endBtn = document.getElementById('end-btn');

    // Initialize chat session
    async function initChat() {
      try {
        const response = await fetch(`${API_BASE}/chat`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${API_KEY}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            assistantId: ASSISTANT_ID,
            metadata: {
              userId: 'web-user-' + Date.now()
            }
          })
        });

        const data = await response.json();
        if (data.success) {
          chatId = data.data.chatId;
          addSystemMessage(`Connected to ${data.data.assistant.name}`);
        } else {
          alert('Connection error: ' + data.error.message);
        }
      } catch (error) {
        console.error('Init error:', error);
        alert('Could not connect');
      }
    }

    // Send message
    async function sendMessage() {
      if (!chatId || !input.value.trim()) return;

      const userMessage = input.value.trim();
      addMessage('user', userMessage);
      input.value = '';
      sendBtn.disabled = true;

      try {
        const response = await fetch(`${API_BASE}/chat/${chatId}/messages`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${API_KEY}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ content: userMessage })
        });

        // You can use EventSource here for SSE streaming
        // For this simple example we read the response body

        // Show assistant response
        addMessage('assistant', 'Processing response...');

      } catch (error) {
        console.error('Send error:', error);
        addMessage('assistant', '[Error: Failed to send message]');
      } finally {
        sendBtn.disabled = false;
      }
    }

    // End chat
    async function endChat() {
      if (!chatId) return;

      try {
        const response = await fetch(`${API_BASE}/chat/${chatId}/end`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${API_KEY}`
          }
        });

        const data = await response.json();
        if (data.success) {
          const cost = data.data.cost.toFixed(4);
          addSystemMessage(`Chat ended. Cost: $${cost}`);
          sendBtn.disabled = true;
          endBtn.disabled = true;
        }
      } catch (error) {
        console.error('End error:', error);
      }
    }

    // Helper functions
    function addMessage(role, content) {
      const div = document.createElement('div');
      div.className = `message ${role}`;
      div.textContent = content;
      messagesDiv.appendChild(div);
      messagesDiv.scrollTop = messagesDiv.scrollHeight;
    }

    function addSystemMessage(content) {
      const div = document.createElement('div');
      div.style.textAlign = 'center';
      div.style.color = '#666';
      div.style.fontSize = '0.9em';
      div.style.margin = '10px 0';
      div.textContent = content;
      messagesDiv.appendChild(div);
    }

    // Event listeners
    sendBtn.addEventListener('click', sendMessage);
    endBtn.addEventListener('click', endChat);
    input.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') sendMessage();
    });

    // Initialize
    initChat();
  </script>
</body>
</html>

Önemli Notlar

  • Güvenlik: API anahtarınızı backend'de saklayın (mümkünse)
  • Domain Kontrolü: API anahtarınızın izin verilen domain listesine sitenizin adresini ekleyin
  • Kayıt: Text chat oturumları otomatik olarak kaydedilir
  • Fiyatlandırma: Sadece LLM maliyeti, sesli aramalardan %40-50 daha ucuz
  • SSE Streaming: Gerçek zamanlı yanıtlar için EventSource kullanın
  • HTTPS Gerekli Değil: Metin chat için HTTP yeterlidir (mikrofon erişimi yok)