使用 OpenAI 的 function calling,讓資料整合更靈活

使用 OpenAI 的 function calling

最近 OpenAI 推出了一個名為「function calling」的新功能,這個功能可以讓你在使用 OpenAI API 的代碼中執行自行定義的 function。透過這個功能,你可以更加彈性地與 OpenAI 模型進行互動和整合。

步驟

  1. 安裝 TypeScript 和 OpenAI API 套件。
1
2
yarn add openai
yarn add -D dotenv typescript
  1. 建立 .env,並將 API key 加進去
1
2
// .env
OPENAI_TOKEN=xxx
  1. 定義想要使用的 function 的描述和參數。
  2. 根據 OpenAI API 的回應判斷是否需要使用自定義的 function。
  3. 將自定義的 function 的結果重新傳遞給 OpenAI 進行處理,並獲得整合的回應。

程式碼範例

以下是一個使用 TypeScript 的程式碼範例,用於查詢特定位置的當前天氣:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import 'dotenv/config';
import {Configuration, OpenAIApi} from 'openai';

const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY
});
const openAiApi = new OpenAIApi(configuration);

function getCurrentWeather(location: string) {
return {
"location": location,
"temperature": "72",
"forecast": ["sunny", "windy"],
}
}

async function main() {
const completion = await openAiApi.createChatCompletion({
model: 'gpt-3.5-turbo-0613',
messages: [
{
role: 'system',
content: 'You are a helpful a assistant.',
},
{
role: 'user',
content: 'what is the current weather in Taipei?',
}
],
function_call: 'auto',
// Step 1: 傳送對話與可使用的 function 給 OpenAI
// 自己定義要執行的 function,OpenAI 可以根據問題自行決定呼叫的 function
functions: [{
name: 'getCurrentWeather',
description: 'Get the current weather in a given location',
parameters: {
type: 'object',
properties: {
location: {
type: 'string',
description: 'The location, e.g. "Taipei"'
}
},
required: ['location']
}
}],
});

const completionResponse = completion.data.choices[0].message!;

console.log(completionResponse);
/**
*
* {
* role: 'assistant',
* content: null,
* function_call: { name: 'getCurrentWeather', arguments: '{\n"location": "Taipei"\n}' }
* }
*
*/

// Step 2: 檢查 OpenAI 是否想要呼叫自定義的 function
// 如果 content 為 null,則表示 OpenAI 認爲需要執行自定義的 function 內容,會列出可執行的 function name,可以根據需求進行處理

let functionCallResult = '';
if (!completionResponse.content && completionResponse.function_call) {
if (completionResponse.function_call.name === 'getCurrentWeather') {
const args = JSON.parse(completionResponse.function_call.arguments!);
// Step 3: 執行自定義的 function
functionCallResult = JSON.stringify(getCurrentWeather(args.location));
}

// Step 4: 將 function 執行結果回傳給 OpenAI,讓 OpenAI 繼續處理

const completionResponse2 = await openAiApi.createChatCompletion({
model: 'gpt-3.5-turbo-0613',
messages: [
{
role: 'system',
content: 'You are a helpful a assistant.',
},
{
role: 'user',
content: 'what is the current weather in Taipei?',
},
{
role: 'function',
name: 'getCurrentWeather',
content: functionCallResult
}
]
});

// Step 5: 取得 OpenAI 最後回傳的結果,會結合 function 執行的結果進行處理
console.log('completion2');
console.log(completionResponse2.data.choices[0].message);
}

}

main();

結論

使用 OpenAI API 的新功能「function calling」,能夠在 OpenAI 模型中執行自定義的 function,使用上就不再受限於資料的時間與網路連線的問題,並且可以將結果與 OpenAI API 進行互動。這個功能不僅增加了彈性,還能夠根據需求取得最新的資料進行查詢。

Reference

https://platform.openai.com/docs/guides/gpt/function-calling