new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

AI SDK · Cookbook · all subjects

patterns/rag

18 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Basic GPT-5 text generation with AI SDK

To generate text with GPT-5 using the AI SDK, import generateText from 'ai' and the openai provider from '@ai-sdk/openai', then call generateText with model: openai('gpt-5') and a prompt.

Structured data generation with GPT-5

Use generateText with Output.object() and a Zod schema to generate type-safe structured JSON data that conforms to a specified schema.

Generating structured JSON with Llama 3.1

To generate structured data with Llama 3.1, use generateText with the Output.object parameter and a Zod schema. This constrains the model output to a specific structure. Example uses z.object to define a recipe schema with name, ingredients array, and steps array fields. The function returns type-safe structured output conforming to the defined schema.

Basic o1 text generation with AI SDK

This example shows how to call OpenAI o1 with the AI SDK using generateText: ```ts import { generateText } from 'ai'; import { openai } from '@ai-sdk/openai'; const { text } = await generateText({ model: openai('o1'), prompt: 'Explain the concept of quantum entanglement.', }); ``` To use the o1 model, you must either be using @ai-sdk/openai version 0.0.59 or greater, or set temperature: 1. System messages are automatically converted to OpenAI developer messages.

RAG Agent guide

The AI SDK provides a guide on how to build a RAG Agent with the AI SDK and Next.js.

Call DeepSeek R1 with AI SDK Core

This example shows how to call DeepSeek R1 directly and extract reasoning tokens: ```ts import { deepSeek } from '@ai-sdk/deepseek'; import { generateText } from 'ai'; const { reasoningText, text } = await generateText({ model: deepSeek('deepseek-reasoner'), prompt: 'Explain quantum entanglement.', }); ``` The returned object includes both `reasoningText` and `text` properties.

Generate image tool definition with AI SDK

The generateImageTool is created using the tool() function from the AI SDK. It accepts an input schema with a required 'prompt' string field. The execute function calls generateImage() with a model (e.g., openai.imageModel('dall-e-3')) and the prompt, then returns the base64-encoded image and the prompt. In production, save the image to blob storage and return a URL instead of base64 to avoid sending large data to the model.

Generate structured output from PDF analysis with generateText

Use generateText with output: Output.object({ schema: zod schema }) to generate structured JSON output from PDF analysis. Define the schema using Zod with descriptions for each field. The result.output will contain the parsed object matching the schema.

RAG implementation code example

```ts import fs from 'fs'; import path from 'path'; import dotenv from 'dotenv'; import { cosineSimilarity, embed, embedMany, generateText } from 'ai'; dotenv.config(); async function main() { const db: { embedding: number[]; value: string }[] = []; const essay = fs.readFileSync(path.join(__dirname, 'essay.txt'), 'utf8'); const chunks = essay .split('.') .map(chunk => chunk.trim()) .filter(chunk => chunk.length > 0 && chunk !== '\n'); const { embeddings } = await embedMany({ model: 'openai/text-embedding-3-small', values: chunks, }); embeddings.forEach((e, i) => { db.push({ embedding: e, value: chunks[i], }); }); const input = 'What were the two main things the author worked on before college?'; const { embedding } = await embed({ model: 'openai/text-embedding-3-small', value: input, }); const context = db .map(item => ({ document: item, similarity: cosineSimilarity(embedding, item.embedding), })) .sort((a, b) => b.similarity - a.similarity) .slice(0, 3) .map(r => r.document.value) .join('\n'); const { text } = await generateText({ model: 'openai/gpt-4o', prompt: `Answer the following question based only on the provided context: ${context} Question: ${input}`, }); console.log(text); } main().catch(console.error); ```

Complete RAG example with Node.js AI SDK

This example demonstrates a full RAG pipeline: read essay text, split into sentence chunks, embed all chunks with OpenAI's text-embedding-3-small model, store in in-memory database, embed user query, retrieve top-3 most similar chunks using cosine similarity, pass chunks as context to GPT-4o generation with a system prompt constraining answer to provided context.

RSC structured data generation pattern

The pattern for generating structured objects with React Server Components involves: a client component that calls a server action, and a server action using generateText with Output.object to generate and validate the structured output against a zod schema.

generateText with Output.object for structured JSON

Use generateText with Output.object to generate structured data like JSON. Provide a zod schema that describes the structure of the desired object. The SDK will validate the generated output and ensure conformance to the specified structure.

Output.object requires zod schema

The Output.object function requires a schema parameter defined using zod, a library for defining schemas for JavaScript objects. Pass the schema as z.object() with nested field definitions.

generateText with Output.object example

Example showing how to generate structured notifications: ```typescript const { output: notifications } = await generateText({ model: 'openai/gpt-5.4', system: 'You generate three notifications for a messages app.', prompt: input, output: Output.object({ schema: z.object({ notifications: z.array( z.object({ name: z.string().describe('Name of a fictional person.'), message: z.string().describe('Do not use emojis or links.'), minutesAgo: z.number(), }), ), }), }), }); ``` This generates an array of notification objects with name, message, and minutesAgo fields.

React Server Component client-side call to server action

In a client component marked with 'use client', call a server action (defined with 'use server') to trigger text generation. Use useState to store the generated output and display it. Set maxDuration export to 30 seconds to allow streaming responses.

ServerMessage interface definition

ServerMessage is an interface with three properties: role (type 'user' | 'assistant' | 'function', required), and content (type string, required). This interface represents server-side message storage format in conversation restoration.

Natural Language Postgres guide overview

This guide teaches how to build a Next.js app that uses AI to interact with a PostgreSQL database using natural language. The application generates SQL queries from natural language input, explains query components in plain English, and creates charts to visualize query results. The tech stack includes Next.js (App Router), AI SDK, OpenAI, Zod, Postgres with Neon, shadcn-ui, TailwindCSS, and Recharts for visualization.

Source structure for RAG models

Source has sourceType 'url' (returned by web search RAG models), id (string), url (string), optional title (string), and optional providerMetadata (SharedV2ProviderMetadata).

Give your agent this brain