Den vollständigen Index der Dokumentation findest du in llms.txt. Die Markdown-Version einer Dokumentationsseite erhältst du, indem du
.md an die URL der Seite anhängst.
Die OpenAI API bietet eine einheitliche Schnittstelle zu KI-Modellen auf dem neuesten Stand der Technik. Du kannst sie für die Textgenerierung, die Verarbeitung natürlicher Sprache, Computer Vision und vieles mehr nutzen. Erstelle zunächst einen API-Schlüssel und führe deinen ersten API-Aufruf aus. Erfahre anschließend, wie du Texte generierst, Bilder analysierst, Agenten entwickelst und weitere Funktionen nutzt.
Erstelle zuerst im Dashboard einen API-Schlüssel. Damit kannst du sicher auf die API zugreifen. Speichere den Schlüssel an einem sicheren Ort, etwa in deiner .zshrc-Datei oder in einer anderen Textdatei auf deinem Computer. Exportiere den erstellten API-Schlüssel im Terminal als Umgebungsvariable.
macOS / Linux
Umgebungsvariable unter macOS oder Linux exportieren
1export OPENAI_API_KEY="your_api_key_here"
Windows
Umgebungsvariable in PowerShell exportieren
1setxOPENAI_API_KEY"your_api_key_here"
Jedes OpenAI SDK liest deinen API-Schlüssel automatisch aus der Systemumgebung.
OpenAI SDK installieren und einen API-Aufruf ausführen
TypeScript
Mit dem offiziellen OpenAI SDK für TypeScript kannst du die OpenAI API in TypeScript-Anwendungen nutzen, die unter Node.js, Deno oder Bun laufen. Dasselbe Paket openai unterstützt auch reines JavaScript. Installiere das SDK zunächst mit npm oder dem Paketmanager deiner Wahl.
OpenAI SDK mit npm installieren
1npminstallopenai
Erstelle nach der Installation eine Datei namens example.mts und kopiere den Beispielcode hinein. Durch die Dateiendung .mts wird die TypeScript-Datei auch in CommonJS-Projekten als ES-Modul behandelt.
Einfache API-Anfrage testen
1
2
3
4
5
6
7
8
9import OpenAI from"openai";constclient=newOpenAI();constresponse=await client.responses.create({ model: "gpt-6-astra", input: "Write a one-sentence bedtime story about a unicorn.",});console.log(response.output_text);
Führe den Code unter Node.js ab Version 22.6 mit node --experimental-strip-types example.mts aus. Wenn du Deno oder Bun verwendest, nutze den entsprechenden Befehl. Nach kurzer Zeit solltest du die Ausgabe deiner API-Anfrage sehen.
Um das Beispiel als reines JavaScript auszuführen, speichere denselben Code als example.mjs und führe node example.mjs aus.
Mit dem offiziellen OpenAI SDK für Ruby kannst du die OpenAI API in Ruby nutzen. Füge dazu zuerst das Gem zu deiner Anwendung hinzu.
OpenAI SDK mit Bundler installieren
1gem "openai"
Sobald du das OpenAI SDK installiert hast, erstelle eine Datei namens example.rb und kopiere den folgenden Beispielcode hinein.
Eine einfache API-Anfrage testen
1
2
3
4
5
6
7
8
9
10require"openai"openai=OpenAI::Client.newresponse= openai.responses.create(model:"gpt-6-astra",input:"Write a one-sentence bedtime story about a unicorn.")puts(response.output_text)
Führe den Code mit ruby example.rb aus. Nach kurzer Zeit solltest du die Antwort auf deine API-Anfrage sehen.
Glückwunsch zu deiner ersten kostenlosen API-Testanfrage! Entwickle jetzt Anwendungen für den praktischen Einsatz. Mit höheren Nutzungslimits kannst du unsere Modelle nutzen, um Texte, Audio, Bilder, Videos und mehr zu generieren.
Mit diesen Tools und Anleitungen kannst du deine App schneller veröffentlichen.
Sende Bild-URLs, hochgeladene Dateien oder PDF-Dokumente direkt an das Modell, um Text zu extrahieren, Inhalte zu klassifizieren oder Bildelemente zu erkennen.
Binde Tools ein, damit das Modell auf externe Daten und Funktionen zugreifen kann. Nutze integrierte Tools wie die Websuche oder die Dateisuche. Du kannst auch eigene Tools definieren, um APIs aufzurufen, Code auszuführen oder Drittsysteme anzubinden.
Websuche
Websuche für eine Antwort nutzen
TypeScript
1
2
3
4
5
6
7
8
9
10import OpenAI from"openai";constclient=newOpenAI();constresponse=await client.responses.create({ model: "gpt-6-astra", tools: [{ type: "web_search" }], input: "What was a positive news story from today?",});console.log(response.output_text);
1
2
3
4
5
6
7
8
9
10
11from openai import OpenAIclient = OpenAI()response = client.responses.create( model="gpt-6-astra", tools=[{"type": "web_search"}], input="What was a positive news story from today?",)print(response.output_text)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18using OpenAI.Responses;#pragma warning disable OPENAI001string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;string vectorStoreId = "<vector_store_id>";ResponsesClient client = new(key);CreateResponseOptions options = new() { Model = "gpt-6-astra" };options.Tools.Add( ResponseTool.CreateFileSearchTool([vectorStoreId]));options.InputItems.Add( ResponseItem.CreateUserMessageItem("What is deep research by OpenAI?"));ResponseResult response = await client.CreateResponseAsync(options);Console.WriteLine(response.GetOutputText());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16require "openai"openai = OpenAI::Client.newresponse = openai.responses.create( model: "gpt-6-astra", input: "What is deep research by OpenAI?", tools: [ { type: "file_search", vector_store_ids: ["<vector_store_id>"] } ])puts(response)
Code Interpreter
Code Interpreter für eine Antwort nutzen
TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17import OpenAI from"openai";constclient=newOpenAI();constresponse=await client.responses.create({ model: "gpt-6-astra", instructions:"You are a personal math tutor. When asked a math question, write and run code to answer the question.", tools: [ { type: "code_interpreter", container: { type: "auto" }, }, ], input: "I need to solve the equation 3x + 11 = 14. Can you help me?",});console.log(response.output_text);
1
2
3
4
5
6
7
8
9
10
11
12from openai import OpenAIclient = OpenAI()response = client.responses.create( model="gpt-6-astra", instructions="You are a personal math tutor. When asked a math question, write and run code to answer the question.", tools=[{"type": "code_interpreter", "container": {"type": "auto"}}], input="I need to solve the equation 3x + 11 = 14. Can you help me?",)print(response.output_text)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25package mainimport ( "context" "fmt" "github.com/openai/openai-go/v3" "github.com/openai/openai-go/v3/responses")func main() { client := openai.NewClient() response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{ Model: "gpt-6-astra", Instructions: openai.String("You are a personal math tutor. When asked a math question, write and run code to answer the question."), Tools: []responses.ToolUnionParam{ responses.ToolParamOfCodeInterpreter(responses.ToolCodeInterpreterContainerCodeInterpreterContainerAutoParam{}), }, Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("I need to solve the equation 3x + 11 = 14. Can you help me?")}, }) if err != nil { panic(err) } fmt.Println(response.OutputText())}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20import com.openai.client.OpenAIClient;import com.openai.client.okhttp.OpenAIOkHttpClient;import com.openai.models.responses.ResponseCreateParams;import com.openai.models.responses.Tool;ResponseCreateParams params = ResponseCreateParams.builder() .model("gpt-6-astra") .input("I need to solve the equation 3x + 11 = 14. Can you help me?") .instructions( "You are a personal math tutor. When asked a math question, write and run code to answer the question.") .addCodeInterpreterTool( Tool.CodeInterpreter.Container.CodeInterpreterToolAuto.builder().build()) .build();client.responses().create(params).output().stream() .flatMap(item -> item.message().stream()) .flatMap(message -> message.content().stream()) .flatMap(content -> content.outputText().stream()) .forEach(text -> System.out.println(text.text()));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23using OpenAI.Responses;#pragma warning disable OPENAI001string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;ResponsesClient client = new(key);CodeInterpreterToolContainer container = new( CodeInterpreterToolContainerConfiguration.CreateAutomaticContainerConfiguration([]));CreateResponseOptions options = new(){ Model = "gpt-6-astra", Instructions = "You are a personal math tutor. Write and run code to answer math questions.",};options.Tools.Add(ResponseTool.CreateCodeInterpreterTool(container));options.InputItems.Add( ResponseItem.CreateUserMessageItem( "I need to solve the equation 3x + 11 = 14. Can you help me?" ));ResponseResult response = await client.CreateResponseAsync(options);Console.WriteLine(response.GetOutputText());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17require "openai"openai = OpenAI::Client.newresponse = openai.responses.create( model: "gpt-6-astra", instructions: "You are a personal math tutor. When asked a math question, write and run code to answer the question.", tools: [ { type: "code_interpreter", container: { type: "auto" } } ], input: "I need to solve the equation 3x + 11 = 14. Can you help me?")puts(response.output_text)
1
2
3
4
5
6
7
8
9
10
11
12
13
14curl https://api.openai.com/v1/responses \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ "model": "gpt-6-astra", "instructions": "You are a personal math tutor. When asked a math question, write and run code to answer the question.", "tools": [ { "type": "code_interpreter", "container": { "type": "auto" } } ], "input": "I need to solve the equation 3x + 11 = 14. Can you help me?" }'
Funktionsaufruf
Eigene Funktion aufrufen
TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32import OpenAI from"openai";constclient=newOpenAI();consttools:OpenAI.Responses.Tool[] = [ { type: "function", name: "get_weather", description: "Get current temperature for a given location.", parameters: { type: "object", properties: { location: { type: "string", description: "City and country e.g. Bogotá, Colombia", }, }, required: ["location"], additionalProperties: false, }, strict: true, },];constresponse=await client.responses.create({ model: "gpt-6-astra", input: [ { role: "user", content: "What is the weather like in Paris today?" }, ], tools,});console.log(response.output[0]);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33from openai import OpenAIclient = OpenAI()tools = [ { "type": "function", "name": "get_weather", "description": "Get current temperature for a given location.", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "City and country e.g. Bogotá, Colombia", } }, "required": ["location"], "additionalProperties": False, }, "strict": True, },]response = client.responses.create( model="gpt-6-astra", input=[ {"role": "user", "content": "What is the weather like in Paris today?"}, ], tools=tools,)print(response.output[0].to_json())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38package mainimport ( "context" "fmt" "github.com/openai/openai-go/v3" "github.com/openai/openai-go/v3/responses")func main() { client := openai.NewClient() parameters := map[string]any{ "type": "object", "properties": map[string]any{ "location": map[string]any{ "type": "string", "description": "City and country e.g. Bogotá, Colombia", }, }, "required": []string{"location"}, "additionalProperties": false, } tool := responses.ToolParamOfFunction("get_weather", parameters, true) tool.OfFunction.Description = openai.String("Get current temperature for a given location.") response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{ Model: "gpt-6-astra", Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{ responses.ResponseInputItemParamOfMessage("What is the weather like in Paris today?", responses.EasyInputMessageRoleUser), }}, Tools: []responses.ToolUnionParam{tool}, }) if err != nil { panic(err) } fmt.Println(response.Output)}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36import com.openai.client.OpenAIClient;import com.openai.client.okhttp.OpenAIOkHttpClient;import com.openai.core.JsonValue;import com.openai.models.responses.FunctionTool;import com.openai.models.responses.ResponseCreateParams;import java.util.List;import java.util.Map;ResponseCreateParams params = ResponseCreateParams.builder() .model("gpt-6-astra") .input("What is the weather like in Paris today?") .addTool( FunctionTool.builder() .name("get_weather") .description("Get current temperature for a given location.") .parameters( FunctionTool.Parameters.builder() .putAdditionalProperty("type", JsonValue.from("object")) .putAdditionalProperty( "properties", JsonValue.from( Map.of( "location", Map.of( "type", "string", "description", "City and country e.g. Bogotá, Colombia")))) .putAdditionalProperty("required", JsonValue.from(List.of("location"))) .putAdditionalProperty("additionalProperties", JsonValue.from(false)) .build()) .strict(true) .build()) .build();client.responses().create(params).output().forEach(System.out::println);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57using OpenAI.Responses;#pragma warning disable OPENAI001string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;ResponsesClient client = new(key);CreateResponseOptions options = new() { Model = "gpt-6-astra" };options.Tools.Add( ResponseTool.CreateFunctionTool( functionName: "get_weather", functionDescription: "Get current temperature for a given location.", functionParameters: BinaryData.FromString( """ { "type": "object", "properties": { "location": { "type": "string", "description": "City and country e.g. Bogotá, Colombia" } }, "required": ["location"], "additionalProperties": false } """ ), strictModeEnabled: true ));options.InputItems.Add( ResponseItem.CreateUserMessageItem("What is the weather like in Paris today?"));ResponseResult response = await client.CreateResponseAsync(options);foreach (ResponseItem outputItem in response.OutputItems){ if (outputItem is FunctionCallResponseItem functionCall) { Console.WriteLine( $"{functionCall.FunctionName}({functionCall.FunctionArguments})" ); } else if (outputItem is MessageResponseItem message) { foreach (ResponseContentPart content in message.Content) { if (content.Kind == ResponseContentPartKind.OutputText) { Console.WriteLine(content.Text); } else if (content.Kind == ResponseContentPartKind.Refusal) { Console.WriteLine(content.Refusal); } } }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36require "openai"openai = OpenAI::Client.newtools = [ { type: "function", name: "get_weather", description: "Get current temperature for a given location.", parameters: { type: "object", properties: { location: { type: "string", description: "City and country e.g. Bogotá, Colombia" } }, required: ["location"], additionalProperties: false }, strict: true }]response = openai.responses.create( model: "gpt-6-astra", input: [ { role: "user", content: "What is the weather like in Paris today?" } ], tools: tools)puts(response.output.fetch(0).to_json)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28curl -X POST https://api.openai.com/v1/responses \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-6-astra", "input": [ {"role": "user", "content": "What is the weather like in Paris today?"} ], "tools": [ { "type": "function", "name": "get_weather", "description": "Get current temperature for a given location.", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "City and country e.g. Bogotá, Colombia" } }, "required": ["location"], "additionalProperties": false }, "strict": true } ] }'
Remote-MCP
Remote-MCP-Server aufrufen
curl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16curlhttps://api.openai.com/v1/responses\-H "Content-Type: application/json"\-H "Authorization: Bearer $OPENAI_API_KEY"\-d '{ "model": "gpt-6-astra", "tools": [ { "type": "mcp", "server_label": "openai_docs", "server_description": "Search and read the public OpenAI documentation.", "server_url": "https://developers.openai.com/mcp", "require_approval": "never" } ], "input": "Search the OpenAI docs for Responses API streaming and return the relevant links." }'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19import OpenAI from "openai";const client = new OpenAI();const resp = await client.responses.create({ model: "gpt-6-astra", tools: [ { type: "mcp", server_label: "openai_docs", server_description: "Search and read the public OpenAI documentation.", server_url: "https://developers.openai.com/mcp", require_approval: "never", }, ], input: "Search the OpenAI docs for Responses API streaming and return the relevant links.",});console.log(resp.output_text);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19from openai import OpenAIclient = OpenAI()resp = client.responses.create( model="gpt-6-astra", tools=[ { "type": "mcp", "server_label": "openai_docs", "server_description": "Search and read the public OpenAI documentation.", "server_url": "https://developers.openai.com/mcp", "require_approval": "never", }, ], input="Search the OpenAI docs for Responses API streaming and return the relevant links.",)print(resp.output_text)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27package mainimport ( "context" "fmt" "github.com/openai/openai-go/v3" "github.com/openai/openai-go/v3/responses")func main() { client := openai.NewClient() tool := responses.ToolParamOfMcp("openai_docs") tool.OfMcp.ServerDescription = openai.String("Search and read the public OpenAI documentation.") tool.OfMcp.ServerURL = openai.String("https://developers.openai.com/mcp") tool.OfMcp.RequireApproval = responses.ToolMcpRequireApprovalUnionParam{OfMcpToolApprovalSetting: openai.String("never")} response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{ Model: "gpt-6-astra", Tools: []responses.ToolUnionParam{tool}, Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Search the OpenAI docs for Responses API streaming and return the relevant links.")}, }) if err != nil { panic(err) } fmt.Println(response.OutputText())}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24import com.openai.client.OpenAIClient;import com.openai.client.okhttp.OpenAIOkHttpClient;import com.openai.models.responses.ResponseCreateParams;import com.openai.models.responses.Tool;ResponseCreateParams params = ResponseCreateParams.builder() .model("gpt-6-astra") .input( "Search the OpenAI docs for Responses API streaming and return the relevant links.") .addTool( Tool.Mcp.builder() .serverLabel("openai_docs") .serverDescription("Search and read the public OpenAI documentation.") .serverUrl("https://developers.openai.com/mcp") .requireApproval(Tool.Mcp.RequireApproval.McpToolApprovalSetting.NEVER) .build()) .build();client.responses().create(params).output().stream() .flatMap(item -> item.message().stream()) .flatMap(message -> message.content().stream()) .flatMap(content -> content.outputText().stream()) .forEach(text -> System.out.println(text.text()));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19using OpenAI.Responses;#pragma warning disable OPENAI001string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;ResponsesClient client = new(key);CreateResponseOptions options = new() { Model = "gpt-6-astra" };options.Tools.Add( ResponseTool.CreateMcpTool( serverLabel: "openai_docs", serverUri: new Uri("https://developers.openai.com/mcp"), toolCallApprovalPolicy: DefaultMcpToolCallApprovalPolicy.NeverRequireApproval ));options.InputItems.Add(ResponseItem.CreateUserMessageItem("Search the OpenAI docs for Responses API streaming and return the relevant links."));ResponseResult response = await client.CreateResponseAsync(options);Console.WriteLine(response.GetOutputText());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19require "openai"openai = OpenAI::Client.newresponse = openai.responses.create( model: "gpt-6-astra", tools: [ { type: "mcp", server_label: "openai_docs", server_description: "Search and read the public OpenAI documentation.", server_url: "https://developers.openai.com/mcp", require_approval: "never" } ], input: "Search the OpenAI docs for Responses API streaming and return the relevant links.")puts(response.output_text)
Mit Streaming-Ereignissen, die der Server sendet, kannst du Ergebnisse schon während der Generierung anzeigen. Nutze die Realtime API für interaktive Sprach-Apps und Apps mit Text-, Audio- und Bildeingaben.
Entwickle auf der OpenAI-Plattform Agenten, die im Auftrag der Menschen handeln, die deine App nutzen. Die Agenten können zum Beispiel Computer steuern. Mit dem Agents SDK legst du auf deinem Server fest, wie die Agenten zusammenarbeiten.
Einen Agenten entwickeln, der Anfragen nach Sprache weiterleitet
TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21import { Agent, run } from"@openai/agents";constspanishAgent=newAgent({ name: "Spanish agent", instructions: "You only speak Spanish.",});constenglishAgent=newAgent({ name: "English agent", instructions: "You only speak English",});consttriageAgent=newAgent({ name: "Triage agent", instructions:"Handoff to the appropriate agent based on the language of the request.", handoffs: [spanishAgent, englishAgent],});constresult=awaitrun(triageAgent, "Hola, ¿cómo estás?");console.log(result.finalOutput);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27from agents import Agent, Runnerimport asynciospanish_agent = Agent( name="Spanish agent", instructions="You only speak Spanish.",)english_agent = Agent( name="English agent", instructions="You only speak English",)triage_agent = Agent( name="Triage agent", instructions="Handoff to the appropriate agent based on the language of the request.", handoffs=[spanish_agent, english_agent],)async def main(): result = await Runner.run(triage_agent, input="Hola, ¿cómo estás?") print(result.final_output)if __name__ == "__main__": asyncio.run(main())