Skip to content

Commit a62865e

Browse files
committed
updating readme based on feedback.
1 parent 07f3c5c commit a62865e

File tree

2 files changed

+129
-37
lines changed

2 files changed

+129
-37
lines changed

README.md

Lines changed: 126 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,22 @@
1-
# Large Language Models with MATLAB®
1+
# Large Language Models (LLMs) with MATLAB®
22

33
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.
44

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.
66

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
820
1. Clone the repository to your local machine.
921

1022
```bash
@@ -21,29 +33,32 @@ The functionality shown here simply serves as an interface to the ChatGPT API. Y
2133

2234
4. Set up your OpenAI API key. You can either:
2335
- 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):
2537
```matlab
2638
setenv("OPENAI_API_KEY","your key here")
2739
```
40+
or
41+
```matlab
42+
loadenv(filename)
43+
```
2844

29-
### MathWorks Products (https://www.mathworks.com)
3045

31-
Requires MATLAB release R2023a or newer
32-
- Text Analytics Toolbox™
46+
### MathWorks Products (https://www.mathworks.com)
3347

48+
- Requires MATLAB release R2023a or newer.
3449

3550
### 3rd Party Products:
36-
3p:
51+
3752
- An active OpenAI API subscription and API key.
3853

3954

40-
## Getting Started
55+
## Getting Started
4156

4257
To get started, you can either create an `openAIChat` object and use its methods or use it in a more complex setup, as needed.
4358

4459
### Simple call without preserving chat history
4560

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.
4762

4863
Here's a simple example of how to use the `openAIChat` for sentiment analysis:
4964
@@ -64,7 +79,7 @@ systemPrompt = "You are a sentiment analyser. You will look at a sentence and ou
6479
chat = openAIChat(systemPrompt);
6580
6681
% 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")
6883
% Should output "positive"
6984
```
7085
@@ -87,7 +102,7 @@ chat = openAIChat("You are a helpful AI assistant.");
87102
Add a user message to the history and pass it to `generate`
88103
89104
```matlab
90-
history = addUserMessage(history, "What is an eigenvalue?");
105+
history = addUserMessage(history,"What is an eigenvalue?");
91106
[text, response] = generate(chat, history)
92107
```
93108
@@ -98,60 +113,135 @@ history = addResponseMessage(history, response);
98113
99114
You can keep interacting with the API and since we are saving the history, it will know about previous interactions.
100115
```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);
103118
% Will generate code to compute the eigenvalue
104119
```
105120
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 function names, 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 function as follows:
107127

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:
109128

110129
```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);
112133
```
113134

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:
115136

116137
```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);
119140
```
120141

121-
Then you can pass the functions to the chat API as follows:
142+
The variable `response` should contain a request for a function call.
143+
```bash
144+
>> response
122145
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↵}'
125162
```
126163

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 function message to the history:
128165

129166
```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
168+
args = jsondecode(response.function_call.arguments);
169+
result = sind(args.x);
170+
messages = addFunctionMessage(messages,"sind","x="+result);
171+
[text, response] = generate(chat, messages);
172+
```
132173

133-
[text, response] = generate(chat, history);
174+
The model then will use the function result 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."
134182
```
135183

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
137185

138-
Once you have the result of the requested function, you can add the value to the history as a function message:
186+
Another useful application for defining functions is extract structured information from some text. You can just pass a function with 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:
139187

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.";
140195
```
141-
history = addFunctionMessage(history, "editDistance", "8");
196+
197+
If you want to extract information from this text, you can define a function as 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.");
142203
```
143204

144-
Then the model can give a more precise answer based on the result of the function:
205+
Note that this function does 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);
145213
```
146-
[text, response] = generate(chat, history);
214+
215+
The model should return the extracted information as a function call:
216+
```shell
217+
>> response
218+
219+
response =
220+
221+
struct with fields:
222+
223+
role: 'assistant'
224+
content: []
225+
function_call: [1×1 struct]
226+
227+
>> response.function_call
228+
229+
ans =
230+
231+
struct with fields:
232+
233+
name: 'extractPatientData'
234+
arguments: '{↵ "patientName": "John Doe",↵ "patientAge": 45,↵ "patientSymptoms": "persistent cough, fatigue"↵}'
147235
```
148236

237+
You can extract the arguments and write the data to a table, for example.
238+
149239
## 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/).
151241

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.
155245

156246
## License
157247

examples/ExampleChatBot.m

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,16 @@
22
% This script orchestrates a chat interaction with the OpenAI Chat Completions API, taking user
33
% inputs, maintaining a word count, and ensuring the chat remains within a
44
% predefined word limit.
5+
%
6+
% Running this example will start an interactive ChatBot in your terminal and it can be ended
7+
% by pressing Ctrl+C or typing "end".
58

69
% Set the maximum allowable number of words per chat session
710
wordLimit = 2000;
811

912
% Define the keyword that, when entered by the user, ends the chat session
1013
stopWord = "end";
1114

12-
1315
modelName = "gpt-3.5-turbo";
1416
chat = openAIChat("You are a helpful assistant.", ModelName=modelName);
1517

0 commit comments

Comments
 (0)