AI
API
JavaScript
Tutorial
Full Stack
Ask anything about this article
Hi! I've read this article.
What would you like to know?
@farhan
The OpenAI API is the gateway to the most powerful AI models available. Whether you're building a chatbot, a code assistant, or an image analyzer, this guide covers everything you need to get started.
bashnpm install openai
typescriptimport OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
typescriptconst response = await openai.chat.completions.create({
model: "gpt-4o",
messages: [
{ role: "system", content: "You are a helpful coding assistant." },
{ role: "user", content: "Explain async/await in JavaScript" }
],
temperature: 0.7,
max_tokens: 1000,
});
console.log(response.choices[0].message.content);
This is the most powerful feature for building AI agents:
typescriptconst tools = [
{
type: "function",
function: {
name: "get_weather",
description: "Get the current weather for a city",
parameters: {
type: "object",
properties: {
city: { type: "string", description: "City name" },
units: { type: "string", enum: ["celsius", "fahrenheit"] }
},
required: ["city"]
}
}
}
];
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "What's the weather in Tokyo?" }],
tools: tools,
tool_choice: "auto",
});
// The model will call get_weather with { city: "Tokyo" }
const toolCall = response.choices[0].message.tool_calls[0];
console.log(JSON.parse(toolCall.function.arguments));
typescriptconst response = await openai.chat.completions.create({
model: "gpt-4o",
messages: [
{
role: "user",
content: [
{ type: "text", text: "What's in this image?" },
{ type: "image_url", image_url: { url: "https://example.com/photo.jpg" } }
]
}
],
});
typescriptconst response = await openai.chat.completions.create({
model: "gpt-4o",
messages: [
{ role: "user", content: "List 3 programming languages with their use cases" }
],
response_format: { type: "json_object" },
});
const data = JSON.parse(response.choices[0].message.content);
typescriptconst stream = await openai.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "Write a poem about coding" }],
stream: true,
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || '';
process.stdout.write(content);
}
Combine these building blocks to create a full application:
The OpenAI API makes it remarkably easy to add intelligence to any application.