> ## Documentation Index
> Fetch the complete documentation index at: https://orchata.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# AI SDK Integration

> Integrate Orchata with Vercel AI SDK v5+ for AI-powered applications

The Orchata SDK includes tools for the Vercel AI SDK v5+, allowing AI models to query your knowledge base directly.

## Installation

Install the SDK along with the required peer dependencies:

<Tabs>
  <Tab title="npm">
    ```bash theme={null}
    npm install @orchata-ai/sdk ai zod
    ```
  </Tab>

  <Tab title="pnpm">
    ```bash theme={null}
    pnpm add @orchata-ai/sdk ai zod
    ```
  </Tab>

  <Tab title="yarn">
    ```bash theme={null}
    yarn add @orchata-ai/sdk ai zod
    ```
  </Tab>

  <Tab title="bun">
    ```bash theme={null}
    bun add @orchata-ai/sdk ai zod
    ```
  </Tab>
</Tabs>

<Note>
  The AI tools require `ai` v5.0.0+ and `zod` v3.22.0+ as peer dependencies. If you don't need AI SDK integration, you can use the core SDK without them.
</Note>

## Basic Usage

Create Orchata tools and use them with the AI SDK:

```typescript theme={null}
import { Orchata } from '@orchata-ai/sdk';
import { createOrchataTools } from '@orchata-ai/sdk/ai';
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';

const client = new Orchata({ apiKey: 'oai_xxx' });
const tools = createOrchataTools(client);

const { text } = await generateText({
  model: openai('gpt-4-turbo'),
  tools,
  prompt: 'What does our documentation say about authentication?'
});

console.log(text);
```

## Available Tools

The `createOrchataTools` function creates these tools for your AI model:

| Tool                 | Description                                         |
| -------------------- | --------------------------------------------------- |
| `queryKnowledge`     | Search the knowledge base for relevant information  |
| `findRelevantSpaces` | Discover which spaces are most relevant for a query |
| `listSpaces`         | List all available knowledge spaces                 |
| `getDocumentContent` | Get the full content of a specific document         |
| `uploadDocument`     | Upload new content (disabled by default)            |
| `createSpace`        | Create a new space (disabled by default)            |

## Simple Query Tool

For simple use cases where you want to query a specific space, use the `createQueryTool` helper:

```typescript theme={null}
import { Orchata } from '@orchata-ai/sdk';
import { createQueryTool } from '@orchata-ai/sdk/ai';
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';

const client = new Orchata({ apiKey: 'oai_xxx' });

// Create a tool that queries a specific space
const queryTool = createQueryTool(client, 'space_123');

const { text } = await generateText({
  model: openai('gpt-4-turbo'),
  tools: { query: queryTool },
  prompt: 'What is our refund policy?'
});
```

## Configuration Options

Customize the tools with configuration options:

```typescript theme={null}
const tools = createOrchataTools(client, {
  // Restrict which spaces the AI can access
  allowedSpaceIds: ['space_123', 'space_456'],

  // Default number of results (default: 5)
  defaultTopK: 10,

  // Enable document upload (default: false)
  enableUpload: true,

  // Enable space creation (default: false)
  enableSpaceCreation: true,
});
```

### Configuration Options

<ParamField body="allowedSpaceIds" type="string[]">
  Restrict which spaces the AI can access. If not provided, all spaces are accessible.
</ParamField>

<ParamField body="defaultTopK" type="integer" default="5">
  Default number of results to return from queries.
</ParamField>

<ParamField body="enableUpload" type="boolean" default="false">
  Enable the `uploadDocument` tool. Keep disabled unless you want AI to modify your knowledge base.
</ParamField>

<ParamField body="enableSpaceCreation" type="boolean" default="false">
  Enable the `createSpace` tool. Keep disabled unless you want AI to create new spaces.
</ParamField>

## Streaming

Use streaming for real-time responses:

```typescript theme={null}
import { streamText } from 'ai';

const result = streamText({
  model: openai('gpt-4-turbo'),
  tools,
  prompt: 'Summarize our API documentation'
});

for await (const chunk of result.textStream) {
  process.stdout.write(chunk);
}
```

## Complete Example

Here's a complete example of an AI-powered chatbot that queries your knowledge base:

```typescript theme={null}
import { Orchata } from '@orchata-ai/sdk';
import { createOrchataTools } from '@orchata-ai/sdk/ai';
import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';

const client = new Orchata({
  apiKey: process.env.ORCHATA_API_KEY!
});

// Create tools with restricted access
const tools = createOrchataTools(client, {
  allowedSpaceIds: ['space_123'], // Only allow access to specific space
  defaultTopK: 5,
  enableUpload: false, // Don't allow AI to upload documents
  enableSpaceCreation: false // Don't allow AI to create spaces
});

export async function POST(request: Request) {
  const { message } = await request.json();

  const result = streamText({
    model: openai('gpt-4-turbo'),
    tools,
    prompt: message,
    system: 'You are a helpful assistant that answers questions using our knowledge base. Always cite your sources.'
  });

  return new Response(result.textStream, {
    headers: { 'Content-Type': 'text/plain' }
  });
}
```

## Tool Descriptions

Each tool includes a description that helps the AI understand when to use it:

* **queryKnowledge**: "Search the knowledge base for information relevant to a query"
* **findRelevantSpaces**: "Find which knowledge spaces are most relevant for a query"
* **listSpaces**: "List all available knowledge spaces"
* **getDocumentContent**: "Get the full content of a specific document"
* **uploadDocument**: "Upload a new document to a knowledge space"
* **createSpace**: "Create a new knowledge space"

The AI model uses these descriptions to decide which tools to call based on the user's request.

## Best Practices

<CardGroup cols={2}>
  <Card title="Restrict Access" icon="shield">
    Use `allowedSpaceIds` to limit which spaces the AI can access. Don't give AI access to sensitive data.
  </Card>

  <Card title="Disable Writes" icon="lock">
    Keep `enableUpload` and `enableSpaceCreation` disabled unless you specifically need AI to modify your knowledge base.
  </Card>

  <Card title="Set Limits" icon="gauge">
    Use `defaultTopK` to control how many results the AI receives. Too many results can be overwhelming.
  </Card>

  <Card title="Provide Context" icon="message-square">
    Use system prompts to guide the AI on how to use the knowledge base and cite sources.
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Usage Guide" icon="book" href="/sdk/usage">
    Learn about Spaces, Documents, and Queries APIs.
  </Card>

  <Card title="Error Handling" icon="triangle-alert" href="/sdk/errors">
    Handle errors gracefully with typed error classes.
  </Card>

  <Card title="Quickstart" icon="rocket" href="/sdk/quickstart">
    Review the quickstart guide.
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/introduction">
    Explore the REST API documentation.
  </Card>
</CardGroup>
