Skip to content

Commit b3de243

Browse files
committed
Update README, examples
1 parent 27aa59e commit b3de243

File tree

3 files changed

+89
-27
lines changed

3 files changed

+89
-27
lines changed

README.md

Lines changed: 89 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
# Large Language Models (LLMs) with MATLAB® [![Open in MATLAB Online](https://www.mathworks.com/images/responsive/global/open-in-matlab-online.svg)](https://matlab.mathworks.com/open/github/v1?repo=matlab-deep-learning/llms-with-matlab)
22

3-
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.
3+
This repository contains example code to demonstrate how to connect MATLAB to the OpenAI™ Chat Completions API (which powers ChatGPT™) as well as OpenAI Images API (which powers DALL-E™). This allows you to leverage the natural language processing capabilities of large language models directly within your MATLAB environment.
44

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. You should be familiar with the limitations and risks associated with using this technology, and you agree that you shall be solely responsible for full compliance with any terms that may apply to your use of the OpenAI Chat Completions API.
5+
The functionality shown here serves as an interface to the ChatGPT and DALL-E APIs. To start using the OpenAI APIs, you first need to obtain the OpenAI API keys. You are responsible for any fees OpenAI may charge for the use of their APIs. You should be familiar with the limitations and risks associated with using this technology, and you agree that you shall be solely responsible for full compliance with any terms that may apply to your use of the OpenAI APIs.
66

77
Some of the current LLMs supported are:
8-
- gpt-3.5-turbo
9-
- gpt-4
8+
- gpt-3.5-turbo, gpt-3.5-turbo-1106
9+
- gpt-4, gpt-4-1106-preview
10+
- gpt-4-vision-preview (a.k.a. GPT-4 Turbo with Vision)
11+
- dall-e-2, dall-e-3
1012

1113
For details on the specification of each model, check the official [OpenAI documentation](https://platform.openai.com/docs/models).
1214

@@ -51,13 +53,13 @@ If you would like to use it with MATLAB Desktop, proceed with the following step
5153
- An active OpenAI API subscription and API key.
5254

5355

54-
## Getting Started
56+
## Getting Started with Chat Completion API
5557

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

5860
### Simple call without preserving chat history
5961

60-
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.
62+
In some situations, you will want to use chat completion models without preserving chat history. For example, when you want to perform independent queries in a programmatic way.
6163

6264
Here's a simple example of how to use the `openAIChat` for sentiment analysis:
6365
@@ -78,7 +80,7 @@ systemPrompt = "You are a sentiment analyser. You will look at a sentence and ou
7880
chat = openAIChat(systemPrompt);
7981
8082
% Generate a response, passing a new sentence for classification
81-
text = generate(chat,"The team is feeling very motivated")
83+
txt = generate(chat,"The team is feeling very motivated")
8284
% Should output "positive"
8385
```
8486
@@ -102,24 +104,34 @@ Add a user message to the history and pass it to `generate`
102104
103105
```matlab
104106
history = addUserMessage(history,"What is an eigenvalue?");
105-
[text, response] = generate(chat, history)
107+
[txt, response] = generate(chat, history)
106108
```
107109
108-
The output `text` will contain the answer and `response` will contain the full response, which you need to include in the history as follows
110+
The output `txt` will contain the answer and `response` will contain the full response, which you need to include in the history as follows
109111
```matlab
110112
history = addResponseMessage(history, response);
111113
```
112114
113115
You can keep interacting with the API and since we are saving the history, it will know about previous interactions.
114116
```matlab
115117
history = addUserMessage(history,"Generate MATLAB code that computes that");
116-
[text, response] = generate(chat,history);
118+
[txt, response] = generate(chat,history);
117119
% Will generate code to compute the eigenvalue
118120
```
119121
122+
### Streaming the response
123+
124+
You can specifying the streaming function when you create the chat assistant. This will print the response to the command window.
125+
```matlab
126+
% streaming function
127+
sf = @(x)fprintf("%s",x);
128+
chat = openAIChat(StreamFun=sf);
129+
txt = generate(chat,"What is Model-Based Design and how is it related to Digital Twin?")
130+
```
131+
120132
### Calling MATLAB functions with the API
121133
122-
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.
134+
The optional parameter `Tools` 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.
123135
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.mlx](/examples/ExampleFunctionCalling.mlx), 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.
124136

125137
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:
@@ -128,14 +140,16 @@ For example, if you want to use the API for mathematical operations such as `sin
128140
```matlab
129141
f = openAIFunction("sind","Sine of argument in degrees");
130142
f = addParameter(f,"x",type="number",description="Angle in degrees.");
131-
chat = openAIChat("You are a helpful assistant.",Functions=f);
143+
chat = openAIChat("You are a helpful assistant.",Tools=f);
132144
```
133145

134-
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:
146+
When the model identifies that it could use the defined functions to answer a query, it will return a `tool_calls` request, instead of directly generating the response:
135147

136148
```matlab
149+
messages = openAIMessages;
137150
messages = addUserMessage(messages, "What is the sine of 30?");
138-
[text, response] = generate(chat, messages);
151+
[txt, response] = generate(chat, messages);
152+
messages = addResponseMessage(messages, response);
139153
```
140154

141155
The variable `response` should contain a request for a function call.
@@ -148,9 +162,19 @@ response =
148162
149163
role: 'assistant'
150164
content: []
151-
function_call: [1×1 struct]
165+
tool_calls: [1×1 struct]
166+
167+
>> response.tool_calls
168+
169+
ans =
170+
171+
struct with fields:
172+
173+
id: 'call_wDpCLqtLhXiuRpKFw71gXzdy'
174+
type: 'function'
175+
function: [1×1 struct]
152176
153-
>> response.function_call
177+
>> response.tool_calls.function
154178
155179
ans =
156180
@@ -164,16 +188,18 @@ You can then call the function `sind` with the specified argument and return the
164188

165189
```matlab
166190
% Arguments are returned as a json, so you need to decode it first
167-
args = jsondecode(response.function_call.arguments);
191+
id = string(response.tool_calls.id);
192+
func = string(response.tool_calls.function.name);
193+
args = jsondecode(response.tool_calls.function.arguments);
168194
result = sind(args.x);
169-
messages = addFunctionMessage(messages,"sind","x="+result);
170-
[text, response] = generate(chat, messages);
195+
messages = addToolMessage(messages,id,func,"x="+result);
196+
[txt, response] = generate(chat, messages);
171197
```
172198

173199
The model then will use the function result to generate a more precise response:
174200

175201
```shell
176-
>> text
202+
>> txt
177203
178204
text =
179205
@@ -205,10 +231,10 @@ Note that this function does not need to exist, since it will only be used to ex
205231

206232
```matlab
207233
chat = openAIChat("You are helpful assistant that reads patient records and extracts information", ...
208-
Functions=f);
234+
Tools=f);
209235
messages = openAIMessages;
210236
messages = addUserMessage(messages,"Extract the information from the report:" + newline + patientReport);
211-
[text, response] = generate(chat, messages);
237+
[txt, response] = generate(chat, messages);
212238
```
213239

214240
The model should return the extracted information as a function call:
@@ -221,9 +247,19 @@ response =
221247
222248
role: 'assistant'
223249
content: []
224-
function_call: [1×1 struct]
250+
tool_call: [1×1 struct]
251+
252+
>> response.tool_calls
253+
254+
ans =
225255
226-
>> response.function_call
256+
struct with fields:
257+
258+
id: 'call_4VRtN7jb3pTPosMSb4ZaLoWP'
259+
type: 'function'
260+
function: [1×1 struct]
261+
262+
>> response.tool_calls.function
227263
228264
ans =
229265
@@ -235,6 +271,17 @@ ans =
235271

236272
You can extract the arguments and write the data to a table, for example.
237273

274+
### Understand the content of an image
275+
276+
You can use gpt-4-vision-preview to experiment with image understanding.
277+
```matlab
278+
chat = openAIChat("You are an AI assistant.", ModelName="gpt-4-vision-preview");
279+
image_path = "peppers.png";
280+
messages = openAIMessages;
281+
messages = addUserMessageWithImages(messages,"What is in the image?",image_path);
282+
[txt,response] = generate(chat,messages);
283+
```
284+
238285
### Obtaining embeddings
239286

240287
You can extract embeddings from your text with OpenAI using the function `extractOpenAIEmbeddings` as follows:
@@ -245,21 +292,36 @@ emb = extractOpenAIEmbeddings(exampleText);
245292

246293
The resulting embedding is a vector that captures the semantics of your text and can be used on tasks such as retrieval augmented generation and clustering.
247294

248-
```
295+
```matlab
249296
>> size(emb)
250297
251298
ans =
252299
253300
1 1536
254301
```
302+
## Getting Started with Images API
303+
304+
To get started, you can either create an `openAIImage` object and use its methods or use it in a more complex setup, as needed.
305+
306+
```matlab
307+
mdl = openAIImages(ModelName="dall-e-3");
308+
images = generate(mdl,"Create a 3D avatar of a whimsical sushi on the beach. He is decorated with various sushi elements and is playfully interacting with the beach environment.");
309+
figure
310+
imshow(images{1})
311+
```
255312

256313
## Examples
257314
To learn how to use this in your workflows, see [Examples](/examples/).
258315

259-
- [ExampleSummarization.mlx](/examples/ExampleSummarization.mlx): Learn to create concise summaries of long texts with ChatGPT. (Requires Text Analytics Toolbox™)
316+
- [ExampleStreaming.mlx](/examples/ExampleStreaming.mlx): Learn to implement a simple chat that stream the response.
317+
- [ExampleSummarization.mlx](/examples/ExampleSummarization.mlx): Learn to create concise summaries of long texts with ChatGPT. (Requires Text Analytics Toolbox™)
260318
- [ExampleChatBot.mlx](/examples/ExampleChatBot.mlx): Build a conversational chatbot capable of handling various dialogue scenarios using ChatGPT. (Requires Text Analytics Toolbox)
261319
- [ExampleFunctionCalling.mlx](/examples/ExampleFunctionCalling.mlx): Learn how to create agents capable of executing MATLAB functions.
320+
- [ExampleParallelFunctionCalls.mlx](/examples/ExampleParallelFunctionCalls.mlx): Learn how to take advantage of parallel function calling.
262321
- [ExampleRetrievalAugmentedGeneration.mlx](/examples/ExampleRetrievalAugmentedGeneration.mlx): Learn about retrieval augmented generation with a simple use case. (Requires Text Analytics Toolbox™)
322+
- [ExampleGPT4Vision.mlx](/examples/ExampleGPT4Vision.mlx): Learn how to use GPT-4 Turbo with Vision to understand the content of an image.
323+
- [ExampleJSONMode.mlx](/examples/ExampleJSONMode.mlx): Learn how to use JSON mode in chat completions
324+
- [ExampleDALLE.mlx](/examples/ExampleDALLE.mlx): Learn how to generate images, create variations and edit the images.
263325

264326
## License
265327

@@ -268,4 +330,4 @@ The license is available in the license.txt file in this GitHub repository.
268330
## Community Support
269331
[MATLAB Central](https://www.mathworks.com/matlabcentral)
270332

271-
Copyright 2023 The MathWorks, Inc.
333+
Copyright 2023-2024 The MathWorks, Inc.
230 Bytes
Binary file not shown.

examples/ExampleStreaming.mlx

-18 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)