Features > ChatGPT Integration
ChatGPT is a powerful AI model that you can use inside your NextStarter app. It's a great way to add AI-powered chatbots to your app. 🤖
First things first, add your OPENAI_API_KEY to your .env.local file.
Then, you can use the ChatGPT API In two ways:
1. ChatGPT Assistant
Inside your NextStarter app, you can use the ChatGPT API directly by making a POST request to the API endpoint. Go into the /libs/gpt.ts and check out the sendChatGPTCompletion function.
Pass this function the messages you want to send to the ChatGPT and it will return the response. It has a custom retry logic built-in, so you don't have to worry about handling retries☀️
1
2 ....
3 const body = JSON.stringify({
4 model: "gpt-4", // gpt-4, gpt-3.5-turbo, etc
5 messages, // array of message objects with role and content. e.g. [{role: "user", content: "What's the weather in San Francisco?"}]
6 max_tokens: max, // max tokens to generate in the response
7 temperature: temp, // temperature of the response, higher is more random
8 user: userId, // user id
9 });
10
11 const options = {
12 headers: {
13 Authorization: `Bearer ${process.env.OPENAI_API_KEY}`, // place in your API key here or use environment variables
14 "Content-Type": "application/json",
15 },
16 };
17
18 try {
19 // Custom retry delay
20 axiosRetry(axios, {
21 retryDelay: (retryCount) => {
22 return retryCount * 1;
23 },
24 retries: 15,
25 });
26
27 const res = await axios.post(url, body, options);
28
29 const answer = res.data.choices[0].message.content;
30 const usage = res?.data?.usage;
31
32 console.log(">>> " + answer);
33 console.log(
34 "TOKENS USED: " +
35 usage?.total_tokens +
36 " (prompt: " +
37 usage?.prompt_tokens +
38 " / response: " +
39 usage?.completion_tokens +
40 ")"
41 );
42 console.log("
43");
44
45 return answer;
46 } catch (e) {
47 console.error("GPT Error: " + e?.response?.status, e?.response?.data);
48 return null;
49 }
50};
51
52
Here's an example of a messages array for sendChatGPTCompletion function.
1const messages =
2 [
3 {
4 role: "user",
5 content: "What's the weather in San Francisco?",
6 },
7 {
8 role: "assistant",
9 content: "I can help with that. Let me check...",
10 }
11 ];
12
2. ChatGPT for Function Calling
You can also use ChatGPT completion API to decide which function to call based on the user's input. This is useful when you want to create a chatbot that can call different functions based on the user's input.
Inside /libs/gpt.ts , simply use sendChatGPTFunctions by passing in the user messages and available functions you want to choose from. ChatGPT will automatically decide which function to call based on the user's input, along with the parameters.
Here's an example of a tools array to use sendChatGPTFunctions function to call a function based on the user's input.
1
2
3 const tools = [ // List of available functions, called tools.
4 {
5 "type": "function",
6 "function": {
7 "name": "get_current_weather",
8 "description": "Get the current weather in a given location",
9 "parameters": {
10 "type": "object",
11 "properties": {
12 "location": {
13 "type": "string",
14 "description": "The city and state, e.g. San Francisco, CA",
15 },
16 "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
17 },
18 "required": ["location"],
19 },
20 }
21 }
22 ];
23
24 const body = JSON.stringify({
25 model: "gpt-3.5-turbo", // gpt-4, gpt-3.5-turbo, etc
26 messages, // array of message objects with role and content. e.g. [{role: "user", content: "What's the weather in San Francisco?"}]
27 max_tokens: max, // max tokens to generate in the response
28 temperature: temp, // temperature of the response, higher is more random
29 tools: tools, // array of available function objects
30 tool_choice: "auto", // let ChatGPT decide when and which function to call
31 });
32
33 const options = {
34 headers: {
35 Authorization: `Bearer ${process.env.OPENAI_API_KEY}`, // place in your API key here or use environment variables
36 "Content-Type": "application/json",
37 },
38 };
39
40 try {
41 // Custom retry delay
42 axiosRetry(axios, {
43 retryDelay: (retryCount) => {
44 return retryCount * 1;
45 },
46 retries: 15,
47 });
48
49 const res = await axios.post(url, body, options);
50
51 const toolCalls = res.data.choices[0].message.tool_calls;
52 const usage = res?.data?.usage;
53
54 console.log(
55 "TOKENS USED: " +
56 usage?.total_tokens +
57 " (prompt: " +
58 usage?.prompt_tokens +
59 " / response: " +
60 usage?.completion_tokens +
61 ")"
62 );
63
64 return toolCalls;
65 } catch (e) {
66 console.error("GPT Error: " + e?.response?.status, e?.response?.data);
67 return null;
68 }
69};
70
71