Enable Streaming

Enable Streaming

Streaming gives your users a better experience by showing AI responses as they're generated, token by token.

Why Streaming?

  • Users see output immediately instead of waiting
  • Feels more interactive and responsive
  • Works with all providers (OpenAI, Anthropic, Gemini)

Streaming with the SDK

streaming.ts
import { Cencori } from 'cencori';

const cencori = new Cencori();

const stream = cencori.ai.chatStream({
  model: 'llama-3.1-8b-instant',
  messages: [
    { role: 'user', content: 'Write a short poem about coding' }
  ],
});

// Iterate over the stream
for await (const chunk of stream) {
  // Print each token as it arrives
  process.stdout.write(chunk.delta);
  
  // Check if generation is complete
  if (chunk.finish_reason) {
    console.log('\nDone!', chunk.finish_reason);
  }
}

Streaming in Next.js API Routes

app/api/chat/route.ts
import { Cencori } from 'cencori';
import { NextRequest } from 'next/server';

const cencori = new Cencori();

export async function POST(req: NextRequest) {
  const { messages } = await req.json();

  const stream = cencori.ai.chatStream({
    model: 'llama-3.1-8b-instant',
    messages,
  });

  // Create a readable stream
  const encoder = new TextEncoder();
  const readable = new ReadableStream({
    async start(controller) {
      for await (const chunk of stream) {
        controller.enqueue(
          encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`)
        );
      }
      controller.close();
    },
  });

  return new Response(readable, {
    headers: {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
    },
  });
}

With Vercel AI SDK

Even simpler with our Vercel AI SDK provider:

app/api/chat/route.ts
import { cencori } from 'cencori/vercel';
import { streamText, convertToModelMessages, type UIMessage } from 'ai';

export async function POST(req: Request) {
  const { messages }: { messages: UIMessage[] } = await req.json();

  const result = await streamText({
    model: cencori('llama-3.1-8b-instant'),
    messages: convertToModelMessages(messages),
  });

  return result.toUIMessageStreamResponse();
}

💡 Tip: The Vercel AI SDK integration handles all the complexity — works with useChat() hook out of the box!