Chat and streaming
Send messages, get the answer as it is written, and say which use case and which person the call is for.
A call
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 wrongStreaming
With stream: true the answer arrives as it is written, so a person sees the first words in well under a second.
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 answeredOver 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
| Header | What it says | Example |
|---|---|---|
Sypnia-Case | the use case the call belongs to | ask-about-a-product |
Sypnia-End-User | the person of your app behind the call: a stable id, never an e-mail | cus_8f3a6c |
Sypnia-Budget | the most this call may cost, in credits | 5 |
Sypnia-Store | keep what was asked and answered, when the route allows it | false |
traceparent | the 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
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 });