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

# Migration von der Assistants API zur Agents API

> Anleitung zur Migration deiner Integration von der alten Assistants API zur neuen Agents API

<Info>
  Die Agents API ist die nächste Generation unserer API, entwickelt für bessere Kompatibilität mit modernen AI SDKs wie dem Vercel AI SDK.
</Info>

## Überblick

Die Agents API stellt eine deutliche Verbesserung gegenüber der Assistants API dar. Das Hauptziel ist native Kompatibilität mit branchenüblichen AI SDKs. Der wesentliche Unterschied liegt in der Abschaffung benutzerdefinierter Input/Output-Transformationen zugunsten von Standardformaten.

### Warum migrieren?

* **Vercel AI SDK Kompatibilität**: Funktioniert nativ mit der `useChat`-Funktion von AI SDK 5
* **Standardformate**: Verwendet branchenübliche Nachrichtenformate statt benutzerdefinierter Transformationen
* **Besseres Streaming**: Native Unterstützung für AI SDK Streaming-Patterns
* **Zukunftssicher**: Die Assistants API wird am 16. August eingestellt

## Wesentliche Unterschiede

### Endpoint-Änderungen

| Assistants API                   | Agents API                   | Breaking?                 |
| -------------------------------- | ---------------------------- | ------------------------- |
| `/assistant/v1/chat/completions` | `/agent/v1/chat/completions` | Ja - Formatänderungen     |
| `/assistant/v1/create`           | `/agent/v1/create`           | Nein - Nur Parameternamen |
| `/assistant/v1/get`              | `/agent/v1/get`              | Nein - Nur Parameternamen |
| `/assistant/v1/update`           | `/agent/v1/update`           | Nein - Nur Parameternamen |
| `/assistant/v1/models`           | `/agent/v1/models`           | Nein - Identisch          |

### Parameter-Änderungen (nicht-breaking)

Bei den Endpoints für Create, Get und Update ändert sich nur die Parameterbenennung:

* `assistantId` → `agentId`
* Request/Response-Struktur bleibt identisch
* Alle anderen Parameter unverändert

## Breaking Changes in `/chat/completions`

Der Chat-Completions-Endpoint hat signifikante Formatänderungen, um Vercel AI SDK Kompatibilität zu unterstützen.

### Änderungen am Request-Format

#### Altes Format (Assistants API)

```javascript theme={null}
{
  assistantId: "asst_123",
  messages: [
    {
      role: "user",
      content: "Hello, how are you?",  // Simple string content
      attachmentIds: ["uuid-1234"]
    }
  ],
  stream: true
}
```

#### Neues Format (Agents API)

```javascript theme={null}
{
  agentId: "agent_123",  // Parameter name changed
  messages: [
    {
      id: "msg_1",  // New: Message ID required
      role: "user",
      parts: [  // New: Parts array instead of content string
        {
          type: "text",
          text: "Hello, how are you?"
        }
      ],
      metadata: {
        attachments: ["uuid-1234"]  // New: Attachment format
      }
    }
  ],
  stream: true
}
```

### Wichtige Request-Unterschiede

1. **Nachrichtenstruktur**:
   * Alt: `content` als String
   * Neu: `parts` als Array mit typisierten Objekten

2. **Nachrichten-ID**:
   * Alt: Optional oder automatisch generiert
   * Neu: Pflichtfeld `id` für jede Nachricht

3. **Anhänge**:
   * Alt: `attachmentIds` Array auf Nachrichtenebene
   * Neu: `metadata.attachments` Array am Nachrichtenobjekt

4. **Parametername**:
   * Alt: `assistantId`
   * Neu: `agentId`

### Änderungen am Response-Format

#### Altes Format (Assistants API)

```javascript theme={null}
{
  result: [
    {
      id: "msg_456",
      role: "assistant",
      content: [
        {
          type: "text",
          text: "I'm doing well, thank you!"
        }
      ]
    }
  ]
}
```

#### Neues Format (Agents API)

```javascript theme={null}
{
  messages: [
    {
      id: "msg_456",
      role: "assistant",
      content: "I'm doing well, thank you!"
    }
  ]
}
```

### Wichtige Response-Unterschiede

1. **Top-Level-Struktur**:
   * Alt: Verpackt in `result` Array
   * Neu: Verpackt in `messages` Array

2. **Content-Feld**:
   * Alt: `content` Array
   * Neu: `content` String

### Streaming-Änderungen

#### Altes Format (Assistants API)

```
data: {"type":"message","content":"Hello"}
data: {"type":"message","content":" world"}
data: {"type":"done"}
```

#### Neues Format (Agents API)

Verwendet das Vercel AI SDK Streaming-Format:

```
0:"text chunk 1"
1:"text chunk 2"
...
```

Die Agents API streamt im nativen Format des Vercel AI SDK, kompatibel mit dem `useChat` Hook.

## Migrationsschritte

### Schritt 1: Endpoint-URLs aktualisieren

```javascript theme={null}
// Before
const url = 'https://api.langdock.com/assistant/v1/chat/completions';

// After
const url = 'https://api.langdock.com/agent/v1/chat/completions';
```

### Schritt 2: Parameternamen aktualisieren (nicht-breaking Endpoints)

Für Create-, Get- und Update-Endpoints:

```javascript theme={null}
// Before
{ assistantId: "asst_123" }

// After
{ agentId: "agent_123" }
```

### Schritt 3: Nachrichtenformat aktualisieren (Breaking - Chat Completions)

#### Nachrichten konvertieren

```javascript theme={null}
// Before (Assistants API)
const oldMessage = {
  role: "user",
  content: "Analyze this document",
  attachmentIds: ["uuid-1234"]
};

// After (Agents API)
const newMessage = {
  id: generateId(), // You need to generate message IDs
  role: "user",
  parts: [
    {
      type: "text",
      text: "Analyze this document"
    }
  ],
  metadata: {
    attachments: ["uuid-1234"]
  }
};
```

#### Verwendung mit Vercel AI SDK

Die Agents API funktioniert nativ mit dem `useChat` Hook des Vercel AI SDK:

```typescript theme={null}
import { useChat } from '@ai-sdk/react';

function ChatComponent() {
  const { messages, input, handleSubmit, handleInputChange } = useChat({
    api: 'https://api.langdock.com/agent/v1/chat/completions',
    headers: {
      'Authorization': `Bearer ${API_KEY}`
    },
    body: {
      agentId: 'agent_123'
    }
  });

  // The hook handles all message formatting automatically!
  return (
    <div>
      {messages.map(m => (
        <div key={m.id}>
          {m.role}: {m.content}
        </div>
      ))}
      <form onSubmit={handleSubmit}>
        <input value={input} onChange={handleInputChange} />
        <button type="submit">Send</button>
      </form>
    </div>
  );
}
```

### Schritt 4: Response-Verarbeitung aktualisieren

```javascript theme={null}
// Before (Assistants API)
const response = await fetch(assistantUrl, options);
const data = await response.json();
const messages = data.result; // Array of messages

// After (Agents API)
const response = await fetch(agentUrl, options);
const data = await response.json();
const messages = data.messages; // Array of messages
const text = messages[0].content; // Plain string content
```

### Schritt 5: Streaming-Code aktualisieren

#### Vorher (Custom SSE Parsing)

```javascript theme={null}
const response = await fetch(url, options);
const reader = response.body.getReader();
const decoder = new TextDecoder();

while (true) {
  const { done, value } = await reader.read();
  if (done) break;

  const chunk = decoder.decode(value);
  const lines = chunk.split('\n');

  for (const line of lines) {
    if (line.startsWith('data: ')) {
      const data = JSON.parse(line.slice(6));
      if (data.type === 'message') {
        console.log(data.content);
      }
    }
  }
}
```

#### Nachher (Vercel AI SDK)

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

const result = await streamText({
  model: langdock({
    apiKey: process.env.LANGDOCK_API_KEY,
    agentId: 'agent_123'
  }),
  messages: conversationHistory
});

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

## Code-Beispiele

### Vollständiges Migrations-Beispiel

#### Vorher (Assistants API)

```javascript theme={null}
const axios = require("axios");

async function chatWithAssistant() {
  const response = await axios.post(
    "https://api.langdock.com/assistant/v1/chat/completions",
    {
      assistantId: "asst_123",
      messages: [
        {
          role: "user",
          content: "What's the weather today?",
          attachmentIds: []
        }
      ],
      stream: false
    },
    {
      headers: {
        Authorization: "Bearer YOUR_API_KEY"
      }
    }
  );

  // Response wrapped in result array
  const assistantMessage = response.data.result[0];
  console.log(assistantMessage.content[0].text);
}
```

#### Nachher (Agents API)

```javascript theme={null}
const axios = require("axios");

async function chatWithAgent() {
  const response = await axios.post(
    "https://api.langdock.com/agent/v1/chat/completions",
    {
      agentId: "agent_123",  // Changed parameter name
      messages: [
        {
          id: "msg_1",  // Added message ID
          role: "user",
          parts: [  // Changed to parts array
            {
              type: "text",
              text: "What's the weather today?"
            }
          ]
        }
      ],
      stream: false
    },
    {
      headers: {
        Authorization: "Bearer YOUR_API_KEY"
      }
    }
  );

  // Response is messages array with content string
  const agentMessage = response.data.messages[0];
  console.log(agentMessage.content);
}
```

### Verwendung mit Next.js und Vercel AI SDK

```typescript theme={null}
// app/api/chat/route.ts
export async function POST(req: Request) {
  const { messages, agentId } = await req.json();

  const response = await fetch(
    'https://api.langdock.com/agent/v1/chat/completions',
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.LANGDOCK_API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        agentId,
        messages,
        stream: true
      })
    }
  );

  // Forward the streaming response
  return new Response(response.body, {
    headers: { 'Content-Type': 'text/event-stream' }
  });
}
```

## Migration testen

### Checkliste

* [ ] Alle Endpoint-URLs von `/assistant/v1/*` zu `/agent/v1/*` aktualisieren
* [ ] `assistantId` durch `agentId` in allen Requests ersetzen
* [ ] Nachrichten-`content`-Strings zu `parts`-Arrays konvertieren (für Chat Completions)
* [ ] `id`-Feld zu allen Nachrichten hinzufügen (für Chat Completions)
* [ ] Anhang-Referenzen auf `metadata.attachments`-Format aktualisieren
* [ ] Response-Verarbeitung für das neue Format anpassen
* [ ] Streaming mit neuem Format testen (oder Vercel AI SDK verwenden)
* [ ] Fehlerbehandlung für neue Response-Struktur aktualisieren
* [ ] Besitzer informieren oder Systeme migrieren, die API-Keys mit der Markierung `Nutzt veraltete Endpoints` in den Workspace-API-Einstellungen verwenden

### Schrittweise Migrationsstrategie

Du kannst Endpoints schrittweise migrieren:

1. **Mit nicht-breaking Endpoints starten**: Zuerst Create, Get, Update und Models migrieren (nur Parameternamen ändern sich)
2. **Gründlich testen**: Sicherstellen, dass diese korrekt funktionieren
3. **Chat Completions zuletzt migrieren**: Dieser Endpoint erfordert die meisten Code-Änderungen
4. **Feature Flags verwenden**: Während der Übergangszeit zwischen alter und neuer API umschalten

## Häufige Migrationsprobleme

### Problem 1: Fehlende Nachrichten-IDs

**Problem**: Die Agents API erfordert Nachrichten-IDs

```javascript theme={null}
// Error: Missing id field
{
  role: "user",
  parts: [...]
}
```

**Lösung**: Generiere eindeutige IDs für jede Nachricht

```javascript theme={null}
import { nanoid } from 'nanoid';

{
  id: nanoid(),
  role: "user",
  parts: [...]
}
```

### Problem 2: Anhangsformat

**Problem**: Altes Anhangsformat wird nicht erkannt

```javascript theme={null}
// Wrong
{
  role: "user",
  attachmentIds: ["uuid-1234"],
  parts: [...]
}
```

**Lösung**: Verwende `metadata.attachments`

```javascript theme={null}
// Correct
{
  id: "msg_1",
  role: "user",
  parts: [
    { type: "text", text: "..." }
  ],
  metadata: {
    attachments: ["uuid-1234"]
  }
}
```

### Problem 3: Response-Parsing

**Problem**: Suche nach `result` Array

```javascript theme={null}
// Wrong - result doesn't exist in Agents API
const messages = response.data.result;
```

**Lösung**: Verwende `messages` Array mit `content` String

```javascript theme={null}
// Correct
const messages = response.data.messages;
const text = messages[0].content;
```

## Support

Falls du während der Migration auf Probleme stößt:

1. Schau dir die [Agents API Dokumentation](/de/developer/agents-api/agent) für detaillierte Beispiele an
2. Lies die [Vercel AI SDK Dokumentation](https://sdk.vercel.ai/docs) für SDK-spezifische Hilfe
3. Kontaktiere den Support unter [support@langdock.com](mailto:support@langdock.com)

## Zeitplan

* **Aktuell**: Beide APIs sind verfügbar
* **Zukünftig**: Die Assistants API wird am 16. August eingestellt
* **Empfehlung**: Migriere neue Systeme jetzt zur Agents API

<Info>
  Bei Fragen oder für Unterstützung bei der Migration kontaktiere unser Support-Team unter [support@langdock.com](mailto:support@langdock.com).
</Info>
