Create an AI-powered chatbot using JavaScript and Node.js with any LLM (Claude, GPT, Gemini) through a single API.
npm install openai readline
import OpenAI from "openai"; import * as readline from "readline"; const client = new OpenAI({ apiKey: "YOUR_API_KEY", baseURL: "https://api.acedata.cloud/v1", }); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); const messages = []; async function chat() { console.log("Chatbot ready. Type 'quit' to exit.\n"); const askQuestion = () => { rl.question("You: ", async (input) => { if (input.toLowerCase() === "quit") { rl.close(); return; } messages.push({ role: "user", content: input }); const stream = await client.chat.completions.create({ model: "gpt-4o", messages, stream: true, }); process.stdout.write("AI: "); let fullResponse = ""; for await (const chunk of stream) { const content = chunk.choices[0]?.delta?.content || ""; process.stdout.write(content); fullResponse += content; } console.log(); messages.push({ role: "assistant", content: fullResponse }); askQuestion(); }); }; askQuestion(); } chat();
// Just change the model string — same code, same API const stream = await client.chat.completions.create({ model: "claude-sonnet-4-20250514", // or "gpt-4o", "gemini-2.5-flash" messages, stream: true, });
此页面对您有帮助吗?