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

# Mastra-Integration

> Baue TypeScript-Agenten, Tools und Workflows mit Mastra unter Verwendung der privaten, OpenAI-kompatiblen Modelle von Venice.

[Mastra](https://mastra.ai/) ist ein TypeScript-Framework zum Bauen von KI-Agenten, Tools und Workflows. Verbinde es mit Venice, indem du einen benutzerdefinierten, OpenAI-kompatiblen Modell-Endpoint konfigurierst.

## Voraussetzungen

* Node.js 22.18 oder neuer
* Ein [Venice-API-Schlüssel](/guides/getting-started/generating-api-key)

## Mastra-Projekt erstellen

<CodeGroup>
  ```bash npm theme={"system"}
  npm create mastra@latest
  ```

  ```bash pnpm theme={"system"}
  pnpm create mastra
  ```

  ```bash yarn theme={"system"}
  yarn create mastra
  ```

  ```bash bun theme={"system"}
  bunx create-mastra
  ```
</CodeGroup>

Füge deinen Venice-API-Schlüssel in die `.env`-Datei des generierten Projekts ein:

```bash theme={"system"}
VENICE_API_KEY=your-venice-api-key
```

<Warning>
  Halte `.env` aus der Versionsverwaltung heraus. Gib deinen Venice-API-Schlüssel nicht in browserseitigem Code preis.
</Warning>

## Einen von Venice angetriebenen Agenten erstellen

Erstelle einen Agenten und richte seine Modellkonfiguration auf die Venice-API aus:

```typescript theme={"system"}
// src/mastra/agents/venice-agent.ts
import { Agent } from '@mastra/core/agent'

export const veniceAgent = new Agent({
  id: 'venice-agent',
  name: 'Venice Agent',
  instructions: `
    You are a concise, privacy-respecting assistant.
    Give accurate answers and say when you are uncertain.
  `,
  model: {
    id: 'venice/venice-uncensored',
    url: 'https://api.venice.ai/api/v1',
    apiKey: process.env.VENICE_API_KEY,
  },
})
```

Das erste Segment von `id` ist das Routing-Label von Mastra. Mastra sendet die verbleibende Modell-ID, `venice-uncensored`, an Venice.

<Note>
  Setze `url` auf die oben gezeigte Basis-API-URL. Hänge nicht `/chat/completions` an; Mastra fügt diesen Pfad automatisch hinzu.
</Note>

Registriere den Agenten in deiner Mastra-Instanz:

```typescript theme={"system"}
// src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { veniceAgent } from './agents/venice-agent'

export const mastra = new Mastra({
  agents: { veniceAgent },
})
```

Starte den Entwicklungsserver und öffne die im Terminal angezeigte URL, um den Agenten in Mastra Studio zu testen:

```bash theme={"system"}
npm run dev
```

## Eine Antwort generieren

Rufe den registrierten Agenten ab und rufe `generate()` auf:

```typescript theme={"system"}
import { mastra } from './src/mastra/index'

const agent = mastra.getAgentById('venice-agent')
const result = await agent.generate(
  'Explain why zero data retention matters in two sentences.',
)

console.log(result.text)
console.log(result.usage)
```

## Eine Antwort streamen

Verwende `stream()`, wenn du die Ausgabe anzeigen möchtest, sobald sie eintrifft:

```typescript theme={"system"}
const agent = mastra.getAgentById('venice-agent')
const result = await agent.stream(
  'Write a short poem about private AI inference.',
)

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

## Tools hinzufügen

Mastra-Tools verwenden Zod-Schemas, um ihre Ein- und Ausgaben zu validieren. Verwende ein Venice-Modell, das Function Calling unterstützt, wenn du einem Agenten Tools zuweist.

```typescript theme={"system"}
// src/mastra/tools/model-info.ts
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'

export const modelInfoTool = createTool({
  id: 'model-info',
  description: 'Returns a short description of a Venice model',
  inputSchema: z.object({
    model: z.string().describe('A Venice model ID'),
  }),
  outputSchema: z.object({
    description: z.string(),
  }),
  execute: async ({ model }) => {
    const descriptions: Record<string, string> = {
      'venice-uncensored': 'A fast, uncensored general-purpose model.',
      'zai-org-glm-5-1': 'A private model for reasoning and tool use.',
    }

    return {
      description: descriptions[model] ?? `No description found for ${model}.`,
    }
  },
})
```

Weise das Tool einem Agenten zu:

```typescript theme={"system"}
// src/mastra/agents/model-guide-agent.ts
import { Agent } from '@mastra/core/agent'
import { modelInfoTool } from '../tools/model-info'

export const modelGuideAgent = new Agent({
  id: 'model-guide-agent',
  name: 'Venice Model Guide',
  instructions: 'Help users choose a Venice model. Use modelInfoTool when needed.',
  model: {
    id: 'venice/zai-org-glm-5-1',
    url: 'https://api.venice.ai/api/v1',
    apiKey: process.env.VENICE_API_KEY,
  },
  tools: { modelInfoTool },
})
```

## Strukturierte Ausgabe generieren

Übergib ein Zod-Schema über `structuredOutput`, um validierte Daten zu erhalten:

```typescript theme={"system"}
import { z } from 'zod'

const result = await veniceAgent.generate(
  'Compare private and data-retaining AI inference.',
  {
    structuredOutput: {
      schema: z.object({
        summary: z.string(),
        privacyBenefits: z.array(z.string()),
        recommendation: z.string(),
      }),
    },
  },
)

console.log(result.object)
```

Wenn das ausgewählte Modell den Structured-Output-Modus der API nicht unterstützt, setze `jsonPromptInjection: true` innerhalb von `structuredOutput`, damit Mastra das Schema stattdessen dem Prompt hinzufügt.

## Modelle wechseln

Um ein anderes Venice-Textmodell zu verwenden, behalte das `venice/`-Routing-Präfix bei und ersetze die verbleibende Modell-ID:

```typescript theme={"system"}
model: {
  id: 'venice/qwen3-5-9b',
  url: 'https://api.venice.ai/api/v1',
  apiKey: process.env.VENICE_API_KEY,
}
```

Durchsuche die [verfügbaren Venice-Modelle](/models/overview) und prüfe deren Fähigkeiten, bevor du eines für Tool Calling, Vision oder strukturierte Ausgaben auswählst.

## Fehlerbehebung

<AccordionGroup>
  <Accordion title="Die API gibt 401 Unauthorized zurück">
    Stelle sicher, dass `VENICE_API_KEY` in der Umgebung vorhanden ist, in der Mastra läuft, und starte den Entwicklungsserver nach Änderungen an `.env` neu.
  </Accordion>

  <Accordion title="Die API meldet, dass das Modell nicht existiert">
    Verwende die exakte Modell-ID, die auf der [Modelle-Seite](/models/overview) angezeigt wird. Stelle ihr in Mastra `venice/` voran, zum Beispiel `venice/venice-uncensored`.
  </Accordion>

  <Accordion title="Anfragen liefern 404 Not Found">
    Setze die Modell-URL auf `https://api.venice.ai/api/v1`. Verwende nicht den vollständigen `/chat/completions`-Endpoint.
  </Accordion>

  <Accordion title="Der Agent ruft sein Tool nicht auf">
    Wähle ein Modell, das Function Calling unterstützt, beschreibe in den Instruktionen, wann der Agent das Tool verwenden soll, und definiere das Tool mit `createTool()`.
  </Accordion>
</AccordionGroup>

<CardGroup cols={2}>
  <Card title="Mastra-Dokumentation" icon="book" href="https://mastra.ai/docs">
    Erfahre mehr über Mastra-Agenten, Tools und Workflows
  </Card>

  <Card title="Venice-Modelle" icon="database" href="/models/overview">
    Modelle und unterstützte Fähigkeiten durchsuchen
  </Card>
</CardGroup>
