Willkommen zu unserem umfassenden Tutorial über OpenAI Function Calling — eine der leistungsstärksten Funktionen moderner KI-APIs. In dieser Anleitung erfahren Sie alles über die Definition von Tools, das korrekte Aufrufen von Functions und die professionelle Verarbeitung der Ergebnisse. Alle Code-Beispiele sind für die Verwendung mit HolySheep AI optimiert, das Ihnen gegenüber der offiziellen OpenAI-API über 85% Kosten spart.
Vergleichstabelle: API-Anbieter für Function Calling
| Feature | HolySheep AI | Offizielle OpenAI API | Andere Relay-Dienste |
|---|---|---|---|
| Function Calling | ✅ Vollständig unterstützt | ✅ Vollständig unterstützt | ⚠️ Teilweise |
| Preis-Modell | ¥1 = $1 (85%+ Ersparnis) | Standard-Preise | Variabel |
| Zahlungsmethoden | WeChat, Alipay, Kreditkarte | Nur Kreditkarte | Variabel |
| Latenz | <50ms | 50-200ms | 100-300ms |
| Startguthaben | ✅ Kostenlose Credits | ❌ Keine | Variabel |
| GPT-4.1 Preis | $8/MTok | $60/MTok | $15-40/MTok |
Was ist Function Calling?
Function Calling ermöglicht es Large Language Models, strukturierte API-Aufrufe zu generieren, die von Ihrer Anwendung ausgeführt werden können. Statt nur Text zu generieren, kann das Modell JSON-Objekte erstellen, die:
- Funktionsnamen und Parameter präzise definieren
- Eine klare Ausführungslogik ermöglichen
- Fehlerbehandlung und Validierung unterstützen
- Mehrere Tool-Aufrufe in einer Anfrage verarbeiten
Tool-Definition erstellen
Der erste Schritt besteht darin, Ihre Tools als JSON-Schema zu definieren. Diese Definition告诉 dem Modell, welche Funktionen verfügbar sind und wie sie aufgerufen werden sollen.
// Tool-Definition für eine Wetter-API
const tools = [
{
type: "function",
function: {
name: "get_weather",
description: "Ruft das aktuelle Wetter für eine bestimmte Stadt ab",
parameters: {
type: "object",
properties: {
city: {
type: "string",
description: "Der Name der Stadt (z.B. 'Berlin', 'München')"
},
unit: {
type: "string",
enum: ["celsius", "fahrenheit"],
description: "Temperatureinheit"
}
},
required: ["city"]
}
}
},
{
type: "function",
function: {
name: "get_forecast",
description: "Erhält eine 5-Tage-Wettervorhersage",
parameters: {
type: "object",
properties: {
city: {
type: "string",
description: "Der Name der Stadt"
},
days: {
type: "integer",
description: "Anzahl der Tage (1-5)",
minimum: 1,
maximum: 5
}
},
required: ["city", "days"]
}
}
}
];
Kompletter API-Aufruf mit HolySheep AI
Jetzt zeigen wir Ihnen den vollständigen Code für einen Function-Calling-Aufruf mit HolySheep AI. Unser Service bietet Ihnen:
- 85%+ Ersparnis gegenüber der offiziellen API
- <50ms Latenz für schnelle Antworten
- Kostenlose Credits für den Start
- DeepSeek V3.2 für nur $0.42/MTok
import fetch from 'node-fetch';
const HOLYSHEEP_API_KEY = 'YOUR_HOLYSHEEP_API_KEY';
const BASE_URL = 'https://api.holysheep.ai/v1';
// Tool-Definitionen
const tools = [
{
type: "function",
function: {
name: "get_weather",
description: "Ruft das aktuelle Wetter ab",
parameters: {
type: "object",
properties: {
city: {
type: "string",
description: "Stadtname"
},
unit: {
type: "string",
enum: ["celsius", "fahrenheit"]
}
},
required: ["city"]
}
}
},
{
type: "function",
function: {
name: "calculate_route",
description: "Berechnet eine Route zwischen zwei Punkten",
parameters: {
type: "object",
properties: {
start: { type: "string" },
destination: { type: "string" },
mode: {
type: "string",
enum: ["car", "walk", "bicycle"]
}
},
required: ["start", "destination"]
}
}
}
];
async function callFunctionWithTools(userMessage) {
const response = await fetch(${BASE_URL}/chat/completions, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': Bearer ${HOLYSHEEP_API_KEY}
},
body: JSON.stringify({
model: 'gpt-4.1',
messages: [
{
role: 'system',
content: 'Du bist ein intelligenter Assistent, der Tools verwendet, um Benutzeranfragen zu beantworten.'
},
{ role: 'user', content: userMessage }
],
tools: tools,
tool_choice: 'auto'
})
});
const data = await response.json();
return data;
}
// Beispiel-Aufruf
async function main() {
const result = await callFunctionWithTools(
'Wie ist das Wetter in München und wie lange dauert die Fahrt nach Hamburg?'
);
console.log('API-Antwort:', JSON.stringify(result, null, 2));
// Verarbeite Tool-Aufrufe
if (result.choices && result.choices[0].message.tool_calls) {
for (const toolCall of result.choices[0].message.tool_calls) {
console.log(\nAufgerufene Funktion: ${toolCall.function.name});
console.log('Parameter:', toolCall.function.arguments);
// Hier würden Sie die Funktion tatsächlich ausführen
const executionResult = executeTool(toolCall.function.name,
JSON.parse(toolCall.function.arguments));
console.log('Ergebnis:', executionResult);
}
}
}
function executeTool(functionName, args) {
// Simulierte Funktionsausführung
const results = {
get_weather: { temp: 18, condition: 'Sonnig', humidity: 65 },
calculate_route: { duration: '6h 30min', distance: '800km' }
};
return results[functionName] || null;
}
main().catch(console.error);
Ergebnisverarbeitung professionell gemeistert
Die Verarbeitung der Ergebnisse erfordert eine strukturierte Herangehensweise. Hier ist ein erweitertes Beispiel für die professionelle Ergebnisverarbeitung:
// Erweiterte Ergebnisverarbeitung
class FunctionCallHandler {
constructor() {
this.tools = {
get_weather: this.getWeather.bind(this),
calculate_route: this.calculateRoute.bind(this),
search_database: this.searchDatabase.bind(this),
send_notification: this.sendNotification.bind(this)
};
}
async handleResponse(apiResponse) {
const message = apiResponse.choices[0].message;
// Fall 1: Keine Tool-Aufrufe - direkte Textantwort
if (!message.tool_calls) {
return {
type: 'text',
content: message.content
};
}
// Fall 2: Ein oder mehrere Tool-Aufrufe
const toolResults = [];
for (const toolCall of message.tool_calls) {
const { name, arguments: args } = toolCall.function;
try {
// Tool ausführen
const result = await this.executeTool(name, JSON.parse(args));
toolResults.push({
tool_call_id: toolCall.id,
role: 'tool',
name: name,
content: JSON.stringify(result)
});
} catch (error) {
toolResults.push({
tool_call_id: toolCall.id,
role: 'tool',
name: name,
content: JSON.stringify({ error: error.message })
});
}
}
// Zweiter API-Aufruf mit Ergebnissen
const followUpResponse = await this.sendResultsWithContext(
apiResponse,
toolResults
);
return {
type: 'function_results',
results: toolResults,
followUp: followUpResponse.choices[0].message.content
};
}
async executeTool(name, args) {
const tool = this.tools[name];
if (!tool) {
throw new Error(Unbekannte Funktion: ${name});
}
return await tool(args);
}
async getWeather({ city, unit = 'celsius' }) {
// API-Integration hier
return {
city: city,
temperature: unit === 'celsius' ? 22 : 72,
condition: 'Teilweise bewölkt',
humidity: 55
};
}
async calculateRoute({ start, destination, mode = 'car' }) {
// Routing-Logik hier
return {
start: start,
destination: destination,
mode: mode,
duration: '4h 20min',
distance: 580
};
}
async searchDatabase({ query, limit = 10 }) {
// Datenbanksuche hier
return {
query: query,
results: [],
total: 0
};
}
async sendNotification({ user_id, message }) {
// Benachrichtigungslogik hier
return { sent: true, timestamp: new Date().toISOString() };
}
async sendResultsWithContext(originalResponse, toolResults) {
const response = await fetch(${BASE_URL}/chat/completions, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': Bearer ${HOLYSHEEP_API_KEY}
},
body: JSON.stringify({
model: 'gpt-4.1',
messages: [
...originalResponse.choices[0].message.tool_calls
? originalResponse.choices[0].message.tool_calls.map(tc => ({
role: 'assistant',
content: null,
tool_calls: [tc]
}))
: [{ role: 'assistant', content: originalResponse.choices[0].message.content }],
...toolResults.map(tr => ({
role: 'tool',
tool_call_id: tr.tool_call_id,
content: tr.content
}))
]
})
});
return await response.json();
}
}
// Verwendung
const handler = new FunctionCallHandler();
const result = await handler.handleResponse(apiResponse);
console.log('Verarbeitetes Ergebnis:', result);
Streaming für Function Calls
Für Echtzeit-Anwendungen bietet sich Streaming an. HolySheep AI unterstützt Streaming mit <50ms Latenz, was besonders für interaktive Anwendungen ideal ist:
// Streaming mit Function Calls
async function* streamFunctionCalls(userMessage) {
const response = await fetch(${BASE_URL}/chat/completions, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': Bearer ${HOLYSHEEP_API_KEY}
},
body: JSON.stringify({
model: 'gpt-4.1',
messages: [{ role: 'user', content: userMessage }],
tools: tools,
stream: true
})
});
let buffer = '';
let currentToolCall = null;
let accumulatedArguments = '';
for await (const chunk of streamIterator(response)) {
const lines = chunk.split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') {
if (currentToolCall) {
yield { type: 'tool_call_end', tool: currentToolCall };
currentToolCall = null;
}
return;
}
const parsed = JSON.parse(data);
const delta = parsed.choices?.[0]?.delta;
if (delta?.tool_calls) {
for (const toolCall of delta.tool_calls) {
if (toolCall.id && !currentToolCall) {
currentToolCall = {
id: toolCall.id,
name: toolCall.function?.name || '',
arguments: ''
};
yield { type: 'tool_call_start', tool: currentToolCall };
}
if (toolCall.function?.arguments) {
currentToolCall.arguments += toolCall.function.arguments;
yield {
type: 'tool_call_delta',
partial: currentToolCall.arguments
};
}
}
}
if (delta?.content) {
yield { type: 'content', text: delta.content };
}
}
}
}
}
// Streaming-Iterator
async function* streamIterator(response) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
yield decoder.decode(value, { stream: true });
}
}
// Verwendung
async function main() {
for await (const event of streamFunctionCalls('Wetter in Berlin?')) {
switch (event.type) {
case 'content':
process.stdout.write(event.text);
break;
case 'tool_call_start':
console.log('\n[Tool-Aufruf erkannt]', event.tool.name);
break;
case 'tool_call_delta':
// Optional: Echtzeit-Anzeige der Argumente
break;
case 'tool_call_end':
console.log('\n[Abgeschlossen]', JSON.parse(event.tool.arguments));
break;
}
}
}
Preisübersicht 2026
Mit HolySheep AI profitieren Sie von führenden Modellen zu unschlagbaren Preisen:
| Modell | Preis pro Million Tokens | Besonderheit |
|---|---|---|
| DeepSeek V3.2 | $0.42 | Bestes Preis-Leistungs-Ver
Verwandte RessourcenVerwandte Artikel🔥 HolySheep AI ausprobierenDirektes KI-API-Gateway. Claude, GPT-5, Gemini, DeepSeek — ein Schlüssel, kein VPN. |