You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This repository contains example code to demonstrate how to connect MATLAB to the OpenAI™ Chat Completions API (which powers ChatGPT™). This allows you to leverage the natural language processing capabilities of GPT models directly within your MATLAB environment.
4
4
5
-
The functionality shown here simply serves as an interface to the ChatGPT API. You should be familiar with the limitations and risks associated with using this technology as well as with [OpenAI terms and policies](https://openai.com/policies). You are responsible for any fees OpenAI may charge for the use of their API.
5
+
The functionality shown here serves as an interface to the ChatGPT API. To start using the ChatGPT API, you first need to obtain the OpenAI API keys. You are responsible for any fees OpenAI may charge for the use of their API.
6
6
7
-
## Setup
7
+
The current LLMs supported are:
8
+
- gpt-3.5-turbo
9
+
- gpt-3.5-turbo-0613
10
+
- gpt-3.5-turbo-16k
11
+
- gpt-3.5-turbo-16k-0613
12
+
- gpt-4
13
+
- gpt-4-0613
14
+
- gpt-4-32k
15
+
- gpt-4-32k-0613
16
+
17
+
For details on the specification of each model, check the official [OpenAI documentation](https://platform.openai.com/docs/models).
18
+
19
+
## Setup
8
20
1. Clone the repository to your local machine.
9
21
10
22
```bash
@@ -21,29 +33,32 @@ The functionality shown here simply serves as an interface to the ChatGPT API. Y
21
33
22
34
4. Set up your OpenAI API key. You can either:
23
35
- Pass it directly to the `openAIChat` class, using the nvp `ApiKey`
24
-
- Or set it as an environment variable.
36
+
- Or set it as an environment variable using [`setenv`](https://www.mathworks.com/help/matlab/ref/setenv.html) or [`loadenv`](https://www.mathworks.com/help/matlab/ref/loadenv.html):
To get started, you can either create an `openAIChat` object and use its methods or use it in a more complex setup, as needed.
43
58
44
59
### Simple call without preserving chat history
45
60
46
-
In some situations, you will want to use GPT models without preserving chat history. For example, when you want to perform independent queries in a programmatic way.
61
+
In some situations, you will want to use GPT models without preserving chat history. For example, when you want to perform independent queries in a programmatic way.
47
62
48
63
Here's a simple example of how to use the `openAIChat` for sentiment analysis:
49
64
@@ -64,7 +79,7 @@ systemPrompt = "You are a sentiment analyser. You will look at a sentence and ou
64
79
chat = openAIChat(systemPrompt);
65
80
66
81
% Generate a response, passing a new sentence for classification
67
-
text = generate(chat,"The team is feeling very motivated")
82
+
text = generate(chat,"The team is feeling very motivated")
68
83
% Should output "positive"
69
84
```
70
85
@@ -87,7 +102,7 @@ chat = openAIChat("You are a helpful AI assistant.");
87
102
Add a user message to the history and pass it to `generate`
88
103
89
104
```matlab
90
-
history = addUserMessage(history,"What is an eigenvalue?");
105
+
history = addUserMessage(history,"What is an eigenvalue?");
91
106
[text, response] = generate(chat, history)
92
107
```
93
108
@@ -98,60 +113,135 @@ history = addResponseMessage(history, response);
98
113
99
114
You can keep interacting with the API and since we are saving the history, it will know about previous interactions.
100
115
```matlab
101
-
history = addUserMessage(history,"Generate MATLAB code that computes that");
102
-
[text, response] = generate(chat,history);
116
+
history = addUserMessage(history,"Generate MATLAB code that computes that");
117
+
[text, response] = generate(chat,history);
103
118
% Will generate code to compute the eigenvalue
104
119
```
105
120
106
-
### Passing functions to API
121
+
### Calling MATLAB functions with the API
122
+
123
+
The optional parameter `functions` can be used to provide function specifications to the API. The purpose of this is to enable models to generate function arguments which adhere to the provided specifications.
124
+
Note that the API is not able to directly call any function, so you should call the function and pass the values to the API directly. This process can be automated as shown in [ExampleFunctionCalling.m](/examples/ExampleFunctionCalling.m), but it's important to consider that ChatGPT can hallucinate functionnames, so avoid executing any arbitrary generated functions and only allow the execution of functions that you have defined.
125
+
126
+
For example, if you want to use the API for mathematical operations such as `sind`, instead of letting the model generate the result and risk running into hallucinations, you can give the model direct access to the functionas follows:
107
127
108
-
You can define functions that the API is allowed to request calls using `openAIFunction`. For example, to define the `editDistance` function for string values, you can do as follows:
109
128
110
129
```matlab
111
-
f = openAIFunction("editDistance", "Find edit distance between two strings or documents");
130
+
f = openAIFunction("sind","Sine of argument in degrees");
131
+
f = addParameter(f,"x",type="number",description="Angle in degrees.");
132
+
chat = openAIChat("You are a helpful assistant.",Functions=f);
112
133
```
113
134
114
-
You also have to define what parameters the function can take, providing details on the properties of each parameter. The properties can be `type`, `description` or `enum`.
135
+
When the model identifies that it could use the defined functions to answer a query, it will return a `function_call` request, instead of directly generating the response:
115
136
116
137
```matlab
117
-
f = addParameter(f, "str1", type="string", description="Source string.");
118
-
f = addParameter(f, "str2", type="string", description="Target string.");
138
+
messages = addUserMessage(messages, "What is the sine of 30?");
139
+
[text, response] = generate(chat, messages);
119
140
```
120
141
121
-
Then you can pass the functions to the chat API as follows:
142
+
The variable `response` should contain a request for a functioncall.
143
+
```bash
144
+
>> response
122
145
123
-
```matlab
124
-
chat = openAIChat("You are a helpful assistant", Functions=f);
146
+
response =
147
+
148
+
struct with fields:
149
+
150
+
role: 'assistant'
151
+
content: []
152
+
function_call: [1×1 struct]
153
+
154
+
>> response.function_call
155
+
156
+
ans =
157
+
158
+
struct with fields:
159
+
160
+
name: 'sind'
161
+
arguments: '{↵ "x": 30↵}'
125
162
```
126
163
127
-
The model will automatically determine if the function should be called based on the user input:
164
+
You can then call the function`sind` with the specified argument and return the value to the API add a functionmessage to the history:
128
165
129
166
```matlab
130
-
history = openAIMessages;
131
-
history = addUserMessage(history, "What is the edit distance between MathWorks and MATLAB?");
167
+
% Arguments are returned as a json, so you need to decode it first
The model then will use the functionresult to generate a more precise response:
175
+
176
+
```shell
177
+
>> text
178
+
179
+
text =
180
+
181
+
"The sine of 30 degrees is approximately 0.5."
134
182
```
135
183
136
-
If the model sends back an empty `text` and a response containing a field `function_call`, it means it's requesting that you call a function. The model is not able to automatically execute a function.
184
+
### Extracting structured information with the API
137
185
138
-
Once you have the result of the requested function, you can add the value to the history as a functionmessage:
186
+
Another useful application for defining functions is extract structured information from some text. You can just pass a functionwith the output format that you would like the model to output and the information you want to extract. For example, consider the following piece of text:
139
187
188
+
```matlab
189
+
patientReport = "Patient John Doe, a 45-year-old male, presented " + ...
190
+
"with a two-week history of persistent cough and fatigue. " + ...
191
+
"Chest X-ray revealed an abnormal shadow in the right lung." + ...
192
+
" A CT scan confirmed a 3cm mass in the right upper lobe," + ...
193
+
" suggestive of lung cancer. The patient has been referred " + ...
194
+
"for biopsy to confirm the diagnosis.";
140
195
```
141
-
history = addFunctionMessage(history, "editDistance", "8");
196
+
197
+
If you want to extract information from this text, you can define a functionas follows:
198
+
```matlab
199
+
f = openAIFunction("extractPatientData","Extracts data about a patient from a record");
200
+
f = addParameter(f,"patientName",type="string",description="Name of the patient");
201
+
f = addParameter(f,"patientAge",type="number",description="Age of the patient");
202
+
f = addParameter(f,"patientSymptoms",type="string",description="Symptoms that the patient is having.");
142
203
```
143
204
144
-
Then the model can give a more precise answer based on the result of the function:
205
+
Note that this functiondoes not need to exist, since it will only be used to extract the Name, Age and Symptoms of the patient and it does not need to be called:
206
+
207
+
```matlab
208
+
chat = openAIChat("You are helpful assistant that reads patient records and extracts information", ...
209
+
Functions=f);
210
+
messages = openAIMessages;
211
+
messages = addUserMessage(messages,"Extract the information from the report:" + newline + patientReport);
212
+
[text, response] = generate(chat, messages);
145
213
```
146
-
[text, response] = generate(chat, history);
214
+
215
+
The model should return the extracted information as a functioncall:
You can extract the arguments and write the data to a table, for example.
238
+
149
239
## Examples
150
-
To learn how to use this in your workflows, see [Examples](/examples/).
240
+
To learn how to use this in your workflows, see [Examples](/examples/).
151
241
152
-
- [ExampleSummarization.m](/examples/ExampleSummarization.m): Learn to create concise summaries of long texts with ChatGPT.
153
-
- [ExampleChatBot.m](/examples/ExampleChatBot.mlx): Build a conversational chatbot capable of handling various dialogue scenarios using ChatGPT.
154
-
- [ExampleFunctionCalling.m](/examples/ExampleFunctionCalling.m): Learn how to create agents capable of executing MATLAB functions.
242
+
- [ExampleSummarization.m](/examples/ExampleSummarization.m): Learn to create concise summaries of long texts with ChatGPT. (Requires Text Analytics Toolbox™)
243
+
- [ExampleChatBot.m](/examples/ExampleChatBot.m): Build a conversational chatbot capable of handling various dialogue scenarios using ChatGPT. (Requires Text Analytics Toolbox)
244
+
- [ExampleFunctionCalling.m](/examples/ExampleFunctionCalling.m): Learn how to create agents capable of executing MATLAB functions.
0 commit comments