> ## Documentation Index
> Fetch the complete documentation index at: https://docs.inputapi.com/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript SDK

> 配置兼容地址，调用 Chat Completions 和 Responses。

使用官方 OpenAI TypeScript SDK。先设置[环境变量](/zh/guides/api-basics.md)，以下代码只在服务端或终端运行。

## 安装

需要 Node.js 22.18+ 或 Node.js 24 LTS，可直接运行 `.mts`。

```bash theme={null}
npm install openai@7.33.0
```

版本为本轮示例验证版本；生产项目按自己的依赖策略升级并复测。

## Chat Completions

保存为 `chat.mts`。

```typescript theme={null}
import OpenAI from 'openai';

const { API_BASE_URL, API_KEY, API_MODEL } = process.env;
if (!API_BASE_URL || !API_KEY || !API_MODEL) {
  throw new Error('Set API_BASE_URL, API_KEY, and API_MODEL first.');
}

const client = new OpenAI({
  baseURL: API_BASE_URL.replace(/\/+$/, ''),
  apiKey: API_KEY,
  timeout: 60_000,
  maxRetries: 0,
});

try {
  const result = await client.chat.completions.create({
    model: API_MODEL,
    messages: [{ role: 'user', content: 'Say hello in one short sentence.' }],
  });
  console.log(result.choices[0]?.message.content ?? '');
} catch (error) {
  console.error(error instanceof OpenAI.APIError && error.status
    ? `Request failed (HTTP ${error.status}). Check the request logs.`
    : 'Request failed. Check the API address and network.');
  process.exitCode = 1;
}
```

## Responses

保存为 `responses.mts`。 请先选择支持 Responses 的模型。

```typescript theme={null}
import OpenAI from 'openai';

const { API_BASE_URL, API_KEY, API_MODEL } = process.env;
if (!API_BASE_URL || !API_KEY || !API_MODEL) {
  throw new Error('Set API_BASE_URL, API_KEY, and API_MODEL first.');
}

const client = new OpenAI({
  baseURL: API_BASE_URL.replace(/\/+$/, ''),
  apiKey: API_KEY,
  timeout: 60_000,
  maxRetries: 0,
});

try {
  const result = await client.responses.create({
    model: API_MODEL,
    input: 'Say hello in one short sentence.',
  });
  if (result.status !== 'completed' || !result.output_text.trim()) {
    throw new Error('Response did not complete with usable text.');
  }
  for (const item of result.output) {
    if (item.type === 'reasoning') continue;
    if (item.type !== 'message' || item.status !== 'completed'
      || item.content.some((part) => part.type !== 'output_text')) {
      throw new Error('Response did not complete with usable text.');
    }
  }
  console.log(result.output_text);
} catch (error) {
  console.error(error instanceof OpenAI.APIError && error.status
    ? `Request failed (HTTP ${error.status}). Check the request logs.`
    : 'Response failed or did not complete. Check the request logs.');
  process.exitCode = 1;
}
```

## 运行与处理结果

```bash theme={null}
node chat.mts
node responses.mts
```

两个命令会分别发起真实请求，按需选择一个运行。示例把超时设为 60 秒，并关闭 SDK 自动重试，避免示例在失败时隐式重复请求。生产环境需设计自己的超时、重试和并发策略。

Chat Completions 的文本可能为空（例如工具调用）；Responses 示例只接受 `completed` 状态。`output_text` 是 SDK 汇总文本的属性，工具调用等非文本输出需要单独处理。

[流式输出](/zh/guides/streaming.md) · [错误处理](/zh/guides/errors.md)

参考：[OpenAI TypeScript SDK 官方说明](https://developers.openai.com/api/reference/typescript)。

Responses 纯文本示例会拒绝空文本、拒答、工具调用及未完成输出。进一步接入见[多轮对话](/zh/guides/conversations.md)、[工具调用](/zh/guides/tool-calling.md)和[结构化输出](/zh/guides/structured-output.md)中的 Responses 完整示例。

[Read in English](/en/guides/typescript.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.