Skip to content

Commit 874536b

Browse files
Cosmetic fixes
2 parents 963a6d9 + ae07cd9 commit 874536b

File tree

63 files changed

+2244
-63
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

63 files changed

+2244
-63
lines changed

+llms/+utils/errorMessageCatalog.m

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -41,22 +41,22 @@
4141
catalog("llms:mustBeAssistantWithIdAndFunction") = "Field 'tool_call' must be a struct with fields 'id' and 'function'.";
4242
catalog("llms:mustBeAssistantWithNameAndArguments") = "Field 'function' must be a struct with fields 'name' and 'arguments'.";
4343
catalog("llms:assistantMustHaveTextNameAndArguments") = "Fields 'name' and 'arguments' must be text with one or more characters.";
44-
catalog("llms:mustBeValidIndex") = "Index exceeds the number of array elements. Index must be less than or equal to ({1}).";
45-
catalog("llms:stopSequencesMustHaveMax4Elements") = "Number of elements must not be larger than 4.";
44+
catalog("llms:mustBeValidIndex") = "Index exceeds the number of array elements. Index must be less than or equal to {1}.";
45+
catalog("llms:stopSequencesMustHaveMax4Elements") = "Number of stop sequences must be less than or equal to 4.";
4646
catalog("llms:endpointMustBeSpecified") = "Unable to find endpoint. Either set environment variable AZURE_OPENAI_ENDPOINT or specify name-value argument ""Endpoint"".";
4747
catalog("llms:deploymentMustBeSpecified") = "Unable to find deployment name. Either set environment variable AZURE_OPENAI_DEPLOYMENT or specify name-value argument ""Deployment"".";
4848
catalog("llms:keyMustBeSpecified") = "Unable to find API key. Either set environment variable {1} or specify name-value argument ""APIKey"".";
49-
catalog("llms:mustHaveMessages") = "Value must contain at least one message in Messages.";
49+
catalog("llms:mustHaveMessages") = "Message history must not be empty.";
5050
catalog("llms:mustSetFunctionsForCall") = "When no functions are defined, ToolChoice must not be specified.";
51-
catalog("llms:mustBeMessagesOrTxt") = "Messages must be text with one or more characters or a messageHistory object.";
52-
catalog("llms:invalidOptionAndValueForModel") = "'{1}' with value '{2}' is not supported for ModelName '{3}'";
53-
catalog("llms:invalidOptionForModel") = "{1} is not supported for ModelName '{2}'";
54-
catalog("llms:invalidContentTypeForModel") = "{1} is not supported for ModelName '{2}'";
55-
catalog("llms:functionNotAvailableForModel") = "This function is not supported for ModelName '{1}'";
56-
catalog("llms:promptLimitCharacter") = "Prompt must have a maximum length of {1} characters for ModelName '{2}'";
57-
catalog("llms:pngExpected") = "Argument must be a PNG image.";
51+
catalog("llms:mustBeMessagesOrTxt") = "Message must be nonempty string, character array, cell array of character vectors, or messageHistory object.";
52+
catalog("llms:invalidOptionAndValueForModel") = "'{1}' with value '{2}' is not supported for model ""{3}"".";
53+
catalog("llms:invalidOptionForModel") = "Invalid argument name {1} for model ""{2}"".";
54+
catalog("llms:invalidContentTypeForModel") = "{1} is not supported for model ""{2}"".";
55+
catalog("llms:functionNotAvailableForModel") = "Image editing is not supported for model ""{1}"".";
56+
catalog("llms:promptLimitCharacter") = "Prompt must contain at most {1} characters for model ""{2}"".";
57+
catalog("llms:pngExpected") = "Image must be a PNG file (*.png).";
5858
catalog("llms:warningJsonInstruction") = "When using JSON mode, you must also prompt the model to produce JSON yourself via a system or user message.";
59-
catalog("llms:apiReturnedError") = "Server error: ""{1}""";
59+
catalog("llms:apiReturnedError") = "Server returned error indicating: ""{1}""";
6060
catalog("llms:dimensionsMustBeSmallerThan") = "Dimensions must be less than or equal to {1}.";
6161
catalog("llms:stream:responseStreamer:InvalidInput") = "Input does not have the expected json format, got ""{1}"".";
6262
end

.githooks/pre-commit

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#!/bin/bash
2+
3+
cd $(git rev-parse --show-toplevel)
4+
pwd
5+
6+
# For all commits of mlx files, create corresponding Markdown (md) files.
7+
# If the mlx files are in .../mlx-scripts/*.mlx, the corresponding
8+
# md files will go into .../*.md.
9+
#
10+
# This script assumes that the mlx files as currently in the file system
11+
# are what is being committed, instead of doing a lot of extra work to
12+
# get them from the stage area.
13+
#
14+
# Note that this script will not remove media files. If an mlx has
15+
# fewer plots at some point in the future, there will be file system
16+
# cruft. Which doesn't hurt the md display in GitHub or elswehere.
17+
changedMlxFiles=`git diff --cached --name-only --diff-filter=d '*.mlx'`
18+
19+
if [ -n "$changedMlxFiles" ]; then
20+
# Keep the line break here, we replace end-of-line with "' '" to get the quotes right
21+
matlab -batch "for file = {'${changedMlxFiles//
22+
/' '}'}, export(file{1},replace(erase(file{1},'mlx-scripts'),'.mlx','.md')); end"
23+
tmp=${changedMlxFiles//mlx-scripts\//}
24+
mdFiles=${tmp//.mlx/.md}
25+
for file in $mdFiles; do
26+
if [ -d ${file%.md}_media ]; then
27+
git add ${file%.md}_media/
28+
fi
29+
perl -pi -e "\$cnt++ if /^#/; " \
30+
-e "\$_ .= \"\nTo run the code shown on this page, open the MLX file in MATLAB®: [mlx-scripts/$(basename $file .md).mlx](mlx-scripts/$(basename $file .md).mlx) \n\" if /^#/ && \$cnt==1;" \
31+
$file
32+
done
33+
git add $mdFiles
34+
fi

.github/workflows/ci.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ jobs:
3030
- name: Pull models
3131
run: |
3232
ollama pull mistral
33+
ollama pull bakllava
3334
OLLAMA_HOST=127.0.0.1:11435 ollama pull qwen2:0.5b
3435
- name: Set up MATLAB
3536
uses: matlab-actions/setup-matlab@v2

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ startup.m
55
papers_to_read.csv
66
data/*
77
examples/data/*
8+
examples/mlx-scripts/data/*
89
._*
910
.nfs*
1011
.DS_Store

DEVELOPMENT.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# Notes for Developers
2+
3+
Nothing in this file should be required knowledge to use the repository. These are notes for people actually making changes that are going to be submitted and incorporated into the main branch.
4+
5+
## Git Hooks
6+
7+
After checkout, link or (on Windows) copy the files from `.githooks` into the local `.git/hooks` folder:
8+
9+
```
10+
(cd .git/hooks/; ln -s ../../.githooks/pre-commit .)
11+
```

README.md

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

33
[![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) [![View Large Language Models (LLMs) with MATLAB on File Exchange](https://www.mathworks.com/matlabcentral/images/matlab-file-exchange.svg)](https://www.mathworks.com/matlabcentral/fileexchange/163796-large-language-models-llms-with-matlab)
44

5-
This repository contains code to connect MATLAB to the [OpenAI Chat Completions API](https://platform.openai.com/docs/guides/text-generation/chat-completions-api) (which powers ChatGPT™), OpenAI Images API (which powers DALL·E™), [Azure® OpenAI Service](https://learn.microsoft.com/en-us/azure/ai-services/openai/), and both local and nonlocal [Ollama™](https://ollama.com/) models. This allows you to leverage the natural language processing capabilities of large language models directly within your MATLAB environment.
5+
This repository contains code to connect MATLAB® to the [OpenAI® Chat Completions API](https://platform.openai.com/docs/guides/text-generation/chat-completions-api) (which powers ChatGPT™), OpenAI Images API (which powers DALL·E™), [Azure® OpenAI Service](https://learn.microsoft.com/en-us/azure/ai-services/openai/), and both local and nonlocal [Ollama™](https://ollama.com/) models. This allows you to leverage the natural language processing capabilities of large language models directly within your MATLAB environment.
66

77
## Requirements
88

@@ -52,16 +52,16 @@ To use this repository with a local installation of MATLAB, first clone the repo
5252
## Examples
5353
To learn how to use this in your workflows, see [Examples](/examples/).
5454

55-
- [ProcessGeneratedTextinRealTimebyUsingChatGPTinStreamingMode.mlx](/examples/ProcessGeneratedTextinRealTimebyUsingChatGPTinStreamingMode.mlx): Learn to implement a simple chat that stream the response.
56-
- [SummarizeLargeDocumentsUsingChatGPTandMATLAB.mlx](/examples/SummarizeLargeDocumentsUsingChatGPTandMATLAB.mlx): Learn to create concise summaries of long texts with ChatGPT. (Requires Text Analytics Toolbox™)
57-
- [CreateSimpleChatBot.mlx](/examples/CreateSimpleChatBot.mlx): Build a conversational chatbot capable of handling various dialogue scenarios using ChatGPT. (Requires Text Analytics Toolbox)
58-
- [AnalyzeScientificPapersUsingFunctionCalls.mlx](/examples/AnalyzeScientificPapersUsingFunctionCalls.mlx): Learn how to create agents capable of executing MATLAB functions.
59-
- [AnalyzeTextDataUsingParallelFunctionCallwithChatGPT.mlx](/examples/AnalyzeTextDataUsingParallelFunctionCallwithChatGPT.mlx): Learn how to take advantage of parallel function calling.
60-
- [RetrievalAugmentedGenerationUsingChatGPTandMATLAB.mlx](/examples/RetrievalAugmentedGenerationUsingChatGPTandMATLAB.mlx): Learn about retrieval augmented generation with a simple use case. (Requires Text Analytics Toolbox™)
61-
- [DescribeImagesUsingChatGPT.mlx](/examples/DescribeImagesUsingChatGPT.mlx): Learn how to use GPT-4 Turbo with Vision to understand the content of an image.
62-
- [AnalyzeSentimentinTextUsingChatGPTinJSONMode.mlx](/examples/AnalyzeSentimentinTextUsingChatGPTinJSONMode.mlx): Learn how to use JSON mode in chat completions
63-
- [UsingDALLEToEditImages.mlx](/examples/UsingDALLEToEditImages.mlx): Learn how to generate images
64-
- [UsingDALLEToGenerateImages.mlx](/examples/UsingDALLEToGenerateImages.mlx): Create variations of images and editimages.
55+
- [ProcessGeneratedTextinRealTimebyUsingChatGPTinStreamingMode.md](/examples/ProcessGeneratedTextinRealTimebyUsingChatGPTinStreamingMode.md): Learn to implement a simple chat that stream the response.
56+
- [SummarizeLargeDocumentsUsingChatGPTandMATLAB.md](/examples/SummarizeLargeDocumentsUsingChatGPTandMATLAB.md): Learn to create concise summaries of long texts with ChatGPT. (Requires Text Analytics Toolbox™)
57+
- [CreateSimpleChatBot.md](/examples/CreateSimpleChatBot.md): Build a conversational chatbot capable of handling various dialogue scenarios using ChatGPT. (Requires Text Analytics Toolbox)
58+
- [AnalyzeScientificPapersUsingFunctionCalls.md](/examples/AnalyzeScientificPapersUsingFunctionCalls.md): Learn how to create agents capable of executing MATLAB functions.
59+
- [AnalyzeTextDataUsingParallelFunctionCallwithChatGPT.md](/examples/AnalyzeTextDataUsingParallelFunctionCallwithChatGPT.md): Learn how to take advantage of parallel function calling.
60+
- [RetrievalAugmentedGenerationUsingChatGPTandMATLAB.md](/examples/RetrievalAugmentedGenerationUsingChatGPTandMATLAB.md): Learn about retrieval augmented generation with a simple use case. (Requires Text Analytics Toolbox™)
61+
- [DescribeImagesUsingChatGPT.md](/examples/DescribeImagesUsingChatGPT.md): Learn how to use GPT-4 Turbo with Vision to understand the content of an image.
62+
- [AnalyzeSentimentinTextUsingChatGPTinJSONMode.md](/examples/AnalyzeSentimentinTextUsingChatGPTinJSONMode.md): Learn how to use JSON mode in chat completions
63+
- [UsingDALLEToEditImages.md](/examples/UsingDALLEToEditImages.md): Learn how to generate images
64+
- [UsingDALLEToGenerateImages.md](/examples/UsingDALLEToGenerateImages.md): Create variations of images and editimages.
6565

6666
## License
6767

azureChat.m

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@
191191
if isstring(messages) && isscalar(messages)
192192
messagesStruct = {struct("role", "user", "content", messages)};
193193
else
194-
messagesStruct = messages.Messages;
194+
messagesStruct = this.encodeImages(messages.Messages);
195195
end
196196

197197
if ~isempty(this.SystemPrompt)
@@ -251,6 +251,40 @@ function mustBeValidFunctionCall(this, functionCall)
251251
end
252252

253253
end
254+
255+
function messageStruct = encodeImages(~, messageStruct)
256+
for k=1:numel(messageStruct)
257+
if isfield(messageStruct{k},"images")
258+
images = messageStruct{k}.images;
259+
detail = messageStruct{k}.image_detail;
260+
messageStruct{k} = rmfield(messageStruct{k},["images","image_detail"]);
261+
messageStruct{k}.content = ...
262+
{struct("type","text","text",messageStruct{k}.content)};
263+
for img = images(:).'
264+
if startsWith(img,("https://"|"http://"))
265+
s = struct( ...
266+
"type","image_url", ...
267+
"image_url",struct("url",img));
268+
else
269+
[~,~,ext] = fileparts(img);
270+
MIMEType = "data:image/" + erase(ext,".") + ";base64,";
271+
% Base64 encode the image using the given MIME type
272+
fid = fopen(img);
273+
im = fread(fid,'*uint8');
274+
fclose(fid);
275+
b64 = matlab.net.base64encode(im);
276+
s = struct( ...
277+
"type","image_url", ...
278+
"image_url",struct("url",MIMEType + b64));
279+
end
280+
281+
s.image_url.detail = detail;
282+
283+
messageStruct{k}.content{end+1} = s;
284+
end
285+
end
286+
end
287+
end
254288
end
255289
end
256290

doc/Azure.md

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
# Connecting to Azure® OpenAI Service
1+
# Connecting to Azure OpenAI Service
22

3-
This repository contains code to connect MATLAB to the [Azure® OpenAI Service](https://learn.microsoft.com/en-us/azure/ai-services/openai/).
3+
This repository contains code to connect MATLAB to the [Azure® OpenAI® Service](https://learn.microsoft.com/en-us/azure/ai-services/openai/).
44

55
To use Azure OpenAI Services, you need to create a model deployment on your Azure account and obtain one of the keys for it. You are responsible for any fees Azure 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 Azure APIs.
66

@@ -31,7 +31,7 @@ loadenv(".env")
3131

3232
## Establishing a connection to Chat Completions API using Azure
3333

34-
To connect MATLAB to Chat Completions API via Azure, you will have to create an `azureChat` object. See [the Azure documentation](https://learn.microsoft.com/en-us/azure/ai-services/openai/chatgpt-quickstart) for details on the setup required and where to find your key, endpoint, and deployment name. As explained above, the endpoint, deployment, and key should be in the environment variables `AZURE_OPENAI_ENDPOINT`, `AZURE_OPENAI_DEPLOYMENYT`, and `AZURE_OPENAI_API_KEY`, or provided as `Endpoint=…`, `Deployment=…`, and `APIKey=…` in the `azureChat` call below.
34+
To connect MATLAB® to Chat Completions API via Azure, you will have to create an `azureChat` object. See [the Azure documentation](https://learn.microsoft.com/en-us/azure/ai-services/openai/chatgpt-quickstart) for details on the setup required and where to find your key, endpoint, and deployment name. As explained above, the endpoint, deployment, and key should be in the environment variables `AZURE_OPENAI_ENDPOINT`, `AZURE_OPENAI_DEPLOYMENYT`, and `AZURE_OPENAI_API_KEY`, or provided as `Endpoint=…`, `Deployment=…`, and `APIKey=…` in the `azureChat` call below.
3535

3636
In order to create the chat assistant, use the `azureChat` function, optionally providing a system prompt:
3737
```matlab
@@ -115,6 +115,19 @@ txt = generate(chat,"What is Model-Based Design and how is it related to Digital
115115
% Should stream the response token by token
116116
```
117117

118+
## Understanding the content of an image
119+
120+
You can use gpt-4o, gpt-4o-mini, or gpt-4-turbo to experiment with image understanding.
121+
```matlab
122+
chat = azureChat("You are an AI assistant.",Deployment="gpt-4o");
123+
image_path = "peppers.png";
124+
messages = messageHistory;
125+
messages = addUserMessageWithImages(messages,"What is in the image?",image_path);
126+
[txt,response] = generate(chat,messages,MaxNumTokens=4096);
127+
txt
128+
% outputs a description of the image
129+
```
130+
118131
## Calling MATLAB functions with the API
119132

120133
Optionally, `Tools=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.

doc/Ollama.md

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Ollama
22

3-
This repository contains code to connect MATLAB to an [Ollama™](https://ollama.com) server, running large language models (LLMs).
3+
This repository contains code to connect MATLAB® to an [Ollama™](https://ollama.com) server, running large language models (LLMs).
44

55
To use local models with Ollama, you will need to install and start an Ollama server, and “pull” models into it. Please follow the Ollama documentation for details. 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 any specific model.
66

@@ -96,6 +96,24 @@ txt = generate(chat,"What is Model-Based Design and how is it related to Digital
9696
% Should stream the response token by token
9797
```
9898

99+
## Understanding the content of an image
100+
101+
You can use multimodal models like `llava` to experiment with image understanding.
102+
103+
> [!TIP]
104+
> Many models available for Ollama allow you to include images in the prompt, even if the model does not support image inputs. In that case, the images are silently removed from the input. This can result in unexpected outputs.
105+
106+
107+
```matlab
108+
chat = ollamaChat("llava");
109+
image_path = "peppers.png";
110+
messages = messageHistory;
111+
messages = addUserMessageWithImages(messages,"What is in the image?",image_path);
112+
[txt,response] = generate(chat,messages,MaxNumTokens=4096);
113+
txt
114+
% outputs a description of the image
115+
```
116+
99117
## Establishing a connection to remote LLMs using Ollama
100118

101119
To connect to a remote Ollama server, use the `Endpoint` name-value pair. Include the server name and port number. Ollama starts on 11434 by default.

doc/OpenAI.md

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
# OpenAI
1+
# OpenAI
22

3-
Several functions in this repository connect MATLAB to the [OpenAI Chat Completions API](https://platform.openai.com/docs/guides/text-generation/chat-completions-api) (which powers ChatGPT™) and the [OpenAI Images API](https://platform.openai.com/docs/guides/images/image-generation-beta) (which powers DALL·E™).
3+
Several functions in this repository connect MATLAB® to the [OpenAI® Chat Completions API](https://platform.openai.com/docs/guides/text-generation/chat-completions-api) (which powers ChatGPT™) and the [OpenAI Images API](https://platform.openai.com/docs/guides/images/image-generation-beta) (which powers DALL·E™).
44

55
To start using the OpenAI APIs, you first need to obtain 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

@@ -250,14 +250,15 @@ You can extract the arguments and write the data to a table, for example.
250250

251251
## Understanding the content of an image
252252

253-
You can use gpt-4-turbo to experiment with image understanding.
253+
You can use gpt-4o, gpt-4o-mini, or gpt-4-turbo to experiment with image understanding.
254254
```matlab
255-
chat = openAIChat("You are an AI assistant.", ModelName="gpt-4-turbo");
255+
chat = openAIChat("You are an AI assistant.");
256256
image_path = "peppers.png";
257257
messages = messageHistory;
258258
messages = addUserMessageWithImages(messages,"What is in the image?",image_path);
259259
[txt,response] = generate(chat,messages,MaxNumTokens=4096);
260-
% Should output the description of the image
260+
txt
261+
% outputs a description of the image
261262
```
262263

263264
## Obtaining embeddings

0 commit comments

Comments
 (0)