OpenAI API 开发者快速开始

2026-11-06 18:55 更新

通过OpenAI API,可以使用模型生成文本、处理自然语言、分析图像并构建智能体。先创建密钥并完成一次Responses请求,再根据应用需要添加文件、工具或流式交互。

创建并导出 API 密钥

在控制台创建API密钥,并保存在本机安全位置。SDK会读取 OPENAI_API_KEY 环境变量。下面分别是macOS/Linux和Windows PowerShell命令。

Bash

## 在macOS或Linux当前终端设置API密钥
export OPENAI_API_KEY="your_api_key_here"

PowerShell

## 持久保存Windows用户环境变量,供新终端读取
setx OPENAI_API_KEY "your_api_key_here"

PowerShell运行 setx 后需要新开终端;要立即用于当前会话,可设置 $env:OPENAI_API_KEY = "your_api_key_here"。不要把真实密钥写进源代码。

安装 SDK 并发送首次请求

选择正在使用的语言,安装其依赖后运行相应示例。JavaScript示例可保存为 example.mjs 并用 node example.mjs 运行;Python可保存为 example.py 并用 python example.py 运行;Ruby可保存为 example.rb 并用 ruby example.rb 运行。C#在.NET项目中添加包,Java使用Maven依赖,Go使用v3模块。示例中的英文提示词保留原文,便于对照不同语言的请求。

Bash

## 安装客户端或发送首次Responses请求
npm install openai

JavaScript

// 安装客户端或发送首次Responses请求;从环境读取凭证,发送请求并读取响应
import OpenAI from "openai";
// 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
const client = new OpenAI();

const response = await client.responses.create({
  model: "gpt-6-astra",
  input: "Write a one-sentence bedtime story about a unicorn.",
});

// 显示本次结果;实际文本与示例不必逐字相同
console.log(response.output_text);

Bash

## 安装客户端或发送首次Responses请求
pip install openai

Python

## 安装客户端或发送首次Responses请求;从环境读取凭证,发送请求并读取响应
from openai import OpenAI

## 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
client = OpenAI()

response = client.responses.create(
    model="gpt-6-astra",
    input="Write a one-sentence bedtime story about a unicorn.",
)

## 显示本次结果;实际文本与示例不必逐字相同
print(response.output_text)

Bash

## 安装客户端或发送首次Responses请求
dotnet add package OpenAI

C# / .NET

// 安装客户端或发送首次Responses请求
using OpenAI.Responses;
#pragma warning disable OPENAI001

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
// 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
ResponsesClient client = new(key);

ResponseResult response = await client.CreateResponseAsync(
    "gpt-6-astra",
    "Say 'this is a test.'"
);

// 显示本次结果;实际文本与示例不必逐字相同
Console.WriteLine($"[ASSISTANT]: {response.GetOutputText()}");

Maven XML

<!-- 安装客户端或发送首次Responses请求:声明依赖坐标和版本 -->
<dependency>
  <groupId>com.openai</groupId>
  <artifactId>openai-java</artifactId>
  <version>4.89.0</version>
</dependency>

Java

// 安装客户端或发送首次Responses请求;从环境读取凭证,发送请求并读取响应
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;

public class Main {
  public static void main(String[] args) {
    // 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
    OpenAIClient client = OpenAIOkHttpClient.fromEnv();

    ResponseCreateParams params =
        ResponseCreateParams.builder().input("Say this is a test").model("gpt-6-astra").build();

    Response response = client.responses().create(params);
    response.output().stream()
        .flatMap(item -> item.message().stream())
        .flatMap(message -> message.content().stream())
        .flatMap(content -> content.outputText().stream())
        .forEach(outputText -> System.out.println(outputText.text()));
  }
}

Go

// 安装客户端或发送首次Responses请求
import (
    "github.com/openai/openai-go/v3" // imported as openai
)

Go

// 安装客户端或发送首次Responses请求;从环境读取凭证,发送请求并读取响应
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/responses"
)

func main() {
    // 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
    client := openai.NewClient()

    resp, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{
        Model: "gpt-6-astra",
        Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say this is a test")},
    })
    if err != nil {
        panic(err.Error())
    }

    // 显示本次结果;实际文本与示例不必逐字相同
    fmt.Println(resp.OutputText())
}

Ruby

## 安装客户端或发送首次Responses请求
gem "openai"

Ruby

## 安装客户端或发送首次Responses请求;从环境读取凭证,发送请求并读取响应
require "openai"

## 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
openai = OpenAI::Client.new

response = openai.responses.create(
  model: "gpt-6-astra",
  input: "Write a one-sentence bedtime story about a unicorn."
)

## 显示本次结果;实际文本与示例不必逐字相同
puts(response.output_text)

各语言客户端说明及Azure、社区项目列表见SDK与命令行工具。可使用Responses示例应用继续构建,并了解文本生成与提示词。

查看账单并继续构建

首次请求运行成功后,可以在账单页面查看账户用量和可用的充值选项,继续构建文本、音频、图像或视频应用。实际可用额度与限制以账户显示为准。

Chat Playground可用来测试对话提示词;Agents SDK用于构建、运行和观察智能体工作流。

分析图像与文件

可把图像URL、文件URL、已上传文件或PDF放入请求,让模型提取文本、分类内容或识别视觉元素。图像输入使用 input_image,文件输入使用 input_file。

图像URL

将图像地址与问题放入同一条消息的content数组。各语言示例可能使用不同的演示图片与提问,按相应示例理解结果。

JavaScript

// 图像URL;从环境读取凭证,发送请求并读取响应
import OpenAI from "openai";
// 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
const client = new OpenAI();

const response = await client.responses.create({
  model: "gpt-6-astra",
  input: [
    {
      role: "user",
      content: [
        {
          type: "input_text",
          text: "What is in this image?",
        },
        {
          type: "input_image",
          image_url:
            "https://openai-documentation.vercel.app/images/cat_and_otter.png",
          detail: "auto",
        },
      ],
    },
  ],
});

// 显示本次结果;实际文本与示例不必逐字相同
console.log(response.output_text);

Python

## 图像URL;从环境读取凭证,发送请求并读取响应
from openai import OpenAI

## 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
client = OpenAI()

response = client.responses.create(
    model="gpt-6-astra",
    input=[
        {
            "role": "user",
            "content": [
                {
                    "type": "input_text",
                    "text": "What teams are playing in this image?",
                },
                {
                    "type": "input_image",
                    "image_url": "https://api.nga.gov/iiif/a2e6da57-3cd1-4235-b20e-95dcaefed6c8/full/!800,800/0/default.jpg",
                },
            ],
        }
    ],
)

## 显示本次结果;实际文本与示例不必逐字相同
print(response.output_text)

Go

// 图像URL;从环境读取凭证,发送请求并读取响应
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/responses"
)

func main() {
    // 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
    client := openai.NewClient()
    response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model: "gpt-6-astra",
        Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{
            responses.ResponseInputItemParamOfMessage(
                responses.ResponseInputMessageContentListParam{
                    responses.ResponseInputContentParamOfInputText("What is in this image?"),
                    {OfInputImage: &responses.ResponseInputImageParam{
                        Detail:   responses.ResponseInputImageDetailAuto,
                        ImageURL: openai.String("https://openai-documentation.vercel.app/images/cat_and_otter.png"),
                    }},
                },
                responses.EasyInputMessageRoleUser,
            ),
        }},
    })
    if err != nil {
        panic(err)
    }
    // 显示本次结果;实际文本与示例不必逐字相同
    fmt.Println(response.OutputText())
}

Java

// 图像URL;从环境读取凭证,发送请求并读取响应
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputImage;
import com.openai.models.responses.ResponseInputItem;
import java.util.List;

ResponseInputItem imageInput =
    ResponseInputItem.ofMessage(
        ResponseInputItem.Message.builder()
            .role(ResponseInputItem.Message.Role.USER)
            .addInputTextContent("What teams are playing in this image?")
            .addContent(
                ResponseInputImage.builder()
                    .detail(ResponseInputImage.Detail.AUTO)
                    .imageUrl(
                        "https://api.nga.gov/iiif/a2e6da57-3cd1-4235-b20e-95dcaefed6c8/full/!800,800/0/default.jpg")
                    .build())
            .build());

ResponseCreateParams params =
    ResponseCreateParams.builder()
        .model("gpt-6-astra")
        .inputOfResponse(List.of(imageInput))
        .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()));

C# / .NET

// 图像URL
using OpenAI.Responses;
#pragma warning disable OPENAI001

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
// 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
ResponsesClient client = new(key);

Uri imageUrl = new(
    "https://openai-documentation.vercel.app/images/cat_and_otter.png"
);

ResponseResult response = await client.CreateResponseAsync(
    "gpt-6-astra",
    [
        ResponseItem.CreateUserMessageItem(
            [
                ResponseContentPart.CreateInputTextPart("What is in this image?"),
                ResponseContentPart.CreateInputImagePart(imageUrl),
            ]
        ),
    ]
);

// 显示本次结果;实际文本与示例不必逐字相同
Console.WriteLine(response.GetOutputText());

Ruby

## 图像URL;从环境读取凭证,发送请求并读取响应
require "openai"

## 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
openai = OpenAI::Client.new

response = openai.responses.create(
  model: "gpt-6-astra",
  input: [
    {
      role: "user",
      content: [
        {
          type: "input_text",
          text: "What teams are playing in this image?"
        },
        {
          type: "input_image",
          image_url: "https://api.nga.gov/iiif/a2e6da57-3cd1-4235-b20e-95dcaefed6c8/full/!800,800/0/default.jpg"
        }
      ]
    }
  ]
)

## 显示本次结果;实际文本与示例不必逐字相同
puts(response.output_text)

cURL / Bash

## 图像URL
curl "https://api.openai.com/v1/responses" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $OPENAI_API_KEY" \
    -d '{
        "model": "gpt-6-astra",
        "input": [
            {
                "role": "user",
                "content": [
                    {
                        "type": "input_text",
                        "text": "What is in this image?"
                    },
                    {
                        "type": "input_image",
                        "image_url": "https://openai-documentation.vercel.app/images/cat_and_otter.png"
                    }
                ]
            }
        ]
}'

OpenAI CLI / Bash

## 图像URL
openai responses create \
  --model gpt-6-astra \
  --raw-output \
  --transform 'output.#(type=="message").content.0.text' <<'YAML'
input:
  - role: user
    content:
      - type: input_text
        text: What is in this image?
      - type: input_image
        image_url: https://openai-documentation.vercel.app/images/cat_and_otter.png
YAML

文件URL

通过file_url传入公开可访问的PDF地址,要求模型归纳内容。

JavaScript

// 文件URL;从环境读取凭证,发送请求并读取响应
import OpenAI from "openai";
// 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
const client = new OpenAI();

const response = await client.responses.create({
  model: "gpt-6-astra",
  input: [
    {
      role: "user",
      content: [
        {
          type: "input_text",
          text: "Analyze the letter and provide a summary of the key points.",
        },
        {
          type: "input_file",
          file_url: "https://www.berkshirehathaway.com/letters/2024ltr.pdf",
        },
      ],
    },
  ],
});

// 显示本次结果;实际文本与示例不必逐字相同
console.log(response.output_text);

Python

## 文件URL;从环境读取凭证,发送请求并读取响应
from openai import OpenAI

## 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
client = OpenAI()

response = client.responses.create(
    model="gpt-6-astra",
    input=[
        {
            "role": "user",
            "content": [
                {
                    "type": "input_text",
                    "text": "Analyze the letter and provide a summary of the key points.",
                },
                {
                    "type": "input_file",
                    "file_url": "https://www.berkshirehathaway.com/letters/2024ltr.pdf",
                },
            ],
        },
    ],
)

## 显示本次结果;实际文本与示例不必逐字相同
print(response.output_text)

Go

// 文件URL;从环境读取凭证,发送请求并读取响应
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/responses"
)

func main() {
    // 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
    client := openai.NewClient()

    response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model: "gpt-6-astra",
        Input: responses.ResponseNewParamsInputUnion{
            OfInputItemList: responses.ResponseInputParam{
                responses.ResponseInputItemParamOfMessage(
                    responses.ResponseInputMessageContentListParam{
                        responses.ResponseInputContentParamOfInputText(
                            "Analyze the letter and provide a summary of the key points.",
                        ),
                        {
                            OfInputFile: &responses.ResponseInputFileParam{
                                FileURL: openai.String(
                                    "https://www.berkshirehathaway.com/letters/2024ltr.pdf",
                                ),
                            },
                        },
                    },
                    responses.EasyInputMessageRoleUser,
                ),
            },
        },
    })
    if err != nil {
        panic(err)
    }

    // 显示本次结果;实际文本与示例不必逐字相同
    fmt.Println(response.OutputText())
}

Java

// 文件URL;从环境读取凭证,发送请求并读取响应
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputFile;
import com.openai.models.responses.ResponseInputItem;
import java.util.List;

ResponseCreateParams params =
    ResponseCreateParams.builder()
        .model("gpt-6-astra")
        .inputOfResponse(
            List.of(
                ResponseInputItem.ofMessage(
                    ResponseInputItem.Message.builder()
                        .role(ResponseInputItem.Message.Role.USER)
                        .addInputTextContent(
                            "Analyze the letter and provide a summary of the key points.")
                        .addContent(
                            ResponseInputFile.builder()
                                .fileUrl(
                                    "https://www.berkshirehathaway.com/letters/2024ltr.pdf")
                                .build())
                        .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()));

C# / .NET

// 文件URL
using OpenAI.Responses;
#pragma warning disable OPENAI001

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
// 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
ResponsesClient client = new(key);

Uri fileUrl = new(
    "https://www.berkshirehathaway.com/letters/2024ltr.pdf"
);

ResponseResult response = await client.CreateResponseAsync(
    "gpt-6-astra",
    [
        ResponseItem.CreateUserMessageItem(
            [
                ResponseContentPart.CreateInputTextPart(
                    "Analyze the letter and provide a summary of the key points."
                ),
                ResponseContentPart.CreateInputFilePart(fileUrl),
            ]
        ),
    ]
);

// 显示本次结果;实际文本与示例不必逐字相同
Console.WriteLine(response.GetOutputText());

Ruby

## 文件URL;从环境读取凭证,发送请求并读取响应
require "openai"

## 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
openai = OpenAI::Client.new

response = openai.responses.create(
  model: "gpt-6-astra",
  input: [
    {
      role: "user",
      content: [
        {
          type: "input_text",
          text: "Analyze the letter and provide a summary of the key points."
        },
        {
          type: "input_file",
          file_url: "https://www.berkshirehathaway.com/letters/2024ltr.pdf"
        }
      ]
    }
  ]
)

## 显示本次结果;实际文本与示例不必逐字相同
puts(response.output_text)

cURL / Bash

## 文件URL
curl "https://api.openai.com/v1/responses" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $OPENAI_API_KEY" \
    -d '{
        "model": "gpt-6-astra",
        "input": [
            {
                "role": "user",
                "content": [
                    {
                        "type": "input_text",
                        "text": "Analyze the letter and provide a summary of the key points."
                    },
                    {
                        "type": "input_file",
                        "file_url": "https://www.berkshirehathaway.com/letters/2024ltr.pdf"
                    }
                ]
            }
        ]
    }'

上传文件

先以user_data用途上传本地PDF,取得文件ID,再以input_file.file_id引用;运行前准备示例PDF。cURL版本中的文件ID占位符需替换为前一次上传实际返回的ID。

JavaScript

// 上传文件;从环境读取凭证,发送请求并读取响应
import fs from "fs";
import OpenAI from "openai";
// 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
const client = new OpenAI();

const file = await client.files.create({
  file: fs.createReadStream("fixtures/draconomicon.pdf"),
  purpose: "user_data",
});

const response = await client.responses.create({
  model: "gpt-6-astra",
  input: [
    {
      role: "user",
      content: [
        {
          type: "input_file",
          file_id: file.id,
        },
        {
          type: "input_text",
          text: "What is the first dragon in the book?",
        },
      ],
    },
  ],
});

// 显示本次结果;实际文本与示例不必逐字相同
console.log(response.output_text);

Python

## 上传文件;从环境读取凭证,发送请求并读取响应
from openai import OpenAI

## 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
client = OpenAI()

file = client.files.create(file=open("draconomicon.pdf", "rb"), purpose="user_data")

response = client.responses.create(
    model="gpt-6-astra",
    input=[
        {
            "role": "user",
            "content": [
                {
                    "type": "input_file",
                    "file_id": file.id,
                },
                {
                    "type": "input_text",
                    "text": "What is the first dragon in the book?",
                },
            ],
        }
    ],
)

## 显示本次结果;实际文本与示例不必逐字相同
print(response.output_text)

Go

// 上传文件;从环境读取凭证,发送请求并读取响应
package main

import (
    "context"
    "fmt"
    "os"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/responses"
)

func main() {
    // 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
    client := openai.NewClient()

    file, err := os.Open("draconomicon.pdf")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    uploadedFile, err := client.Files.New(context.Background(), openai.FileNewParams{
        File:    file,
        Purpose: openai.FilePurposeUserData,
    })
    if err != nil {
        panic(err)
    }

    response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model: "gpt-6-astra",
        Input: responses.ResponseNewParamsInputUnion{
            OfInputItemList: responses.ResponseInputParam{
                responses.ResponseInputItemParamOfMessage(
                    responses.ResponseInputMessageContentListParam{
                        {
                            OfInputFile: &responses.ResponseInputFileParam{
                                FileID: openai.String(uploadedFile.ID),
                            },
                        },
                        responses.ResponseInputContentParamOfInputText(
                            "What is the first dragon in the book?",
                        ),
                    },
                    responses.EasyInputMessageRoleUser,
                ),
            },
        },
    })
    if err != nil {
        panic(err)
    }

    // 显示本次结果;实际文本与示例不必逐字相同
    fmt.Println(response.OutputText())
}

Java

// 上传文件;从环境读取凭证,发送请求并读取响应
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.files.FileCreateParams;
import com.openai.models.files.FilePurpose;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputFile;
import com.openai.models.responses.ResponseInputItem;
import java.nio.file.Path;
import java.util.List;

var file =
    client
        .files()
        .create(
            FileCreateParams.builder()
                .file(Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH")))
                .purpose(FilePurpose.USER_DATA)
                .build());

var response =
    client
        .responses()
        .create(
            ResponseCreateParams.builder()
                .model("gpt-6-astra")
                .inputOfResponse(
                    List.of(
                        ResponseInputItem.ofMessage(
                            ResponseInputItem.Message.builder()
                                .role(ResponseInputItem.Message.Role.USER)
                                .addContent(
                                    ResponseInputFile.builder().fileId(file.id()).build())
                                .addInputTextContent("What is the first dragon in the book?")
                                .build())))
                .build());
response.output().stream()
    .flatMap(item -> item.message().stream())
    .flatMap(message -> message.content().stream())
    .flatMap(content -> content.outputText().stream())
    .forEach(text -> System.out.println(text.text()));

C# / .NET

// 上传文件
using OpenAI.Files;
using OpenAI.Responses;
#pragma warning disable OPENAI001

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
// 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
ResponsesClient client = new(key);

OpenAIFileClient files = new(key);

OpenAIFile file = await files.UploadFileAsync(
    "draconomicon.pdf",
    FileUploadPurpose.UserData
);

ResponseResult response = await client.CreateResponseAsync(
    "gpt-6-astra",
    [
        ResponseItem.CreateUserMessageItem(
            [
                ResponseContentPart.CreateInputFilePart(file.Id),
                ResponseContentPart.CreateInputTextPart(
                    "What is the first dragon in the book?"
                ),
            ]
        ),
    ]
);

// 显示本次结果;实际文本与示例不必逐字相同
Console.WriteLine(response.GetOutputText());

Ruby

## 上传文件;从环境读取凭证,发送请求并读取响应
require "openai"
require "pathname"

## 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
openai = OpenAI::Client.new

file = openai.files.create(
  file: Pathname("draconomicon.pdf"),
  purpose: "user_data"
)

response = openai.responses.create(
  model: "gpt-6-astra",
  input: [
    {
      role: "user",
      content: [
        {
          type: "input_file",
          file_id: file.id
        },
        {
          type: "input_text",
          text: "What is the first dragon in the book?"
        }
      ]
    }
  ]
)

## 显示本次结果;实际文本与示例不必逐字相同
puts(response.output_text)

cURL / Bash

## 上传文件
curl https://api.openai.com/v1/files \
    -H "Authorization: Bearer $OPENAI_API_KEY" \
    -F purpose="user_data" \
    -F file="@draconomicon.pdf"

curl "https://api.openai.com/v1/responses" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $OPENAI_API_KEY" \
    -d '{
        "model": "gpt-6-astra",
        "input": [
            {
                "role": "user",
                "content": [
                    {
                        "type": "input_file",
                        "file_id": "file-6F2ksmvXxt4VdoqmHRw6kL"
                    },
                    {
                        "type": "input_text",
                        "text": "What is the first dragon in the book?"
                    }
                ]
            }
        ]
    }'

图像输入的格式与边界见图像与视觉;文件输入限制见文件输入。

使用工具扩展模型能力

在请求的 tools 中声明工具,可以让模型访问外部信息和功能。可使用托管的网页搜索、文件搜索和代码解释器,也可以提供应用自己的函数或连接远程MCP服务器。

网页搜索

添加web_search工具,让模型根据当日网页信息回答问题。

JavaScript

// 网页搜索;从环境读取凭证,发送请求并读取响应
import OpenAI from "openai";
// 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
const client = new OpenAI();

const response = 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);

Python

## 网页搜索;从环境读取凭证,发送请求并读取响应
from openai import OpenAI

## 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
client = 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)

Go

// 网页搜索;从环境读取凭证,发送请求并读取响应
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/responses"
)

func main() {
    // 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
    client := openai.NewClient()
    response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model: "gpt-6-astra",
        Tools: []responses.ToolUnionParam{
            responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch),
        },
        Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What was a positive news story from today?")},
    })
    if err != nil {
        panic(err)
    }
    // 显示本次结果;实际文本与示例不必逐字相同
    fmt.Println(response.OutputText())
}

Java

// 网页搜索;从环境读取凭证,发送请求并读取响应
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.WebSearchTool;

ResponseCreateParams params =
    ResponseCreateParams.builder()
        .model("gpt-6-astra")
        .input("What was a positive news story from today?")
        .addTool(WebSearchTool.builder().type(WebSearchTool.Type.WEB_SEARCH).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()));

C# / .NET

// 网页搜索
using OpenAI.Responses;
#pragma warning disable OPENAI001

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
// 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
ResponsesClient client = new(key);

CreateResponseOptions options = new() { Model = "gpt-6-astra" };
options.Tools.Add(ResponseTool.CreateWebSearchTool());
options.InputItems.Add(
    ResponseItem.CreateUserMessageItem("What was a positive news story from today?")
);

ResponseResult response = await client.CreateResponseAsync(options);

// 显示本次结果;实际文本与示例不必逐字相同
Console.WriteLine(response.GetOutputText());

Ruby

## 网页搜索;从环境读取凭证,发送请求并读取响应
require "openai"

## 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
openai = OpenAI::Client.new

response = openai.responses.create(
  model: "gpt-6-astra",
  tools: [{ type: "web_search" }],
  input: "What was a positive news story from today?"
)

## 显示本次结果;实际文本与示例不必逐字相同
puts(response.output_text)

cURL / Bash

## 网页搜索
curl "https://api.openai.com/v1/responses" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $OPENAI_API_KEY" \
    -d '{
        "model": "gpt-6-astra",
        "tools": [{"type": "web_search"}],
        "input": "what was a positive news story from today?"
}'

OpenAI CLI / Bash

## 网页搜索
openai responses create \
  --model gpt-6-astra \
  --raw-output \
  --transform 'output.#(type=="message").content.0.text' <<'YAML'
tools:
  - type: web_search
input: What was a positive news story from today?
YAML

文件搜索

提供实际vector_store_ids,使模型检索已经加入向量存储的文件;先准备相应资源,再替换占位符。

JavaScript

// 文件搜索;从环境读取凭证,发送请求并读取响应
import OpenAI from "openai";
// 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
const openai = new OpenAI();

const response = await openai.responses.create({
  model: "gpt-6-astra",
  input: "What is deep research by OpenAI?",
  tools: [
    {
      type: "file_search",
      vector_store_ids: ["<vector_store_id>"],
    },
  ],
});
// 显示本次结果;实际文本与示例不必逐字相同
console.log(response);

Python

## 文件搜索;从环境读取凭证,发送请求并读取响应
from openai import OpenAI

## 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
client = OpenAI()

response = client.responses.create(
    model="gpt-6-astra",
    input="What is deep research by OpenAI?",
    tools=[{"type": "file_search", "vector_store_ids": ["<vector_store_id>"]}],
)
## 显示本次结果;实际文本与示例不必逐字相同
print(response)

Go

// 文件搜索;从环境读取凭证,发送请求并读取响应
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/responses"
)

func main() {
    // 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
    client := openai.NewClient()
    response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model: "gpt-6-astra",
        Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What is deep research by OpenAI?")},
        Tools: []responses.ToolUnionParam{responses.ToolParamOfFileSearch([]string{"<vector_store_id>"})},
    })
    if err != nil {
        panic(err)
    }
    // 显示本次结果;实际文本与示例不必逐字相同
    fmt.Println(response)
}

Java

// 文件搜索;从环境读取凭证,发送请求并读取响应
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
import java.util.List;

String vectorStoreId = "<vector_store_id>";

ResponseCreateParams params =
    ResponseCreateParams.builder()
        .model("gpt-6-astra")
        .input("What is deep research by OpenAI?")
        .addFileSearchTool(List.of(vectorStoreId))
        .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()));

C# / .NET

// 文件搜索
using OpenAI.Responses;
#pragma warning disable OPENAI001

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string vectorStoreId = "<vector_store_id>";
// 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
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());

Ruby

## 文件搜索;从环境读取凭证,发送请求并读取响应
require "openai"

## 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
openai = OpenAI::Client.new

response = 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)

代码解释器

启用自动容器,让模型编写并运行代码。本例给出数学辅导指令,并让模型求解方程。

JavaScript

// 代码解释器;从环境读取凭证,发送请求并读取响应
import OpenAI from "openai";
// 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
const client = new OpenAI();

const response = 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);

Python

## 代码解释器;从环境读取凭证,发送请求并读取响应
from openai import OpenAI

## 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
client = 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)

Go

// 代码解释器;从环境读取凭证,发送请求并读取响应
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/responses"
)

func main() {
    // 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
    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())
}

Java

// 代码解释器;从环境读取凭证,发送请求并读取响应
import 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()));

C# / .NET

// 代码解释器
using OpenAI.Responses;
#pragma warning disable OPENAI001

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
// 创建客户端;使用 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());

Ruby

## 代码解释器;从环境读取凭证,发送请求并读取响应
require "openai"

## 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
openai = OpenAI::Client.new

response = 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)

cURL / Bash

## 代码解释器
curl 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?"
  }'

函数调用

声明get_weather名称、参数Schema与严格模式,查看模型返回的函数调用。这里只展示函数声明和调用请求,不会替你执行天气查询;完整应用还需执行函数并回传结果。

JavaScript

// 函数调用;从环境读取凭证,发送请求并读取响应
import OpenAI from "openai";
// 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
const client = new OpenAI();

const 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,
  },
];

const response = 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]);

Python

## 函数调用;从环境读取凭证,发送请求并读取响应
from openai import OpenAI

## 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
client = 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())

Go

// 函数调用;从环境读取凭证,发送请求并读取响应
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/responses"
)

func main() {
    // 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
    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)
}

Java

// 函数调用;从环境读取凭证,发送请求并读取响应
import 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);

C# / .NET

// 函数调用
using OpenAI.Responses;
#pragma warning disable OPENAI001

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
// 创建客户端;使用 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);
            }
        }
    }
}

Ruby

## 函数调用;从环境读取凭证,发送请求并读取响应
require "openai"

## 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
openai = OpenAI::Client.new

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 = 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)

cURL / Bash

## 函数调用
curl -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
      }
    ]
  }'

远程MCP

连接公开OpenAI文档MCP服务器。示例的require_approval为never,表示此示例不要求工具调用批准;按实际服务器和应用要求配置,不将该设置默认推广到其他服务。

cURL / Bash

## 远程MCP
curl https://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."
  }'

JavaScript

// 远程MCP;从环境读取凭证,发送请求并读取响应
import OpenAI from "openai";
// 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
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);

Python

## 远程MCP;从环境读取凭证,发送请求并读取响应
from openai import OpenAI

## 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
client = 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)

Go

// 远程MCP;从环境读取凭证,发送请求并读取响应
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/responses"
)

func main() {
    // 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
    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())
}

Java

// 远程MCP;从环境读取凭证,发送请求并读取响应
import 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()));

C# / .NET

// 远程MCP
using OpenAI.Responses;
#pragma warning disable OPENAI001

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
// 创建客户端;使用 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());

Ruby

## 远程MCP;从环境读取凭证,发送请求并读取响应
require "openai"

## 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
openai = OpenAI::Client.new

response = 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)

相关结构与用法见工具指南和函数调用。

流式响应与实时应用

开启服务端发送事件流,可在生成过程中逐步显示结果。以下示例开启 stream 并遍历事件,不把流式返回当作已经完成的普通响应对象。

JavaScript

// 流式读取Responses事件;从环境读取凭证,发送请求并读取响应
import { OpenAI } from "openai";
// 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
const client = new OpenAI();

const stream = await client.responses.create({
  model: "gpt-6-astra",
  input: [
    {
      role: "user",
      content: "Say 'double bubble bath' ten times fast.",
    },
  ],
  stream: true,
});

for await (const event of stream) {
  // 显示本次结果;实际文本与示例不必逐字相同
  console.log(event);
}

Python

## 流式读取Responses事件;从环境读取凭证,发送请求并读取响应
from openai import OpenAI

## 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
client = OpenAI()

stream = client.responses.create(
    model="gpt-6-astra",
    input=[
        {
            "role": "user",
            "content": "Say 'double bubble bath' ten times fast.",
        },
    ],
    stream=True,
)

for event in stream:
    # 显示本次结果;实际文本与示例不必逐字相同
    print(event)

Go

// 流式读取Responses事件;从环境读取凭证,发送请求并读取响应
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/responses"
)

func main() {
    // 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
    client := openai.NewClient()
    stream := client.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{
        Model: "gpt-6-astra",
        Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say 'double bubble bath' ten times fast.")},
    })
    for stream.Next() {
        // 显示本次结果;实际文本与示例不必逐字相同
        fmt.Println(stream.Current().Type)
    }
    if err := stream.Err(); err != nil {
        panic(err)
    }
}

Java

// 流式读取Responses事件;从环境读取凭证,发送请求并读取响应
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.StreamResponse;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseStreamEvent;

ResponseCreateParams params =
    ResponseCreateParams.builder()
        .model("gpt-6-astra")
        .input("Say 'double bubble bath' ten times fast.")
        .build();

try (StreamResponse<ResponseStreamEvent> stream = client.responses().createStreaming(params)) {
  stream.stream().forEach(System.out::println);
}

C# / .NET

// 流式读取Responses事件;从环境读取凭证,发送请求并读取响应
using OpenAI.Responses;
#pragma warning disable OPENAI001

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
// 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
ResponsesClient client = new(key);

var responses = client.CreateResponseStreamingAsync(
    "gpt-6-astra",
    "Say 'double bubble bath' ten times fast."
);

await foreach (StreamingResponseUpdate response in responses)
{
    if (response is StreamingResponseOutputTextDeltaUpdate delta)
    {
        Console.Write(delta.Delta);
    }
}

Ruby

## 流式读取Responses事件;从环境读取凭证,发送请求并读取响应
require "openai"

## 创建客户端;使用 OPENAI_API_KEY 环境变量,不在代码中写入真实密钥
openai = OpenAI::Client.new

stream = openai.responses.stream(
  model: "gpt-6-astra",
  input: [
    {
      role: "user",
      content: "Say 'double bubble bath' ten times fast."
    }
  ]
)

stream.each do |event|
  # 显示本次结果;实际文本与示例不必逐字相同
  puts(event)
end

流式输出适用于将模型生成过程推送给用户;Realtime API通过WebRTC或WebSocket等连接构建低延迟语音等交互应用。

构建智能体

使用Agents SDK,可以在服务端组织工具调用和智能体交接,让应用代表用户执行任务,包括计算机操作等。下面的语言分流示例创建西班牙语与英语智能体,再交由分流智能体根据用户语言选择接收者。

使用前安装相应Agents SDK:JavaScript项目使用 npm install @openai/agents,Python环境使用 python -m pip install openai-agents。普通 openai SDK与Agents SDK是不同的依赖。

JavaScript

// 按用户语言将任务交接给对应智能体
import { Agent, run } from "@openai/agents";

const spanishAgent = new Agent({
  name: "Spanish agent",
  instructions: "You only speak Spanish.",
});

const englishAgent = new Agent({
  name: "English agent",
  instructions: "You only speak English",
});

const triageAgent = new Agent({
  name: "Triage agent",
  instructions:
    "Handoff to the appropriate agent based on the language of the request.",
  handoffs: [spanishAgent, englishAgent],
});

const result = await run(triageAgent, "Hola, ¿cómo estás?");
// 显示本次结果;实际文本与示例不必逐字相同
console.log(result.finalOutput);

Python

## 按用户语言将任务交接给对应智能体
from agents import Agent, Runner
import asyncio

spanish_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())
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号