The OpenAI API provides a consistent interface to state-of-the-art AI models for text generation, natural language processing, computer vision, and more. Get started by creating an API Key and running your first API call. Discover how to generate text, analyze images, build agents, and more.
Before you begin, create an API key in the dashboard, which you’ll use to
securely access the API. Store the key
in a safe location, like a .zshrc
file or
another text file on your computer. Once you’ve generated an API key, export it
as an environment variable
in your terminal.
macOS / Linux
Export an environment variable on macOS or Linux systems
1export OPENAI_API_KEY="your_api_key_here"
Windows
Export an environment variable in PowerShell
1setxOPENAI_API_KEY"your_api_key_here"
Each OpenAI SDK automatically reads your API key from the system environment.
Install the OpenAI SDK and Run an API Call
JavaScript
To use the OpenAI API in server-side JavaScript environments like Node.js, Deno, or Bun, you can use the official OpenAI SDK for TypeScript and JavaScript. Get started by installing the SDK using npm or your preferred package manager:
Install the OpenAI SDK with npm
1npminstallopenai
With the OpenAI SDK installed, create a file called example.mjs and copy the example code into it:
Test a basic API request
1
2
3
4
5
6
7
8
9import OpenAI from"openai";constclient=newOpenAI();constresponse=await client.responses.create({ model: "gpt-5.6", input: "Write a one-sentence bedtime story about a unicorn.",});console.log(response.output_text);
Execute the code with node example.mjs (or the equivalent command for Deno or Bun). In a few moments, you should see the output of your API request.
In collaboration with Microsoft, OpenAI provides an officially supported API client for C#. You can install it with the .NET CLI from NuGet.
dotnet add package OpenAI
A simple API request to the Responses API would look like this:
Test a basic API request
1
2
3
4
5
6
7
8
9
10
11
12usingOpenAI.Responses;#pragmawarningdisable OPENAI001stringkey= Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;ResponsesClientclient=new(key);ResponseResultresponse=await client.CreateResponseAsync("gpt-5.6","Say 'this is a test.'");Console.WriteLine($"[ASSISTANT]: {response.GetOutputText()}");
Java
OpenAI provides an API helper for the Java programming language, currently in beta. You can include the Maven dependency using the following configuration:
To use the OpenAI API in Ruby, you can use the official OpenAI SDK for Ruby. Get started by adding the gem to your application:
Install the OpenAI SDK with Bundler
1gem "openai"
With the OpenAI SDK installed, create a file called example.rb and copy the example code into it:
Test a basic API request
1
2
3
4
5
6
7
8
9
10require"openai"openai=OpenAI::Client.newresponse= openai.responses.create(model:"gpt-5.6",input:"Write a one-sentence bedtime story about a unicorn.")puts(response.output_text)
Execute the code with ruby example.rb. In a few moments, you should see the output of your API request.
Congrats on running a free test API request! Start building real applications with higher limits and use our models to generate text, audio, images, videos and more.
Explore tools and docs designed to help you ship faster:
Give the model access to external data and functions by attaching tools. Use built-in tools like web search or file search, or define your own for calling APIs, running code, or integrating with third-party systems.
Web search
Use web search in a response
JavaScript
1
2
3
4
5
6
7
8
9
10import OpenAI from"openai";constclient=newOpenAI();constresponse=await client.responses.create({ model: "gpt-5.6", 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-5.6", 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
17using OpenAI.Responses;#pragma warning disable OPENAI001string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;ResponsesClient client = new(key);CreateResponseOptions options = new() { Model = "gpt-5.6" };options.Tools.Add( ResponseTool.CreateFileSearchTool(["<vector_store_id>"]));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-5.6", input: "What is deep research by OpenAI?", tools: [ { type: "file_search", vector_store_ids: ["<vector_store_id>"] } ])puts(response)
Code Interpreter
Use Code Interpreter in a response
JavaScript
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-5.6", 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-5.6", 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-5.6", 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
17require "openai"openai = OpenAI::Client.newresponse = openai.responses.create( model: "gpt-5.6", 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-5.6", "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?" }'
Function calling
Call your own function
JavaScript
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
33import OpenAI from"openai";constclient=newOpenAI();/** @type{OpenAI.Responses.Tool[]} */consttools= [ { 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-5.6", 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-5.6", 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-5.6", 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
36
37
38
39
40
41
42
43
44
45
46using System.Text.Json;using System.Text.Json.Serialization.Metadata;using OpenAI.Responses;#pragma warning disable CA1869#pragma warning disable OPENAI001string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;ResponsesClient client = new(key);CreateResponseOptions options = new() { Model = "gpt-5.6" };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 = client.CreateResponse(options);Console.WriteLine( JsonSerializer.Serialize( response.OutputItems[0], new JsonSerializerOptions { TypeInfoResolver = new DefaultJsonTypeInfoResolver(), } ));
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
33require "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-5.6", input: [ {role: "user", content: "What is the weather like in Paris today?"} ], tools: tools)puts(response.output.first.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-5.6", "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 } ] }'
Use server‑sent streaming events to show results as they’re generated, or use the Realtime API for interactive voice apps and apps with text, audio, and image inputs.
Use the OpenAI platform to build agents capable of taking action—like controlling computers—on behalf of your users. Use the Agents SDK to create orchestration logic on your server.
Build a language triage agent
JavaScript
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())