OneLi ב־OpenAI Agents SDK

איך נותנים לסוכן שבנוי ב־OpenAI Agents SDK לבצע שיחות טלפון בעברית דרך OneLi, לעקוב אחרי השיחה, לענות להתייעצויות ולקבל את התוצאה.

ב־OpenAI Agents SDK מחברים את OneLi כשרת MCP מסוג Streamable HTTP, עם מפתח ה־API בכותרת. יש גם גרסה מתארחת שבה OpenAI עצמה פונה לשרת, וכלי פונקציה רגיל מעל ה־REST API.

התקנה

  1. יוצרים מפתח API ב־oneli.io/app/connect ושומרים אותו במשתנה הסביבה ONELI_API_KEY בשרת.
  2. מתקינים את החבילות:
Terminal
pip install openai-agents httpx   # or: npm i @openai/agents zod

נבדק מול: openai-agents 0.24.0 (Python) · @openai/agents 0.21.0 (JS)

Python: שרת MCP

Python
import asyncio, os
from agents import Agent, Runner
from agents.mcp import MCPServerStreamableHttp

async def main():
    async with MCPServerStreamableHttp(
        name="OneLi",
        params={"url": "https://mcp.oneli.io/mcp",
                "headers": {"Authorization": f"Bearer {os.environ['ONELI_API_KEY']}"},
                "timeout": 30},
        client_session_timeout_seconds=60,   # default 5s is too short
        cache_tools_list=True,
    ) as oneli:
        agent = Agent(name="Assistant", instructions="Use OneLi to place calls.", mcp_servers=[oneli])
        print((await Runner.run(agent, "Call +972… and book a table for 2 at 19:00")).final_output)

asyncio.run(main())

Python: MCP מתארח (OpenAI פונה לשרת)

Python
from agents import Agent, HostedMCPTool
agent = Agent(name="Assistant", tools=[HostedMCPTool(tool_config={
    "type": "mcp", "server_label": "oneli", "server_url": "https://mcp.oneli.io/mcp",
    "headers": {"Authorization": f"Bearer {os.environ['ONELI_API_KEY']}"}, "require_approval": "never"})])

Python: כלי פונקציה מעל REST

Python
import os, uuid, httpx
from agents import function_tool

@function_tool
async def create_call_task(to_number: str, goal: str, instructions: str | None = None) -> dict:
    """Have OneLi place a phone call. to_number in E.164."""
    body = {"idempotency_key": str(uuid.uuid4()), "to_number": to_number, "goal": goal}
    if instructions: body["instructions"] = instructions
    async with httpx.AsyncClient(timeout=30) as c:
        r = await c.post("https://api.oneli.io/v1/call-tasks", json=body,
                         headers={"Authorization": f"Bearer {os.environ['ONELI_API_KEY']}"})
        r.raise_for_status(); return r.json()

JavaScript: שרת MCP וכלי REST

TypeScript
import { Agent, run, MCPServerStreamableHttp, tool } from '@openai/agents';
import { z } from 'zod';

const oneli = new MCPServerStreamableHttp({
  name: 'OneLi', url: 'https://mcp.oneli.io/mcp',
  requestInit: { headers: { Authorization: `Bearer ${process.env.ONELI_API_KEY}` } },
  cacheToolsList: true,
});
await oneli.connect();
try {
  const agent = new Agent({ name: 'Assistant', instructions: 'Use OneLi to place calls.', mcpServers: [oneli] });
  console.log((await run(agent, 'Call +972… and book a table')).finalOutput);
} finally { await oneli.close(); }

// Hosted: hostedMcpTool({ serverLabel:'oneli', serverUrl:'https://mcp.oneli.io/mcp', headers:{Authorization:`Bearer ${key}`}, requireApproval:'never' })

export const createCallTask = tool({
  name: 'create_call_task', description: 'Have OneLi place a phone call. to_number in E.164.',
  parameters: z.object({ to_number: z.string(), goal: z.string(), instructions: z.string().nullable() }), // strict mode: nullable, not optional
  async execute({ to_number, goal, instructions }) {
    const r = await fetch('https://api.oneli.io/v1/call-tasks', { method: 'POST',
      headers: { Authorization: `Bearer ${process.env.ONELI_API_KEY}`, 'Content-Type': 'application/json' },
      body: JSON.stringify({ idempotency_key: crypto.randomUUID(), to_number, goal, ...(instructions ? { instructions } : {}) }) });
    if (!r.ok) throw new Error(`OneLi ${r.status}: ${await r.text()}`);
    return r.json();
  },
});

שימו לב

  • למפתח קבוע משתמשים ב־headers ולא ב־authorization, שמיועד לטוקן OAuth.
  • ב־Python ברירת המחדל של client_session_timeout_seconds היא 5 שניות, קצרה מדי. הגדילו אותה.
  • ב־JS אין אפשרות headers ישירה; מעבירים אותן דרך requestInit.
  • הכלי המתארח עובד רק עם מודלים של Responses API, ו־guardrails מקומיים לא חלים עליו.
  • httpx אינו תלות מוצהרת של החבילה, לכן מתקינים אותו בנפרד.

מספרי טלפון: OneLi מקבלת מספר ישראלי בכל פורמט נפוץ (050-1234567,‏ +972501234567). כשהשיחה מתחילה, הסוכן ממשיך עם get_call_events או עם GET /v1/call-tasks/:id/events כדי לעקוב, לענות להתייעצויות ולקבל את הסיכום.

מה הלאה

מקורות: openai.github.io/openai-agents-python/mcp/ · openai.github.io/openai-agents-js/guides/mcp/