Skip to content

Commit 1384590

Browse files
committed
Moved mlx into sub-directory, added Markdown export
Generating Markdown in pre-commit hook. The hook needs to be activated in the local repository, by including it in `.git/hooks/pre-commit`.
1 parent c607360 commit 1384590

File tree

49 files changed

+2040
-10
lines changed

Some content is hidden

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

49 files changed

+2040
-10
lines changed

.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

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: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
2+
# Analyze Scientific Papers Using ChatGPT™ Function Calls
3+
4+
To run the code shown on this page, open the MLX file in MATLAB: [mlx-scripts/AnalyzeScientificPapersUsingFunctionCalls.mlx](mlx-scripts/AnalyzeScientificPapersUsingFunctionCalls.mlx)
5+
6+
This example shows how to extract recent scientific papers from ArXiv, summarize them using ChatGPT, and write the results to a CSV file using the `openAIFunction` function.
7+
8+
- The example contains three steps:
9+
- Define a custom function for ChatGPT to use to process its input and output.
10+
- Extract papers from ArXiv.
11+
- Use ChatGPT to assess whether a paper is relevant to your query, and to add an entry to the results table if so.
12+
13+
To run this example, you need a valid API key from a paid OpenAI™ API account.
14+
15+
```matlab
16+
loadenv(".env")
17+
addpath('../..')
18+
```
19+
# Initialize OpenAI API Function and Chat
20+
21+
Use `openAIFunction` to define functions that the model will be able to requests calls.
22+
23+
24+
Set up the function to store paper details and initiate a chat with the OpenAI API with a defined role as a scientific paper expert.
25+
26+
27+
Define the function that you want the model to have access to. In this example the used function is `writePaperDetails`.
28+
29+
```matlab
30+
f = openAIFunction("writePaperDetails", "Function to write paper details to a table.");
31+
f = addParameter(f, "name", type="string", description="Name of the paper.");
32+
f = addParameter(f, "url", type="string", description="URL containing the paper.");
33+
f = addParameter(f, "explanation", type="string", description="Explanation on why the paper is related to the given topic.");
34+
35+
paperVerifier = openAIChat("You are an expert in filtering scientific papers. " + ...
36+
"Given a certain topic, you are able to decide if the paper" + ...
37+
" fits the given topic or not.");
38+
39+
paperExtractor = openAIChat("You are an expert in extracting information from a paper.", Tools=f);
40+
41+
function writePaperDetails(name, url, desc)
42+
filename = "papers_to_read.csv";
43+
T = table(name, url, desc, VariableNames=["Name", "URL", "Description"]);
44+
writetable(T, filename, WriteMode="append");
45+
end
46+
```
47+
# Extract Papers From ArXiv
48+
49+
Specify the category of interest, the date range for the query, and the maximum number of results to retrieve from the ArXiv API.
50+
51+
```matlab
52+
category = "cs.CL";
53+
endDate = datetime("today", "Format","uuuuMMdd");
54+
startDate = datetime("today", "Format","uuuuMMdd") - 5;
55+
maxResults = 40;
56+
urlQuery = "https://export.arxiv.org/api/query?search_query=" + ...
57+
"cat:" + category + ...
58+
"&submittedDate=["+string(startDate)+"+TO+"+string(endDate)+"]"+...
59+
"&max_results=" + maxResults + ...
60+
"&sortBy=submittedDate&sortOrder=descending";
61+
62+
options = weboptions('Timeout',160);
63+
code = webread(urlQuery,options);
64+
```
65+
66+
Extract individual paper entries from the API response and use ChatGPT to determine whether each paper is related to the specified topic.
67+
68+
69+
ChatGPT will parse the XML file, so we only need to extract the relevant entries.
70+
71+
```matlab
72+
entries = extractBetween(code, '<entry>', '</entry>');
73+
```
74+
# Write Relevant Information to Table
75+
76+
Create empty file and determine the topic of interest.
77+
78+
```matlab
79+
filename = "papers_to_read.csv";
80+
T = table([], [], [], VariableNames=["Name", "URL", "Description"]);
81+
writetable(T, filename);
82+
83+
topic = "Large Language Models";
84+
```
85+
86+
Loop over the entries and see if they are relevant to the topic of interest.
87+
88+
```matlab
89+
for i = 1:length(entries)
90+
prompt = "Given the following paper:" + newline +...
91+
string(entries{i})+ newline +...
92+
"Is it related to the topic: "+ topic +"?" + ...
93+
" Answer 'yes' or 'no'.";
94+
[text, response] = generate(paperVerifier, prompt);
95+
96+
```
97+
98+
If the model classifies this entry as relevant, then it tries to request a function call.
99+
100+
```matlab
101+
if contains("yes", text, IgnoreCase=true)
102+
prompt = "Given the following paper:" + newline + string(entries{i})+ newline +...
103+
"Given the topic: "+ topic + newline + "Write the details to a table.";
104+
[text, response] = generate(paperExtractor, prompt);
105+
```
106+
107+
If `function_call` if part of the response, it means the model is requesting a function call. The function call request should contain the needed arguments to call the function specified at the end of this example and defined with `openAIFunctions`.
108+
109+
```matlab
110+
if isfield(response, "tool_calls")
111+
funCall = response.tool_calls;
112+
functionCallAttempt(funCall);
113+
end
114+
end
115+
end
116+
```
117+
118+
Read the generated file.
119+
120+
```matlab
121+
data = readtable("papers_to_read.csv", Delimiter=",")
122+
```
123+
# Helper Function
124+
125+
This function handles function call attempts from the model, checking the function name and arguments before calling the appropriate function to store the paper details.
126+
127+
```matlab
128+
function functionCallAttempt(funCall)
129+
```
130+
131+
The model can sometimes hallucinate function names, so you need to ensure that it's suggesting the correct name.
132+
133+
```matlab
134+
if funCall.function.name == "writePaperDetails"
135+
try
136+
```
137+
138+
The model can sometimes return improperly formed JSON, which needs to be handled.
139+
140+
```matlab
141+
funArgs = jsondecode(funCall.function.arguments);
142+
catch ME
143+
error("Model returned improperly formed JSON.");
144+
end
145+
```
146+
147+
The model can hallucinate arguments. The code needs to ensure the arguments have been defined before calling the function.
148+
149+
```matlab
150+
if isfield(funArgs, "name") && isfield(funArgs, "url") && isfield(funArgs,"explanation")
151+
writePaperDetails(string(funArgs.name), string(funArgs.url), string(funArgs.explanation));
152+
end
153+
end
154+
end
155+
```
156+
157+
*Copyright 2023\-2024 The MathWorks, Inc.*
158+
Binary file not shown.
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
2+
# Analyze Sentiment in Text Using ChatGPT™ in JSON Mode
3+
4+
To run the code shown on this page, open the MLX file in MATLAB: [mlx-scripts/AnalyzeSentimentinTextUsingChatGPTinJSONMode.mlx](mlx-scripts/AnalyzeSentimentinTextUsingChatGPTinJSONMode.mlx)
5+
6+
This example shows how to use ChatGPT for sentiment analysis and output the results in JSON format.
7+
8+
9+
To run this example, you need a valid API key from a paid OpenAI™ API account.
10+
11+
```matlab
12+
loadenv(".env")
13+
addpath('../..')
14+
```
15+
16+
Define some text to analyze the sentiment.
17+
18+
```matlab
19+
inputText = ["I can't stand homework.";
20+
"This sucks. I'm bored.";
21+
"I can't wait for Halloween!!!";
22+
"I am neigher for or against the idea.";
23+
"My cat is adorable ❤️❤️";
24+
"I hate chocolate"];
25+
```
26+
27+
Define the expected output JSON Schema.
28+
29+
```matlab
30+
jsonSchema = '{"sentiment": "string (positive, negative, neutral)","confidence_score": "number (0-1)"}';
31+
```
32+
33+
Define the the system prompt, combining your instructions and the JSON Schema. In order for the model to output JSON, you need to specify that in the prompt, for example, adding *"designed to output to JSON"* to the prompt.
34+
35+
```matlab
36+
systemPrompt = "You are an AI designed to output to JSON. You analyze the sentiment of the provided text and " + ...
37+
"Determine whether the sentiment is positive, negative, or neutral and provide a confidence score using " + ...
38+
"the schema: " + jsonSchema;
39+
prompt = "Analyze the sentiment of the provided text. " + ...
40+
"Determine whether the sentiment is positive, negative," + ...
41+
" or neutral and provide a confidence score";
42+
```
43+
44+
Create a chat object with `ModelName gpt-3.5-turbo` and specify `ResponseFormat` as `"json".`
45+
46+
```matlab
47+
model = "gpt-3.5-turbo";
48+
chat = openAIChat(systemPrompt, ModelName=model, ResponseFormat="json");
49+
```
50+
51+
```matlabTextOutput
52+
Warning: When using JSON mode, you must also prompt the model to produce JSON yourself via a system or user message.
53+
```
54+
55+
Concatenate the prompt and input text and generate an answer with the model.
56+
57+
```matlab
58+
scores = cell(1,numel(inputText));
59+
for i = 1:numel(inputText)
60+
```
61+
62+
Generate a response from the message.
63+
64+
```matlab
65+
[json, message, response] = generate(chat,prompt + newline + newline + inputText(i));
66+
scores{i} = jsondecode(json);
67+
end
68+
```
69+
70+
Extract the data from the JSON ouput.
71+
72+
```matlab
73+
T = struct2table([scores{:}]);
74+
T.text = inputText;
75+
T = movevars(T,"text","Before","sentiment")
76+
```
77+
| |text|sentiment|confidence_score|
78+
|:--:|:--:|:--:|:--:|
79+
|1|"I can't stand homework."|'negative'|0.9500|
80+
|2|"This sucks. I'm bored."|'negative'|0.9000|
81+
|3|"I can't wait for Halloween!!!"|'positive'|0.9500|
82+
|4|"I am neigher for or against the idea."|'neutral'|1|
83+
|5|"My cat is adorable ❤️❤️"|'positive'|0.9500|
84+
|6|"I hate chocolate"|'negative'|0.9000|
85+
86+
87+
*Copyright 2024 The MathWorks, Inc.*
88+
Binary file not shown.

0 commit comments

Comments
 (0)