Skip to content

Commit c5f0f4a

Browse files
committed
adding examples.
1 parent 393ceb1 commit c5f0f4a

10 files changed

+276
-9
lines changed

README.md

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -147,14 +147,11 @@ Then the model can give a more precise answer based on the result of the functio
147147
```
148148
149149
## Examples
150-
To learn how to use this in testing workflows, see [Examples](/examples/).
151-
152-
- [ExampleBasicUsage.mlx](/examples/ExampleBasicUsage.mlx): A beginner's guide to using ChatGPT with a focus on parameter settings like temperature for controlling text generation.
153-
- [ExampleSummarization.mlx](/examples/ExampleSummarization.mlx): Learn to create concise summaries of long texts with ChatGPT.
154-
- [ExampleChatBot.mlx](/examples/ExampleChatBot.mlx): Build a conversational chatbot capable of handling various dialogue scenarios using ChatGPT.
155-
- [ExampleRetrievalAugmentedGeneration.mlx](/examples/ExampleRetrievalAugmentedGeneration.mlx): Enhance ChatGPT responses by integrating data retrieved from a separate knowledge base.
156-
- [ExampleRobotControl.mlx](/examples/ExampleRobotControl.mlx): Translate natural language commands into robotic actions using ChatGPT.
157-
- [ExampleAgentCreation.mlx](/examples/ExampleAgentCreation.mlx): Learn how to create agents capable of execting MATLAB functions.
150+
To learn how to use this in your workflows, see [Examples](/examples/).
151+
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.
158155
159156
## License
160157

examples/ExampleAgentCreation.mlx

-2.75 KB
Binary file not shown.

examples/ExampleChatBot.m

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
%% Creating a Chatbot
2+
% This script orchestrates a chat interaction with the OpenAI Chat Completions API, taking user
3+
% inputs, maintaining a word count, and ensuring the chat remains within a
4+
% predefined word limit.
5+
6+
% Set the maximum allowable number of words per chat session
7+
wordLimit = 2000;
8+
9+
% Define the keyword that, when entered by the user, ends the chat session
10+
stopWord = "end";
11+
12+
13+
modelName = "gpt-3.5-turbo";
14+
chat = openAIChat("You are a helpful assistant.", ModelName=modelName);
15+
16+
messages = openAIMessages;
17+
18+
query = "";
19+
totalWords = 0;
20+
messagesSizes = [];
21+
22+
% Main loop: continues indefinitely until the user inputs the stop word
23+
while true
24+
% Prompt the user for input and convert it to a string
25+
query = input("User: ", "s");
26+
query = string(query);
27+
28+
% If the user inputs the stop word, display a farewell message and exit the loop
29+
if query == stopWord
30+
disp("AI: Closing the chat. Have a great day!")
31+
break;
32+
end
33+
34+
35+
numWordsQuery = countNumWords(query);
36+
37+
% If the query exceeds the word limit, display an error message and halt execution
38+
if numWordsQuery>wordLimit
39+
error("Your query should have less than 2000 words. You query had " + numWordsQuery + " words")
40+
end
41+
42+
% Keep track of the size of each message and the total number of words used so far
43+
messagesSizes = [messagesSizes; numWordsQuery]; %#ok
44+
totalWords = totalWords + numWordsQuery;
45+
46+
% If the total word count exceeds the limit, remove messages from the start of the session until it no longer does
47+
while totalWords > wordLimit
48+
totalWords = totalWords - messagesSizes(1);
49+
messages = removeMessage(messages, 1);
50+
messagesSizes(1) = [];
51+
end
52+
53+
% Add the user's message to the session and generate a response using the OpenAI API
54+
messages = addUserMessage(messages, query);
55+
[text, response] = generate(chat, messages);
56+
57+
disp("AI: " + text)
58+
59+
% Count the number of words in the AI's response and update the total word count
60+
numWordsResponse = countNumWords(text);
61+
messagesSizes = [messagesSizes; numWordsResponse]; %#ok
62+
totalWords = totalWords + numWordsResponse;
63+
64+
% Add the AI's response to the session
65+
messages = addResponseMessage(messages, response);
66+
end
67+
68+
%% countNumWords function
69+
% Function to count the number of words in a text string
70+
function numWords = countNumWords(text)
71+
numWords = doclength(tokenizedDocument(text));
72+
end

examples/ExampleChatBot.mlx

-2.75 KB
Binary file not shown.

examples/ExampleFunctionCalling.m

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
%% Using ChatGPT with function calls
2+
% This script automatically analyzes recent scientific papers from the
3+
% ArXiv API, filtering papers based on the topic and using ChatGPT
4+
% functions feature to extract relevant information on the papers.
5+
6+
%% Initialize OpenAI API Function and Chat
7+
% Set up the function to store paper details and initiate a chat with the OpenAI API
8+
% with a defined role as a scientific paper expert.
9+
10+
% Define the function that you want the model to have access to. The
11+
% function is defined at the end of the example.
12+
f = openAIFunction("writePaperDetails", "Function to write paper details to a table.");
13+
f = addParameter(f, "name", type="string", description="Name of the paper.");
14+
f = addParameter(f, "url", type="string", description="URL containing the paper.");
15+
f = addParameter(f, "explanation", type="string", description="Explanation on why the paper is related to the given topic.");
16+
17+
chat = openAIChat("You are an expert in filtering scientific papers. " + ...
18+
"Given a certain topic, you are able to decide if the paper" + ...
19+
" fits the given topic or not.", Functions=f);
20+
21+
%% Query ArXiv API for Recent Papers
22+
% Specify the category of interest, the date range for the query, and the maximum
23+
% number of results to retrieve from the ArXiv API.
24+
25+
category = "cs.CL";
26+
endDate = datetime("today", "Format","uuuuMMdd");
27+
startDate = datetime("today", "Format","uuuuMMdd") - 5;
28+
maxResults = 40;
29+
urlQuery = "https://export.arxiv.org/api/query?search_query=" + ...
30+
"cat:" + category + ...
31+
"&submittedDate=["+string(startDate)+"+TO+"+string(endDate)+"]"+...
32+
"&max_results=" + maxResults + ...
33+
"&sortBy=submittedDate&sortOrder=descending";
34+
35+
options = weboptions('Timeout',160);
36+
code = webread(urlQuery,options);
37+
38+
%% Extract Paper Entries and Filter by Topic
39+
% Extract individual paper entries from the API response and use ChatGPT
40+
% to determine whether each paper is related to the specified topic.
41+
42+
pattern = '<entry>(.*?)</entry>';
43+
44+
% ChatGPT will parse the XML file, so we only need to extract the relevant
45+
% entries.
46+
matches = regexp(code, pattern, 'tokens');
47+
48+
% Determine the topic of interest
49+
topic = "Embedding documents or sentences";
50+
51+
% Loop over the entries and see if they are relevant to the topic of
52+
% interest.
53+
for i = 1:length(matches)
54+
prompt = "Given the following paper:" + newline +...
55+
string(matches{i})+ newline +...
56+
"Is it related to the topic: "+ topic +"?" + ...
57+
" Answer 'yes' or 'no'.";
58+
[text, response] = generate(chat, prompt);
59+
60+
% If the model classifies this entry as relevant, then it tries to
61+
% request a function call.
62+
if contains("yes", text, IgnoreCase=true)
63+
prompt = "Given the following paper:" + newline + string(matches{i})+ newline +...
64+
"Given the topic: "+ topic + newline + "Write the details to a table.";
65+
[text, response] = generate(chat, prompt);
66+
67+
% If function_call if part of the response, it means the model is
68+
% requesting a function call. The function call request should
69+
% contain the needed arguments to call the function specified at
70+
% the end of this example and defined with openAIFunctions
71+
if isfield(response, "function_call")
72+
funCall = response.function_call;
73+
functionCallAttempt(funCall);
74+
end
75+
end
76+
end
77+
78+
%% Function to Handle Function Call Attempts
79+
% This function handles function call attempts from the model, checking
80+
% the function name and arguments before calling the appropriate function to
81+
% store the paper details.
82+
83+
function functionCallAttempt(funCall)
84+
% The model can sometimes hallucinate function names, so you need to ensure
85+
% that it's suggesting the correct name.
86+
if funCall.name == "writePaperDetails"
87+
try
88+
% The model can sometimes return improperly formed JSON, which
89+
% needs to be handled
90+
funArgs = jsondecode(funCall.arguments);
91+
catch ME
92+
error("Model returned improperly formed JSON.");
93+
end
94+
% The model can hallucinate arguments. The code needs to ensure the
95+
% arguments have been defined before calling the function.
96+
if isfield(funArgs, "name") && isfield(funArgs, "url") && isfield(funArgs,"explanation")
97+
writePaperDetails(string(funArgs.name), string(funArgs.url), string(funArgs.explanation));
98+
end
99+
end
100+
end
101+
102+
%% Function to Write Paper Details to CSV File
103+
% This function takes the details of a scientific paper and writes them to
104+
% a CSV file for further review.
105+
106+
function writePaperDetails(name, url, desc)
107+
filename = "papers_to_read.csv";
108+
T = table(name, url, desc, VariableNames=["Name", "URL", "Description"]);
109+
writetable(T, filename, WriteMode="append");
110+
end
-2.75 KB
Binary file not shown.

examples/ExampleRobotControl.mlx

-2.75 KB
Binary file not shown.

examples/ExampleSummarization.m

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
%% Summarization using ChatGPT
2+
% This script leverages ChatGPT to summarize texts of different lengths.
3+
4+
%% Summarizing small documents
5+
% In this part of the script, a ChatGPT session is initialized to summarize a short
6+
% piece of text extracted from a webpage hosted by MathWorks.
7+
8+
% Initiating a ChatGPT session with the role defined as a professional summarizer
9+
chat = openAIChat("You are a professional summarizer, create a summary of the provided text, be it an article, post, conversation, or passage.");
10+
11+
12+
url = "https://www.mathworks.com/help/textanalytics";
13+
code = webread(url);
14+
shortText = extractHTMLText(string(code));
15+
16+
% Utilizing ChatGPT to create a summary of the extracted text
17+
shortTextSummary = generate(chat, shortText)
18+
19+
%% Summarizing large documents
20+
% This section of the script demonstrates how to incrementally summarize a large text
21+
% by breaking it into smaller chunks and summarizing each chunk step by
22+
% step. It uses as input text Romeo and Juliet, by William Shakespeare,
23+
% from The Project Gutenberg.
24+
25+
options = weboptions(Timeout=30);
26+
code = webread("https://www.gutenberg.org/files/1513/1513-h/1513-h.htm", options);
27+
longText = extractHTMLText(string(code));
28+
29+
incrementalSummary = longText;
30+
31+
% Define the number of words in each chunk
32+
limitChunkWords = 2000;
33+
34+
% Creating initial divisions of the text into chunks
35+
chunks = createChunks(incrementalSummary, limitChunkWords);
36+
37+
% Initiating a ChatGPT session with the role of summarizing text
38+
summarizer = openAIChat("You are a professional summarizer.");
39+
40+
% Looping process to gradually summarize the text chunk by chunk, reducing
41+
% the chunk size with each iteration.
42+
while numel(chunks)>1
43+
summarizedChunks = strings(size(chunks));
44+
45+
for i = 1:length(chunks)
46+
summarizedChunks(i) = generate(summarizer, "Summarize this content:" + newline + chunks(i));
47+
end
48+
49+
% Merging the summarized chunks to serve as the base for the next iteration
50+
incrementalSummary = join(summarizedChunks);
51+
52+
% Forming new chunks with a reduced size for the subsequent iteration
53+
chunks = createChunks(incrementalSummary, limitChunkWords);
54+
end
55+
56+
% Compiling the final summary by combining the summaries from all the chunks
57+
fullSummary = generate(summarizer, "Combine these summaries:" + newline + incrementalSummary)
58+
59+
%% CreateChunks function
60+
% This function segments a long text into smaller parts of a predefined size
61+
% to facilitate easier summarization. It preserves the structure of
62+
% sentences. The chunkSize should be large enough to fit at least one
63+
% sentence.
64+
65+
function chunks = createChunks(text, chunkSize)
66+
% Tokenizing the input text for processing
67+
text = tokenizedDocument(text);
68+
69+
% Splitting the tokenized text into individual sentences
70+
text = splitSentences(text);
71+
chunks = [];
72+
currentChunk = "";
73+
currentChunkSize = 0;
74+
75+
% Iterating through the sentences to aggregate them into chunks until the chunk
76+
% attains the predefined size, after which a new chunk is started
77+
for i=1:length(text)
78+
newChunkSize = currentChunkSize + doclength(text(i));
79+
if newChunkSize < chunkSize
80+
currentChunkSize = currentChunkSize + doclength(text(i));
81+
currentChunk = currentChunk + " " + joinWords(text(i));
82+
else
83+
chunks = [chunks; currentChunk]; %#ok
84+
currentChunkSize = doclength(text(i));
85+
currentChunk = joinWords(text(i));
86+
end
87+
end
88+
end

examples/ExampleSummarization.mlx

-2.76 KB
Binary file not shown.

openAIMessages.m

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,7 @@
185185
else
186186
% function_call message
187187
functionCall = struct("name", contentOrfunctionName, "arguments", arguments);
188-
newMessage = struct("role", "assistant", "content", [], "function_call", functionCall);
188+
newMessage = struct("role", "assistant", "content", "", "function_call", functionCall);
189189
end
190190

191191
if isempty(this.Messages)

0 commit comments

Comments
 (0)