How to set up an api call with openai 4.0.0

hi so im new to this stuff and wanted to make an api request to chatgpt3.5 i think i have configured my route.tsx file correctly but i need help with my page.tsx thank you.

//route.ts
import OpenAI from 'openai';
import { auth } from "@clerk/nextjs";
import { NextResponse } from "next/server";


const openai = new OpenAI({
    apiKey: process.env.OPENAI_API_KEY // This is also the default, can be omitted
});

export async function POST(
    req: Request
) {
    try {
        const { userId } = auth();
        const body = await req.json();
        const { messages } = body;

        if (!userId) {
            return new NextResponse("Unauthorised", { status: 401 });
        }

        if (!openai) {
            return new NextResponse("OpenAI API Key not configured", { status: 500 });
        }

        if (!messages) {
            return new NextResponse("Messages are required", { status: 400 });
        }

        const response = await openai.chat.completions.create({
            model: "gpt-3.5-turbo",
            messages: [{"role": "user", "content": "Hello!"}],
        });

        console.log(response.choices[0].message);

    } catch (error) {
        console.log("[CONVERSATION_ERROR]", error)
        return new NextResponse("Internal error", { status: 500 });
    }
}

this is my route page which i updated to documentation.

    //page.tsx

    "use client";

    import axios from "axios";
    import * as z from "zod";

    import {zodResolver} from "@hookform/resolvers/zod";
    import { Heading } from "@/components/heading";
    import{MessageSquare} from "lucide-react";
    import { useForm } from "react-hook-form";
    import ChatCompletion from "openai";
    import { formSchema } from "./constants";
    import { Form, FormControl, FormField, FormItem } from "@/components/ui/form";
    import { Input } from "@/components/ui/input";
    import { Button } from "@/components/ui/button";
    import { useRouter } from "next/navigation";
    import { useState } from "react";
    import createCompletion from "openai";
    import OpenAI from 'openai';

    const ConversationPage = () => {
        const router = useRouter();
        const [messages, setMessages] = useState<createCompletion[]>([]);
      
        const form = useForm<z.infer<typeof formSchema>>({
          resolver: zodResolver(formSchema),
          defaultValues: {
            prompt: ""
          }
        });
      
        const isLoading = form.formState.isSubmitting;
        
        const onSubmit = async (values: z.infer<typeof formSchema>) => {
          try {
            const userMessage: createCompletion = { role: "user", content: values.prompt };
            const newMessages = [...messages, userMessage];
            
            const response = await axios.post('/api/conversation', { messages: newMessages });
            setMessages((current) => [...current, userMessage, response.data]);
            
            form.reset();
          } catch (error: any) {
            console.log(error);
            } 
            finally {
            router.refresh();
          }
        }
      
        return ( 
          <div>
            <Heading
              title="Conversation"
              description="Our most advanced conversation model."
              icon={MessageSquare}
              iconColor="text-violet-500"
              bgColor="bg-violet-500/10"
            />
            <div className="px-4 lg:px-8">
              <div>
                <Form {...form}>
                            <form onSubmit={form.handleSubmit(onSubmit)} className="rounded-lg border w-full p-4 px-3 md:px-6 focus-within:shadow-sm grid grid-cols-12 gap-2">
                                <FormField 
                                name="prompt"
                                render={({field})=>(
                                    <FormItem className="col-span-12 lg:col-span-10">
                                        <FormControl className="m-0 p-0">
                                    <Input
                                    className="border-0 outline-none focus-visible:ring-0 focus-visible:ring-transparent"
                                    disabled={isLoading}
                                    placeholder="How do I calculate the radius of a circle?"
                                    {...field}
                                    />
                                        </FormControl>
                                    </FormItem>
                                )}/>
                                <Button className="col-span-12 lg:col-span-2 w-full" disabled={isLoading}>
                                    Generate
                                </Button>
                            </form>

                        </Form>
                    </div>
                    <div className="space-y-4 mt-4">
                    <div className=" flex flex-col-reverse gap-y-4">
                            {messages.map((message)=> (
                                <div key={message.content}>
                                    {message.content}
                                    </div>
                            ))}
                    </div>
                    </div>
                </div>
            </div>
        );
    }
    
    export default ConversationPage;

this is the page i need help with, this code is in line with the previous api update and i dont know how to update it.

Are you getting an error or what are you looking for help with?

If you’re looking to upgrade the OpenAI library try their migration guide/automated tool: v3 to v4 Migration Guide · openai/openai-node · Discussion #217 · GitHub

GNU nano 6.2 curl
curl https://api.openai.com/v1/chat/completions
-H “Content-Type: application/json”
-H "Authorization: Bearer $(cat /etc/keys/key.txt) "
-d ‘{
“model”: “gpt-3.5-turbo”,
“messages”: [
{
“role”: “system”,
“content”: "Talkeetna is in alaska "
},
{
“role”: “assistant”,
“content”: "Where is talkeetna "
},
{
“role”: “assistant”,
“content”: "Talkeetna is a small town located in Alask>
}
],
“temperature”: 1,
“max_tokens”: 256,
“top_p”: 1,
“frequency_penalty”: 0,
“presence_penalty”: 0
}’

This works use it as your guide to write your curl in your code the model for GPT4 is “ gpt-4”

Type ‘{ role: string; content: string; }’ is not assignable to type ‘OpenAI’.
Object literal may only specify known properties, and ‘role’ does not exist in type ‘OpenAI’.ts(2322)
(property) role: string

getting this error over and over
:frowning:

Hi and welcome to the Developer Forum!

Can you please post the code that is causing this error?

1 Like
"use client";

import * as z from "zod";
import axios from "axios";
import { MessageSquare } from "lucide-react";
import { useForm } from "react-hook-form";
import { useState } from "react";
import { useRouter } from "next/navigation";
import createCompletion from "openai";
import OpenAI from 'openai';
import ChatCompletion from "openai";

import { BotAvatar } from "@/components/bot-avatar";
import { Heading } from "@/components/heading";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { zodResolver } from "@hookform/resolvers/zod";
import { Form, FormControl, FormField, FormItem } from "@/components/ui/form";
import { cn } from "@/lib/utils";
import { Loader } from "@/components/loader";
import { UserAvatar } from "@/components/user-avatar";
import { Empty } from "@/components/empty";

import { formSchema } from "./constants";

const ConversationPage = () => {
  const router = useRouter();
  const [messages, setMessages] = useState<createCompletion[]>([]);

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      prompt: ""
    }
  });

  const isLoading = form.formState.isSubmitting;
  
  const onSubmit = async (values: z.infer<typeof formSchema>) => {
    try {
      const userMessage: createCompletion = { role: "user", content: values.prompt };
      const newMessages = [...messages, userMessage];
      
      const response = await axios.post('/api/conversation', { messages: newMessages });
      setMessages((current) => [...current, userMessage, response.data]);
      
      form.reset();
    } catch (error: any) {
      console.log(error)
    } finally {
      router.refresh();
    }
  }
return ( .....written code
    <div className="flex flex-col-reverse gap-y-4">
            {messages.map((message) => (
              <div 
                key={message.content} 
                className={cn(
                  "p-8 w-full flex items-start gap-x-8 rounded-lg",
                  message.role === "user" ? "bg-white border border-black/10" : "bg-muted",
                )}
              >
                {message.role === "user" ? <UserAvatar /> : <BotAvatar />}
                <p className="text-sm">
                  {message.content}
                </p>
              </div>
            ))}
          </div>
)
}
 
export default ConversationPage;

Same as the code given above, but in this line,

const userMessage: createCompletion = { role: “user”, content: values.prompt };
the error is occuring that,
Type ‘{ role: string; content: string; }’ is not assignable to type ‘OpenAI’. Object literal may only specify known properties, and ‘role’ does not exist in type ‘OpenAI’.

I am having this exact same problem. Were you able to solve it?