Voice Agent

البدء السريع مع Voice Agent

ابدأ جلسة Voice Agent من خادمك الخلفي وتحدث مع الوكيل من صفحة ويب في نحو خمس دقائق.

تضيف إلى خادمك الخلفي مسارًا واحدًا يبدأ جلسة، وصفحة ويب واحدة تنضم إليها.

قبل أن تبدأ

  • مفتاح API من لوحة تحكم HUMAIN Voice (المصادقة) بالنطاق agent: افتح المفتاح من API keys وفعّله. لا تملكه المفاتيح الجديدة، وبدونه يعيد طلب الجلسة 403 AUTH_SCOPE_MISSING.
  • Node.js 24 أو أحدث، أو Python 3.10 أو أحدث، للخادم الخلفي. ويُستخدم Node.js أيضًا لتجميع الصفحة.

1. التثبيت

npm install @humain-voice/[email protected] @humain-voice/[email protected] livekit-client express
npm install --save-dev esbuild @types/express

2. اضبط بيئتك

export API_URL="https://api.voice.humain.com"
export API_KEY="YOUR_API_KEY"

3. أضف مسار جلسة إلى خادمك الخلفي

server.ts أو server.py. استبدل user-123 بمعرّفك الخاص للمستخدم المسجّل دخوله.

import express from 'express';
import { AgentClient } from '@humain-voice/sdk/agent';

function requiredEnv(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`${name} is required`);
  return value;
}

const agent = new AgentClient({ api_url: requiredEnv('API_URL'), api_key: requiredEnv('API_KEY') });
const app = express();
app.use(express.static('public'));

app.post('/agent-session', async (_req, res) => {
  try {
    const session = await agent.createSession({
      participant: { identity: 'user-123' },
      agent: {
        prompt: 'You are the assistant of a bakery in Riyadh. Keep answers short.',
        intro: 'Hello! How can I help you today?',
      },
    });
    res.json(session.tokenResponse());
  } catch (err) {
    console.error('error:', err);
    res.status(502).json({ error: 'could not start a session' });
  }
});

app.listen(3000, () => console.log('open http://localhost:3000'));

4. أضف صفحة الويب

public/index.html. قدّمها من localhost أو عبر HTTPS، وإلا حجب المتصفح الميكروفون:

<!doctype html>
<html lang="en">
  <body>
    <button id="talk">Talk to the agent</button>
    <p id="status">idle</p>
    <script type="module" src="./agent.js"></script>
  </body>
</html>

agent.ts:

import { AgentSession } from '@humain-voice/agent';

const button = document.querySelector<HTMLButtonElement>('#talk')!;
const status = document.querySelector<HTMLParagraphElement>('#status')!;
let call: AgentSession | undefined;

button.addEventListener('click', async () => {
  if (call) {
    await call.end();
    return;
  }
  call = await AgentSession.start({
    token: () => fetch('/agent-session', { method: 'POST' }).then((res) => res.json()),
    onStatusChange: (value) => (status.textContent = value),
    onModeChange: (mode) => (status.textContent = mode),
    onMessage: (message) => {
      if (message.final) console.log(`${message.role}: ${message.text}`);
    },
    onEnd: ({ reason }) => {
      status.textContent = `ended: ${reason}`;
      button.textContent = 'Talk to the agent';
      call = undefined;
    },
  });
  button.textContent = 'Hang up';
});

جمّعه في الصفحة:

npx esbuild agent.ts --bundle --format=esm --outfile=public/agent.js

5. تحدث مع الوكيل

node server.ts

افتح http://localhost:3000 واختر Talk to the agent.

في هذه الصفحة