OpenAI Function Calling

JS
S
JavaScript

Guide for implementing and utilizing OpenAI's function calling feature to enhance AI interactions with structured outputs and custom functionality.

1FRONTEND
2=======================
3<!DOCTYPE html>
4<html lang="en">
5  <head>
6    <meta charset="UTF-8" />
7    <title>Wall Street Bets Updates</title>
8    <style>
9      .question {
10        font-size: 0.9em;
11        color: #666;
12      }
13    </style>
14  </head>
15  <body>
16    <h1>OpenAI Assistant Functions</h1>
17    <form id="form">
18      <input type="text" id="input" placeholder="Enter Input" />
19      <button type="submit">Send</button>
20    </form>
21    <div id="chat"></div>
22    <script>
23      document.addEventListener("DOMContentLoaded", function () {
24        const form = document.getElementById("form");
25        const chatDiv = document.getElementById("chat");
26
27        form.addEventListener("submit", function (e) {
28          e.preventDefault();
29          const input = document.getElementById("input").value;
30          if (input) {
31            addQuestion(input);
32            sendMessage(input);
33            document.getElementById("input").value = "";
34          }
35        });
36
37        function addQuestion(location) {
38          const questionDiv = `<div class="question">${location}</div>`;
39          chatDiv.innerHTML += questionDiv;
40        }
41
42        function sendMessage(message) {
43          fetch("http://localhost:3000/chat", {
44            method: "POST",
45            headers: {
46              "Content-Type": "application/json",
47            },
48            body: JSON.stringify({ message }),
49          })
50            .then((response) => response.json())
51            .then((data) => {
52              console.log(data);
53              const responseDiv = `<div>${data.message}</div><hr/>`;
54              chatDiv.innerHTML += responseDiv;
55            })
56            .catch((error) => console.error("Error fetching weather:", error));
57        }
58      });
59    </script>
60  </body>
61</html>
62
63BACKEND
64=======================
65import fetch from "node-fetch";
66import express from "express";
67const app = express();
68const port = 3000;
69
70const apiKey = "<api-key>"
71
72app.use(express.json());
73app.use((_, res, next) => {
74  res.header("Access-Control-Allow-Origin", "*");
75  res.header(
76    "Access-Control-Allow-Headers",
77    "Origin, X-Requested-With, Content-Type, Accept"
78  );
79  next();
80});
81
82app.post("/chat", async (req, res) => {
83  const { message } = req.body;
84  const response = await processChatRequest(message);
85  res.json({ message: response });
86});
87
88app.listen(port, () =>
89  console.log(`Server running at http://localhost:${port}`)
90);
91
92const processChatRequest = async (location) => {
93    const messages = [
94      {
95        role: "user",
96        content: `${location}. Use the api call if needed, where needed list thinks in bulleted lists`,
97      },
98    ];
99    let response = await callChatCompletion(messages);
100  
101    if (
102      response.choices &&
103      response.choices[0].finish_reason === "function_call"
104    ) {
105      const functionCall = response.choices[0].message.function_call;
106      if (functionCall.name === "get_current_weather") {
107        const location = JSON.parse(functionCall.arguments).location;
108        const weather = `The weather in ${location} is ${Math.floor(
109          Math.random() * 101
110        )} degrees.`;
111        messages.push({
112          role: "function",
113          name: functionCall.name,
114          content: JSON.stringify(weather),
115        });
116        response = await callChatCompletion(messages);
117        return response.choices[0].message.content;
118      }
119    } else {
120      return response.choices[0].message.content;
121    }
122  };
123
124const callChatCompletion = async (messages) => {
125  const response = await fetch("https://api.openai.com/v1/chat/completions", {
126    method: "POST",
127    headers: {
128      Authorization: `Bearer ${apiKey}`,
129      "Content-Type": "application/json",
130    },
131    body: JSON.stringify({
132      model: "gpt-3.5-turbo",
133      messages: messages,
134      functions: [
135        {
136          name: "get_current_weather",
137          description: "Get the current weather in a given location.",
138          parameters: {
139            type: "object",
140            properties: {
141              location: {
142                type: "string",
143                description: "The city and state, e.g. San Francisco, CA",
144              },
145            },
146            required: ["location"],
147          },
148        },
149      ],
150    }),
151  });
152  return response.json();
153};
154

Created on 5/22/2024