跳转到内容
返回主站

TypeScript

TypeScript 提供完整的类型安全,适合对代码质量有较高要求的项目。通过官方 openai 包,你可以获得完整的类型定义和自动补全。

安装 SDK

Terminal window
npm install openai

需要 Node.js 18 或更高版本,TypeScript 4.6 或更高版本。

TypeScript 类型定义

OpenAI SDK 自带 TypeScript 类型定义,安装后即可直接使用,无需额外安装 @types/openai。SDK 提供了完整的类型推断,包括请求参数和响应结构。

配置 Client

通过环境变量配置:

Terminal window
export API_KEY="sk-your-api-key"
export BASE_URL="https://your-domain.com/v1"
export MODEL="gpt-4o"
import OpenAI from "openai";
const client: OpenAI = new OpenAI({
apiKey: process.env.API_KEY,
baseURL: process.env.BASE_URL,
});

Chat Completions 示例

import OpenAI from "openai";
import type { ChatCompletionMessageParam } from "openai/resources/chat/completions";
const client: OpenAI = new OpenAI({
apiKey: process.env.API_KEY,
baseURL: process.env.BASE_URL,
});
async function chat(): Promise<void> {
const messages: ChatCompletionMessageParam[] = [
{ role: "system", content: "你是一个有帮助的助手。" },
{ role: "user", content: "用一句话解释什么是 TypeScript。" },
];
const response = await client.chat.completions.create({
model: process.env.MODEL as string,
messages,
});
const content: string | null = response.choices[0].message.content;
console.log(content);
}
chat();

类型安全的响应处理

利用 SDK 提供的类型,可以安全地处理流式响应:

import OpenAI from "openai";
const client: OpenAI = new OpenAI({
apiKey: process.env.API_KEY,
baseURL: process.env.BASE_URL,
});
async function streamChat(): Promise<void> {
const stream = await client.chat.completions.create({
model: process.env.MODEL as string,
messages: [{ role: "user", content: "写一首关于冬天的诗。" }],
stream: true,
});
for await (const chunk of stream) {
const content: string | null = chunk.choices[0]?.delta?.content ?? null;
if (content !== null) {
process.stdout.write(content);
}
}
}
streamChat();

运行 TypeScript

使用 tsx 直接运行 TypeScript 文件:

Terminal window
npx tsx index.ts

或者先编译再运行:

Terminal window
npx tsc index.ts && node index.js