Die OpenAI API gehört 2026 zur Standardausstattung moderner KI-Anwendungen. Claude Code macht es einfach, GPT-4o, die Assistants API und DALL-E in TypeScript-Projekte zu integrieren — von Chat Completions über Function Calling bis hin zu multimodalen Vision-Anwendungen. Dieser Guide zeigt produktionsreife Patterns für jede Stufe der Integration.
Der Einstieg beginnt mit dem openai npm package — dem offiziellen TypeScript/JavaScript SDK. Claude Code generiert den Setup-Code inklusive Typen, Error Handling und Environment-Variable-Verwaltung.
# Installation
npm install openai
npm install -D @types/node dotenv
.env-Datei (lokal) oder dem Secret-Manager der Deployment-Plattform.// .env
OPENAI_API_KEY=sk-proj-...
// client.ts — zentrale Client-Initialisierung
import OpenAI from 'openai';
import 'dotenv/config';
export const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
// Optional: Custom Base URL für Proxy-Setup
// baseURL: process.env.OPENAI_BASE_URL,
maxRetries: 3,
timeout: 30_000,
});
// Modell-Konstanten für einfaches Wechseln
export const MODELS = {
smart: 'gpt-4o', // Komplex, multimodal
fast: 'gpt-4o-mini', // Schnell, günstig
reason: 'o3-mini', // Reasoning-Tasks
embed: 'text-embedding-3-small',
image: 'dall-e-3',
} as const;
| Modell | Stärke | Context | Preis (Input/1M) |
|---|---|---|---|
| gpt-4o | Multimodal, komplex | 128k | ~$2.50 |
| gpt-4o-mini | Schnell, effizient | 128k | ~$0.15 |
| o3-mini | Reasoning, Mathe | 200k | ~$1.10 |
| text-embedding-3-small | Embeddings | 8k | ~$0.02 |
Chat Completions sind die Kernfunktionalität der OpenAI API. Mit stream: true liefert die API Token für Token — ideal für chatähnliche Interfaces, die sofortiges Feedback geben sollen.
// chat.ts — einfache Completion
import { openai, MODELS } from './client';
async function chat(userMessage: string): Promise<string> {
const response = await openai.chat.completions.create({
model: MODELS.smart,
messages: [
{
role: 'system',
content: 'Du bist ein hilfreicher KI-Assistent für deutsche Nutzer.',
},
{
role: 'user',
content: userMessage,
},
],
temperature: 0.7,
max_tokens: 1024,
});
return response.choices[0].message.content ?? '';
}
// streaming.ts — Token-by-Token Output
async function streamChat(userMessage: string): Promise<void> {
const stream = await openai.chat.completions.create({
model: MODELS.smart,
messages: [{ role: 'user', content: userMessage }],
stream: true,
});
// for-await Loop über den Stream
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta?.content ?? '';
process.stdout.write(delta); // Sofort ausgeben
}
console.log(); // Newline am Ende
}
// Für Web: Streaming via ReadableStream (Edge Runtime)
export async function streamToResponse(
userMessage: string
): Promise<ReadableStream> {
const stream = await openai.chat.completions.create({
model: MODELS.smart,
messages: [{ role: 'user', content: userMessage }],
stream: true,
});
return new ReadableStream({
async start(controller) {
for await (const chunk of stream) {
const text = chunk.choices[0]?.delta?.content ?? '';
if (text) controller.enqueue(new TextEncoder().encode(text));
}
controller.close();
},
});
}
Function Calling — auch Tool Use genannt — erlaubt es GPT-4o, strukturierte Daten zurückzugeben und externe Funktionen aufzurufen. Das Modell entscheidet selbst, wann welches Tool einzusetzen ist.
// tools.ts — Function Calling Pattern
import { openai, MODELS } from './client';
import type { ChatCompletionTool } from 'openai/resources';
// Tool-Definitionen (JSON Schema)
const tools: ChatCompletionTool[] = [
{
type: 'function',
function: {
name: 'get_weather',
description: 'Aktuelles Wetter für eine Stadt abrufen',
parameters: {
type: 'object',
properties: {
city: { type: 'string', description: 'Stadtname' },
units: { type: 'string', enum: ['celsius', 'fahrenheit'] },
},
required: ['city'],
},
},
},
{
type: 'function',
function: {
name: 'search_database',
description: 'Produkte in der Datenbank suchen',
parameters: {
type: 'object',
properties: {
query: { type: 'string' },
limit: { type: 'number', default: 10 },
},
required: ['query'],
},
},
},
];
// Tool-Handler-Map
const toolHandlers: Record<string, (args: any) => Promise<any>> = {
get_weather: ({ city, units }) => fetchWeather(city, units),
search_database: ({ query, limit }) => searchDB(query, limit),
};
async function agentLoop(userMessage: string): Promise<string> {
const messages: any[] = [{ role: 'user', content: userMessage }];
while (true) {
const response = await openai.chat.completions.create({
model: MODELS.smart,
messages,
tools,
tool_choice: 'auto', // Modell entscheidet
});
const choice = response.choices[0];
messages.push(choice.message);
// Kein Tool-Call → fertig
if (choice.finish_reason === 'stop') {
return choice.message.content ?? '';
}
// Parallel Tool Calls ausführen
if (choice.message.tool_calls) {
const results = await Promise.all(
choice.message.tool_calls.map(async (tc) => {
const args = JSON.parse(tc.function.arguments);
const result = await toolHandlers[tc.function.name]?.(args);
return {
role: 'tool' as const,
tool_call_id: tc.id,
content: JSON.stringify(result),
};
})
);
messages.push(...results);
}
}
}
Mit response_format: { type: 'json_schema' } garantiert GPT-4o typsicheres JSON-Output — kein manuelles Parsing nötig:
const result = await openai.chat.completions.create({
model: MODELS.smart,
messages: [{ role: 'user', content: 'Analysiere dieses Feedback...' }],
response_format: {
type: 'json_schema',
json_schema: {
name: 'feedback_analysis',
schema: {
type: 'object',
properties: {
sentiment: { type: 'string', enum: ['positive', 'neutral', 'negative'] },
score: { type: 'number', minimum: 0, maximum: 10 },
topics: { type: 'array', items: { type: 'string' } },
summary: { type: 'string' },
},
required: ['sentiment', 'score', 'topics', 'summary'],
additionalProperties: false,
},
strict: true,
},
},
});
Die Assistants API bietet persistente KI-Agenten mit eingebautem Memory, File-Suche und Code-Interpreter. Ideal für komplexe Multi-Turn-Workflows ohne manuelles Conversation-Management.
// assistants.ts — vollständiger Assistants-Workflow
import { openai } from './client';
// 1. Assistant einmalig erstellen (in DB speichern)
export async function createMyAssistant() {
return openai.beta.assistants.create({
name: 'KI-Berater',
model: 'gpt-4o',
instructions: 'Du bist ein Experte für KI-Integration und hilfst Entwicklern.',
tools: [
{ type: 'file_search' }, // Dokumente durchsuchen
{ type: 'code_interpreter' }, // Code ausführen
],
});
}
// 2. Thread pro User-Session erstellen
export async function createThread() {
return openai.beta.threads.create();
}
// 3. Nachricht senden + Run starten
export async function sendMessage(
threadId: string,
assistantId: string,
userMessage: string
): Promise<string> {
// Nachricht zum Thread hinzufügen
await openai.beta.threads.messages.create(threadId, {
role: 'user',
content: userMessage,
});
// Run erstellen und auf Abschluss warten
const run = await openai.beta.threads.runs.createAndPoll(
threadId,
{ assistant_id: assistantId }
);
if (run.status !== 'completed') {
throw new Error(`Run failed: ${run.status}`);
}
// Letzte Antwort holen
const messages = await openai.beta.threads.messages.list(
threadId,
{ order: 'desc', limit: 1 }
);
const lastMsg = messages.data[0];
if (lastMsg.content[0].type === 'text') {
return lastMsg.content[0].text.value;
}
return '';
}
// Vector Store für Dokument-Upload
export async function addDocumentsToAssistant(
assistantId: string,
filePaths: string[]
) {
const vectorStore = await openai.beta.vectorStores.create({
name: 'Wissensbasis',
});
// Dateien hochladen und zum Vector Store hinzufügen
await openai.beta.vectorStores.fileBatches.uploadAndPoll(
vectorStore.id,
{ files: filePaths.map((p) => fs.createReadStream(p)) }
);
// Vector Store mit Assistant verknüpfen
await openai.beta.assistants.update(assistantId, {
tool_resources: { file_search: { vector_store_ids: [vectorStore.id] } },
});
}
OpenAI Embeddings wandeln Text in hochdimensionale Vektoren um, die semantische Ähnlichkeit kodieren. Kombiniert mit pgvector (PostgreSQL) oder Pinecone entstehen leistungsstarke semantische Suchsysteme.
// embeddings.ts — Embeddings + Cosine Similarity
import { openai, MODELS } from './client';
// Embedding für einen Text erzeugen
export async function embed(text: string): Promise<number[]> {
const response = await openai.embeddings.create({
model: MODELS.embed, // text-embedding-3-small (1536 dim)
input: text,
encoding_format: 'float',
});
return response.data[0].embedding;
}
// Batch-Embedding für mehrere Texte (effizienter)
export async function embedBatch(texts: string[]): Promise<number[][]> {
const response = await openai.embeddings.create({
model: MODELS.embed,
input: texts,
});
return response.data
.sort((a, b) => a.index - b.index)
.map((item) => item.embedding);
}
// Cosine Similarity berechnen
function cosineSimilarity(a: number[], b: number[]): number {
const dot = a.reduce((sum, val, i) => sum + val * b[i], 0);
const normA = Math.sqrt(a.reduce((sum, v) => sum + v * v, 0));
const normB = Math.sqrt(b.reduce((sum, v) => sum + v * v, 0));
return dot / (normA * normB);
}
// Semantic Search gegen eine Sammlung von Dokumenten
export async function semanticSearch(
query: string,
documents: { id: string; text: string; embedding: number[] }[],
topK = 5
) {
const queryEmbedding = await embed(query);
return documents
.map((doc) => ({
...doc,
score: cosineSimilarity(queryEmbedding, doc.embedding),
}))
.sort((a, b) => b.score - a.score)
.slice(0, topK);
}
// pgvector Integration (Supabase/PostgreSQL)
const pgSearch = `
SELECT id, content,
1 - (embedding <=> $1::vector) AS similarity
FROM documents
WHERE 1 - (embedding <=> $1::vector) > $2
ORDER BY similarity DESC
LIMIT $3
`;
async function vectorSearchPg(query: string, threshold = 0.7, limit = 10) {
const queryVector = await embed(query);
const vectorStr = `[${queryVector.join(',')}]`;
return db.query(pgSearch, [vectorStr, threshold, limit]);
}
// rag.ts — Retrieval Augmented Generation
async function ragQuery(userQuestion: string): Promise<string> {
// 1. Relevante Dokumente holen
const results = await vectorSearchPg(userQuestion, 0.75, 5);
const context = results.rows.map((r) => r.content).join('\n\n');
// 2. GPT-4o mit Kontext antworten lassen
return chat(`Kontext:\n${context}\n\nFrage: ${userQuestion}`);
}
GPT-4o ist nativ multimodal — es versteht Bilder sowohl per URL als auch als Base64-Daten. DALL-E 3 generiert hochwertige Bilder aus Textbeschreibungen. Zusammen entstehen komplette multimodale Pipelines.
// images.ts — DALL-E 3 Bildgenerierung
import { openai, MODELS } from './client';
import fs from 'fs/promises';
export async function generateImage(prompt: string) {
const response = await openai.images.generate({
model: MODELS.image, // dall-e-3
prompt,
n: 1,
size: '1792x1024', // Landscape, ideal für Banner
quality: 'hd', // Standard oder HD
style: 'vivid', // Vivid oder Natural
response_format: 'url',
});
return {
url: response.data[0].url,
revisedPrompt: response.data[0].revised_prompt,
};
}
// Als Base64 speichern (URL läuft nach 60 min ab!)
export async function generateAndSave(prompt: string, outputPath: string) {
const response = await openai.images.generate({
model: MODELS.image,
prompt,
response_format: 'b64_json', // Direkt als Base64
size: '1024x1024',
});
const b64 = response.data[0].b64_json!;
await fs.writeFile(outputPath, Buffer.from(b64, 'base64'));
console.log(`Bild gespeichert: ${outputPath}`);
}
// vision.ts — GPT-4o Bildanalyse
export async function analyzeImage(imageUrl: string): Promise<string> {
const response = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{
role: 'user',
content: [
{
type: 'image_url',
image_url: { url: imageUrl, detail: 'high' },
},
{
type: 'text',
text: 'Beschreibe dieses Bild auf Deutsch. Was ist zu sehen?',
},
],
},
],
max_tokens: 1024,
});
return response.choices[0].message.content ?? '';
}
// Lokales Bild als Base64 analysieren
export async function analyzeLocalImage(imagePath: string): Promise<string> {
const imageData = await fs.readFile(imagePath);
const base64 = imageData.toString('base64');
const mimeType = 'image/jpeg'; // oder image/png
const response = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{
role: 'user',
content: [
{
type: 'image_url',
image_url: {
url: `data:${mimeType};base64,${base64}`,
},
},
{ type: 'text', text: 'Was zeigt dieses Bild?' },
],
},
],
});
return response.choices[0].message.content ?? '';
}
// Komplette multimodale Pipeline: Bild analysieren → Text generieren → Bild erstellen
async function multimodalPipeline(inputImageUrl: string) {
// 1. Bild analysieren
const description = await analyzeImage(inputImageUrl);
// 2. Verbesserten Prompt generieren
const enhancedPrompt = await chat(
`Erstelle einen DALL-E Prompt auf Englisch basierend auf: ${description}`
);
// 3. Neues Bild generieren
const { url } = await generateImage(enhancedPrompt);
return { description, enhancedPrompt, generatedImageUrl: url };
}
Starte jetzt deinen kostenlosen Trial und integriere OpenAI API, Embeddings und DALL-E in deine TypeScript-Projekte — mit Unterstützung von Claude Code.
Kostenlos testen →Die OpenAI API bietet 2026 ein vollständiges Ökosystem für KI-Anwendungen: von einfachen Chat Completions über intelligentes Function Calling bis zu multimodalen Vision-Pipelines. Claude Code vereinfacht die Integration erheblich — generiert typsicheren TypeScript-Code, erkennt Fehler frühzeitig und schlägt Best Practices vor.
Der Schlüssel zu produktionsreifem Code liegt im strukturierten Aufbau: zentrale Client-Initialisierung, klare Tool-Handler-Maps, Batch-Processing für Embeddings und konsequentes Error Handling. Mit diesen Patterns skalieren KI-Anwendungen von der ersten Demo bis zum Produktionsbetrieb.