章節導覽
TypeScript / Node.js
TypeScript / Node.js
安裝
1
npm install openai基本用法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.bazaarlink.ai/v1",
apiKey: process.env.BAZAARLINK_API_KEY,
});
async function chat(message: string): Promise<string> {
const response = await client.chat.completions.create({
model: "openai/gpt-4o",
messages: [{ role: "user", content: message }],
});
return response.choices[0].message.content ?? "";
}串流
1
2
3
4
5
6
7
8
9
const stream = await client.chat.completions.create({
model: "openai/gpt-4o",
messages: [{ role: "user", content: "Tell me a story" }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}