typescript openai gtp-4o 示例

卓能文發表於2024-06-21
import OpenAI from "openai";

const openai = new OpenAI();

async function main() {
	const stream = await openai.chat.completions.create({
		model: "gpt-4o",
		messages: [
			{
				role: "user",
				content: `your question`,
			},
		],
		stream: true,
	});
	for await (const chunk of stream) {
		process.stdout.write(chunk.choices[0]?.delta?.content || "");
	}
}

main();

直接執行:

bun test.ts

程式碼會自動從.env讀取OPENAI_API_KEYOPENAI_BASE_URL等值,執行之前請設定好。

相關文章