Skip to content

Chat and streaming

Send messages, get the answer as it is written, and say which use case and which person the call is for.

Applies to EngineCloud
View as Markdown
On this page
  1. A call
  2. Streaming
  3. The Sypnia headers
  4. With the OpenAI client

A call

ask-about-a-product.ts
import { createAI } from '@sypnia/ai/server';
const ai = createAI({ apiKey: process.env.SYPNIA_SECRET_KEY! });

const answer = await ai.chat({
  task: 'allergen-answer',
  case: 'ask-about-a-product',
  endUser: customer.id,
  messages: [{ role: 'user', content: '¿El pan de centeno tiene nueces?' }],
});

answer.text;          // «No. El pan de centeno lleva harina de centeno, agua, sal y masa madre.»
answer.usage;         // { input_tokens: 412, output_tokens: 38, credits: … }
answer.callId;        // give it to support when something looks wrong

Streaming

With stream: true the answer arrives as it is written, so a person sees the first words in well under a second.

TypeScript
const stream = await ai.chat({ task: 'chat', case: 'ask-about-a-product', endUser: customer.id, messages, stream: true });
for await (const part of stream) process.stdout.write(part.text);
const done = await stream.final();   // usage, credits, the model that answered

Over HTTP it is Server-Sent Events: chunks in the OpenAI shape, then a last chunk with usage and the sypnia object, then data: [DONE].

The Sypnia headers

HeaderWhat it saysExample
Sypnia-Casethe use case the call belongs toask-about-a-product
Sypnia-End-Userthe person of your app behind the call: a stable id, never an e-mailcus_8f3a6c
Sypnia-Budgetthe most this call may cost, in credits5
Sypnia-Storekeep what was asked and answered, when the route allows itfalse
traceparentthe trace this call is part of (the SDK sends it for you)00-…-01

Every response carries a sypnia object: the route, the model that answered, each attempt, the credits charged and the call_id.

With the OpenAI client

TypeScript
import OpenAI from 'openai';
const client = new OpenAI({
  baseURL: 'https://ai.api.sypnia.com/v1',
  apiKey: process.env.SYPNIA_SECRET_KEY,
  defaultHeaders: { 'Sypnia-Case': 'publish-bread-of-the-day' },
});
await client.chat.completions.create({ model: 'task:write', messages });
  1. A call
  2. Streaming
  3. The Sypnia headers
  4. With the OpenAI client

    Search pages, sections and terms