赞
踩
(2023年11月7日)
https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo
训练数据日期升级到2023年四月
上线文增加到128k
调用一次chatgpt接口,可以得到多次函数调用
- import OpenAI from "openai";
- const openai = new OpenAI();
-
-
- // Example dummy function hard coded to return the same weather
- // In production, this could be your backend API or an external API
- function getCurrentWeather(location, unit = "fahrenheit") {
- if (location.toLowerCase().includes("tokyo")) {
- return JSON.stringify({ location, temperature: "10", unit: "celsius" });
- } else if (location.toLowerCase().includes("san francisco")) {
- return JSON.stringify({ location, temperature: "72", unit: "fahrenheit" });
- } else {
- return JSON.stringify({ location, temperature: "22", unit: "celsius" });
- }
- }
-
-
- async function runConversation() {
- // Step 1: send the conversation and available functions to the model
- const messages = [
- { role: "user", content: "What's the weather like in San Francisco, Tokyo, and Paris?" },
- ];
- const tools = [
- {
- type: "function",
- function: {
- name: "get_current_weather",
- description: "Get the current weather in a given location",
- parameters: {
- type: "object",
- properties: {
- location: {
- type: "string",
- description: "The city and state, e.g. San Francisco, CA",
- },
- unit: { type: "string", enum: ["celsius", "fahrenheit"] },
- },
- required: ["location"],
- },
- },
- },
- ];
-
-
- const response = await openai.chat.completions.create({
- model: "gpt-3.5-turbo-1106",
- messages: messages,
- tools: tools,
- tool_choice: "auto", // auto is default, but we'll be explicit
- });
- const responseMessage = response.choices[0].message;
-
- // Step 2: check if the model wanted to call a function
- const toolCalls = responseMessage.tool_calls;
- if (responseMessage.tool_calls) {
- // Step 3: call the function
- // Note: the JSON response may not always be valid; be sure to handle errors
- const availableFunctions = {
- get_current_weather: getCurrentWeather,
- }; // only one function in this example, but you can have multiple
- messages.push(responseMessage); // extend conversation with assistant's reply
- for (const toolCall of toolCalls) {
- const functionName = toolCall.function.name;
- const functionToCall = availableFunctions[functionName];
- const functionArgs = JSON.parse(toolCall.function.arguments);
- const functionResponse = functionToCall(
- functionArgs.location,
- functionArgs.unit
- );
- messages.push({
- tool_call_id: toolCall.id,
- role: "tool",
- name: functionName,
- content: functionResponse,
- }); // extend conversation with function response
- }
- const secondResponse = await openai.chat.completions.create({
- model: "gpt-3.5-turbo-1106",
- messages: messages,
- }); // get a new response from the model where it can see the function response
- return secondResponse.choices;
- }
- }
-
-
- runConversation().then(console.log).catch(console.error);
一次查询两个城市的天气
一次查询两个人的新闻
参考链接:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。