Back to journal
AI Solutions12 min readJanuary 22, 2024

AI Integration Guide: Connecting OpenAI API to Your App

Step-by-step tutorial on integrating GPT models into your web applications for intelligent features.

#AI#OpenAI#API

Integrating AI into your applications opens up possibilities for intelligent features. This guide walks you through connecting OpenAI's GPT models to your Next.js or Node.js application.

Prerequisites

Before starting, ensure you have:

  • An OpenAI API key (get one at platform.openai.com)
  • Node.js 18+ installed
  • A Next.js or Node.js project

Setting Up the Client

First, install the OpenAI SDK:

npm install openai

Then create an API route in Next.js:

// app/api/chat/route.ts
import { OpenAI } from 'openai';
import { NextResponse } from 'next/server';

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

export async function POST(request: Request) {
  const { messages } = await request.json();

  const completion = await openai.chat.completions.create({
    model: 'gpt-4-turbo-preview',
    messages: [
      { role: 'system', content: 'You are a helpful assistant.' },
      ...messages,
    ],
    temperature: 0.7,
    max_tokens: 1000,
  });

  return NextResponse.json({
    message: completion.choices[0].message,
  });
}

Building the Frontend

Create a chat interface:

'use client';
import { useState } from 'react';

export default function Chat() {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');

  const sendMessage = async () => {
    const newMessages = [...messages, { role: 'user', content: input }];
    setMessages(newMessages);

    const response = await fetch('/api/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ messages: newMessages }),
    });

    const data = await response.json();
    setMessages([...newMessages, data.message]);
    setInput('');
  };

  return (
    <div>
      {messages.map((m, i) => (
        <div key={i}>{m.content}</div>
      ))}
      <input value={input} onChange={(e) => setInput(e.target.value)} />
      <button onClick={sendMessage}>Send</button>
    </div>
  );
}

Handling API Keys Securely

Never expose your API key in client-side code. Use environment variables:

OPENAI_API_KEY=sk-your-key-here

Cost Optimization

  • Use gpt-3.5-turbo for simpler tasks
  • Implement caching for repeated queries
  • Set reasonable max_tokens limits
  • Monitor usage in OpenAI dashboard

Conclusion

AI integration is straightforward with the OpenAI SDK. Start with simple implementations and iterate based on your use case.

If the note connects to your work

If the project needs a clearer technical read, send a brief.

Send a brief