Skip to content

Commit 1f706c9

Browse files
authored
Add files via upload
Updated the response object to cope with changes to the json output. Removed legacy textcompletion endpoint.
1 parent 9d21bf0 commit 1f706c9

File tree

8 files changed

+97
-331
lines changed

8 files changed

+97
-331
lines changed

OpenAIFrameworkDemo.xlsm

-14 KB
Binary file not shown.

README.md

Lines changed: 0 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -52,30 +52,6 @@ Public Sub TestSimpleOpenAI()
5252
End Sub
5353
```
5454

55-
### Text Completion API
56-
57-
```
58-
Public Sub TestTextCompletionSimpleOpenAI()
59-
60-
Dim oOpenAI As clsOpenAI
61-
Dim oResponse As clsOpenAIResponse
62-
63-
Set oOpenAI = New clsOpenAI
64-
65-
oOpenAI.API_KEY = "<API_KEY>"
66-
67-
Set oResponse = oOpenAI.TextCompletion("Write a Haiku about a dinosaur that loves to code!")
68-
69-
If Not oResponse Is Nothing Then
70-
Debug.Print (oResponse.TextContent)
71-
End If
72-
73-
Set oResponse = Nothing
74-
Set oOpenAI = Nothing
75-
76-
End Sub
77-
```
78-
7955
### DALL-E Image Creation
8056

8157
```

clsOpenAI.cls

Lines changed: 0 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -50,18 +50,14 @@ Private mlngCallsToAPICount As Long
5050

5151
'OpenAI API Endpoints
5252
Private Const API_ENDPOINT_CHAT As String = "https://api.openai.com/v1/chat/completions"
53-
Private Const API_ENDPOINT_COMPLETIONS As String = "https://api.openai.com/v1/completions"
5453
Private Const API_ENDPOINT_IMAGE_CREATION As String = "https://api.openai.com/v1/images/generations"
5554

5655
Private Const DEFAULT_LOCAL_LOCATION As String = "C:\Users\Public\Downloads\"
5756
Private mstrFolderToSave As String
5857

5958
'More models can be found here: https://platform.openai.com/docs/models/overview
6059
Private Const DEFAULT_CHAT_MODEL As String = "gpt-3.5-turbo"
61-
Private Const DEFAULT_TEXT_COMPLETION_MODEL As String = "text-davinci-003"
62-
6360
Private Const DEFAULT_CHAT_TOKENS_COUNT As Integer = 512
64-
Private Const DEFAULT_TEXT_TOKENS_COUNT As Integer = 1024
6561

6662
'Project constants
6763
Private Const UNASSIGNED_VALUE As Integer = -1
@@ -236,13 +232,6 @@ On Error GoTo ERR_HANDLER:
236232
oResponse.ParseChatJSON (strResponseJson)
237233
Set GetResponseFromAPI = oResponse
238234

239-
ElseIf strEndPoint = API_ENDPOINT_COMPLETIONS Then
240-
241-
'GPT3 and earlier
242-
Set oResponse = New clsOpenAIResponse
243-
oResponse.ParseTextCompletionJSON (strResponseJson)
244-
Set GetResponseFromAPI = oResponse
245-
246235
ElseIf strEndPoint = API_ENDPOINT_IMAGE_CREATION Then
247236

248237
'DALL-E image generator
@@ -354,37 +343,6 @@ Public Function ChatCompletion(ByVal oMessages As clsOpenAIMessages) As clsOpenA
354343
End Function
355344

356345

357-
Public Function TextCompletion(ByVal strPrompt As String) As clsOpenAIResponse
358-
'Purpose: This is for OpenAI's Text Completion API
359-
360-
Set TextCompletion = Nothing
361-
362-
If Not IsAPIKeyValid Then
363-
mobjLogger.PrintCriticalMessage MESSAGE_INVALID_API_KEY, True
364-
Exit Function
365-
End If
366-
367-
If strPrompt = Empty Then
368-
Exit Function
369-
End If
370-
371-
mobjRequest.prompt = strPrompt
372-
373-
If mobjRequest.Model = Empty Then
374-
mobjRequest.Model = DEFAULT_TEXT_COMPLETION_MODEL
375-
End If
376-
377-
If mobjRequest.MaxTokens = UNASSIGNED_VALUE Then
378-
mobjRequest.MaxTokens = DEFAULT_TEXT_TOKENS_COUNT
379-
End If
380-
381-
Log mobjRequest.GetTextCompletionSendToAPIJsonString
382-
383-
Set TextCompletion = GetResponseFromAPI(mobjRequest.GetTextCompletionSendToAPIJsonString, API_ENDPOINT_COMPLETIONS)
384-
385-
End Function
386-
387-
388346
Private Sub Class_Initialize()
389347

390348
mstrMSXMLType = MSXML_DEFAULT

clsOpenAILogger.cls

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,8 @@ Private Sub Class_Terminate()
6060
Set mobjClass = Nothing
6161
End Sub
6262

63-
Public Sub SetClass(ByVal Obj As IOpenAINameProvider)
64-
Set mobjClass = Obj
63+
Public Sub SetClass(ByVal obj As IOpenAINameProvider)
64+
Set mobjClass = obj
6565
End Sub
6666

6767

clsOpenAIRequest.cls

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ End Function
6060

6161

6262
Private Function IOpenAINameProvider_ToString() As String
63-
IOpenAINameProvider_ToString = "chat json=" & Me.GetChatSendToAPIJsonString & " | " & "text json=" & Me.GetTextCompletionSendToAPIJsonString
63+
IOpenAINameProvider_ToString = "chat json=" & Me.GetChatSendToAPIJsonString
6464
End Function
6565

6666

@@ -172,11 +172,6 @@ Public Function GetChatSendToAPIJsonString() As String
172172
End Function
173173

174174

175-
Public Function GetTextCompletionSendToAPIJsonString() As String
176-
GetTextCompletionSendToAPIJsonString = "{""model"": """ & mstrModel & """, ""prompt"": """ & mstrPrompt & """, ""max_tokens"": " & mlngMaxTokens & ", ""temperature"": " & mdblTemperature & "}"
177-
End Function
178-
179-
180175
Public Function GetDalleImageSendToAPIJsonString() As String
181176
Dim strImageSize As String
182177
strImageSize = Me.GetImageDimensionLabel()

clsOpenAIResponse.cls

Lines changed: 44 additions & 174 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ Private mintIndex As Integer
5050
Private mstrText As String
5151
Private mstrLogprobs As String
5252
Private mstrSavedFile As String
53-
53+
Private mstrJson As String
5454

5555
Private Function IOpenAINameProvider_GetClassName() As String
5656
IOpenAINameProvider_GetClassName = "clsOpenAIResponse"
@@ -68,6 +68,10 @@ Private Function IOpenAINameProvider_ToString() As String
6868
End Function
6969

7070

71+
Public Property Get Json() As String
72+
Json = mstrJson
73+
End Property
74+
7175
Public Property Get Id() As String
7276
Id = mstrId
7377
End Property
@@ -132,8 +136,10 @@ Public Function IsExistSavedLocalFile() As Boolean
132136
IsExistSavedLocalFile = IIf(Len(Dir(mstrSavedFile)) > 0, True, False)
133137
End Function
134138

139+
135140
Private Sub Class_Initialize()
136141
' Initialize the variables
142+
mstrJson = Empty
137143
mstrId = Empty
138144
mstrObject = Empty
139145
mstrCreated = 0
@@ -152,183 +158,49 @@ End Sub
152158

153159

154160
Public Sub ParseChatJSON(ByVal strJson As String)
155-
'Purpose: This method is for parsing OpenAI's strJson response from it's Chat End point
161+
' Purpose: This method is for parsing OpenAI's strJson response from its Chat Endpoint
162+
163+
'Allow for the full response to be accessed by downstream clients using the class
164+
mstrJson = strJson
165+
166+
' Extract each property from the JSON string
167+
mstrId = ExtractJsonValue(strJson, """id"": """, """")
168+
mstrObject = ExtractJsonValue(strJson, """object"": """, """")
169+
mstrCreated = CLng(ExtractJsonValue(strJson, """created"": ", ","))
170+
mstrModel = ExtractJsonValue(strJson, """model"": """, """")
171+
mintPromptTokens = CInt(ExtractJsonValue(strJson, """prompt_tokens"": ", ","))
172+
mintCompletionTokens = CInt(ExtractJsonValue(strJson, """completion_tokens"": ", ","))
173+
mintTotalTokens = CInt(ExtractJsonValue(strJson, """total_tokens"": ", "}"))
174+
175+
' Extract the nested message information
176+
Dim messageJson As String
177+
messageJson = ExtractJsonValue(strJson, """message"": {", "}")
178+
mstrMessageRole = ExtractJsonValue(messageJson, """role"": """, """")
179+
mstrMessageContent = ExtractJsonValue(messageJson, """content"": """, """")
180+
mstrMessageContent = Replace(mstrMessageContent, "\""", """") ' Replace escaped quotes with actual quotes
181+
mstrFinishReason = ExtractJsonValue(strJson, """finish_reason"": """, """")
182+
mintIndex = CInt(ExtractJsonValue(strJson, """index"": ", ","))
156183

157-
Dim intStartPos As Integer
158-
Dim intEndPos As Integer
159-
Dim strTemp As String
160-
161-
' Extract "id"
162-
If InStr(1, strJson, """id"":""") > 0 Then
163-
intStartPos = InStr(1, strJson, """id"":""") + Len("""id"":""")
164-
intEndPos = InStr(intStartPos, strJson, """")
165-
mstrId = Trim(Mid(strJson, intStartPos, intEndPos - intStartPos))
166-
End If
167-
168-
' Extract "object"
169-
If InStr(1, strJson, """object"":""") > 0 Then
170-
intStartPos = InStr(1, strJson, """object"":""") + Len("""object"":""")
171-
intEndPos = InStr(intStartPos, strJson, """")
172-
mstrObject = Trim(Mid(strJson, intStartPos, intEndPos - intStartPos))
173-
End If
174-
175-
' Extract "created"
176-
If InStr(1, strJson, """created"":") > 0 Then
177-
intStartPos = InStr(1, strJson, """created"":") + Len("""created"":")
178-
intEndPos = InStr(intStartPos, strJson, ",")
179-
mstrCreated = CLng(Trim(Mid(strJson, intStartPos, intEndPos - intStartPos)))
180-
End If
181-
182-
' Extract "model"
183-
If InStr(1, strJson, """model"":""") > 0 Then
184-
intStartPos = InStr(1, strJson, """model"":""") + Len("""model"":""")
185-
intEndPos = InStr(intStartPos, strJson, """")
186-
mstrModel = Trim(Mid(strJson, intStartPos, intEndPos - intStartPos))
187-
End If
188-
189-
' Extract "prompt_tokens"
190-
If InStr(1, strJson, """prompt_tokens"":") > 0 Then
191-
intStartPos = InStr(1, strJson, """prompt_tokens"":") + Len("""prompt_tokens"":")
192-
intEndPos = InStr(intStartPos, strJson, ",")
193-
mintPromptTokens = CInt(Trim(Mid(strJson, intStartPos, intEndPos - intStartPos)))
194-
End If
195-
196-
' Extract "completion_tokens"
197-
If InStr(1, strJson, """completion_tokens"":") > 0 Then
198-
intStartPos = InStr(1, strJson, """completion_tokens"":") + Len("""completion_tokens"":")
199-
intEndPos = InStr(intStartPos, strJson, ",")
200-
mintCompletionTokens = CInt(Trim(Mid(strJson, intStartPos, intEndPos - intStartPos)))
201-
End If
202-
203-
' Extract "total_tokens"
204-
If InStr(1, strJson, """total_tokens"":") > 0 Then
205-
intStartPos = InStr(1, strJson, """total_tokens"":") + Len("""total_tokens"":")
206-
intEndPos = InStr(intStartPos, strJson, "}")
207-
mintTotalTokens = CInt(Trim(Mid(strJson, intStartPos, intEndPos - intStartPos)))
208-
End If
209-
210-
' Extract "message_role"
211-
If InStr(1, strJson, """role"":""") > 0 Then
212-
intStartPos = InStr(1, strJson, """role"":""") + Len("""role"":""")
213-
intEndPos = InStr(intStartPos, strJson, """")
214-
mstrMessageRole = Trim(Mid(strJson, intStartPos, intEndPos - intStartPos))
215-
End If
216-
217-
' Extract "message_content"
218-
If InStr(1, strJson, """content"":""") > 0 Then
219-
intStartPos = InStr(1, strJson, """content"":""") + Len("""content"":""")
220-
intEndPos = InStr(intStartPos, strJson, """},") ' end position is now before "}," sequence
221-
strTemp = Mid(strJson, intStartPos, intEndPos - intStartPos)
222-
strTemp = Replace(strTemp, "\""", """") ' Replace escaped quotes with actual quotes
223-
mstrMessageContent = Trim(strTemp)
224-
End If
225-
226-
227-
' Extract "finish_reason"
228-
If InStr(1, strJson, """finish_reason"":""") > 0 Then
229-
intStartPos = InStr(1, strJson, """finish_reason"":""") + Len("""finish_reason"":""")
230-
intEndPos = InStr(intStartPos, strJson, """")
231-
mstrFinishReason = Trim(Mid(strJson, intStartPos, intEndPos - intStartPos))
232-
End If
233-
234-
' Extract "index"
235-
If InStr(1, strJson, """index"":") > 0 Then
236-
intStartPos = InStr(1, strJson, """index"":") + Len("""index"":")
237-
intEndPos = InStr(intStartPos, strJson, "}")
238-
mintIndex = CInt(Trim(Mid(strJson, intStartPos, intEndPos - intStartPos)))
239-
End If
240184
End Sub
241185

242186

243-
Public Sub ParseTextCompletionJSON(ByVal strJson As String)
244-
'Purpose: This method is for parsing OpenAI's strJson from it's text completion end point
187+
Private Function ExtractJsonValue(ByVal Json As String, ByVal key As String, ByVal delimiter As String) As String
188+
' Find the start position of the key
189+
Dim startPos As Integer
190+
startPos = InStr(Json, key)
191+
If startPos = 0 Then Exit Function
245192

246-
Dim intStartPos As Integer
247-
Dim intEndPos As Integer
248-
Dim strTemp As String
249-
250-
' Extract "id"
251-
If InStr(1, strJson, """id"":""") > 0 Then
252-
intStartPos = InStr(1, strJson, """id"":""") + Len("""id"":""")
253-
intEndPos = InStr(intStartPos, strJson, """")
254-
mstrId = Trim(Mid(strJson, intStartPos, intEndPos - intStartPos))
255-
End If
256-
257-
' Extract "object"
258-
If InStr(1, strJson, """object"":""") > 0 Then
259-
intStartPos = InStr(1, strJson, """object"":""") + Len("""object"":""")
260-
intEndPos = InStr(intStartPos, strJson, """")
261-
mstrObject = Trim(Mid(strJson, intStartPos, intEndPos - intStartPos))
262-
End If
263-
264-
' Extract "created"
265-
If InStr(1, strJson, """created"":") > 0 Then
266-
intStartPos = InStr(1, strJson, """created"":") + Len("""created"":")
267-
intEndPos = InStr(intStartPos, strJson, ",")
268-
mstrCreated = CLng(Trim(Mid(strJson, intStartPos, intEndPos - intStartPos)))
269-
End If
270-
271-
' Extract "model"
272-
If InStr(1, strJson, """model"":""") > 0 Then
273-
intStartPos = InStr(1, strJson, """model"":""") + Len("""model"":""")
274-
intEndPos = InStr(intStartPos, strJson, """")
275-
mstrModel = Trim(Mid(strJson, intStartPos, intEndPos - intStartPos))
276-
End If
277-
278-
' Extract "prompt_tokens"
279-
If InStr(1, strJson, """prompt_tokens"":") > 0 Then
280-
intStartPos = InStr(1, strJson, """prompt_tokens"":") + Len("""prompt_tokens"":")
281-
intEndPos = InStr(intStartPos, strJson, ",")
282-
mintPromptTokens = CInt(Trim(Mid(strJson, intStartPos, intEndPos - intStartPos)))
283-
End If
284-
285-
' Extract "completion_tokens"
286-
If InStr(1, strJson, """completion_tokens"":") > 0 Then
287-
intStartPos = InStr(1, strJson, """completion_tokens"":") + Len("""completion_tokens"":")
288-
intEndPos = InStr(intStartPos, strJson, ",")
289-
mintCompletionTokens = CInt(Trim(Mid(strJson, intStartPos, intEndPos - intStartPos)))
290-
End If
291-
292-
' Extract "total_tokens"
293-
If InStr(1, strJson, """total_tokens"":") > 0 Then
294-
intStartPos = InStr(1, strJson, """total_tokens"":") + Len("""total_tokens"":")
295-
intEndPos = InStr(intStartPos, strJson, "}")
296-
mintTotalTokens = CInt(Trim(Mid(strJson, intStartPos, intEndPos - intStartPos)))
297-
End If
298-
299-
' Extract "text"
300-
If InStr(1, strJson, """text"":""") > 0 Then
301-
intStartPos = InStr(1, strJson, """text"":""") + Len("""text"":""")
302-
intEndPos = InStr(intStartPos, strJson, """,""") ' end position is now before the sequence ","
303-
strTemp = Mid(strJson, intStartPos, intEndPos - intStartPos)
304-
strTemp = Replace(strTemp, "\""", """") ' Replace escaped quotes with actual quotes
305-
mstrText = Trim(strTemp)
306-
End If
307-
308-
' Extract "logprobs"
309-
If InStr(1, strJson, """logprobs"":") > 0 Then
310-
intStartPos = InStr(1, strJson, """logprobs"":") + Len("""logprobs"":")
311-
intEndPos = InStr(intStartPos, strJson, ",") ' end position is now before the sequence ","
312-
strTemp = Mid(strJson, intStartPos, intEndPos - intStartPos)
313-
strTemp = Replace(strTemp, "\""", """") ' Replace escaped quotes with actual quotes
314-
mstrLogprobs = Trim(strTemp)
315-
End If
193+
' Adjust start position to start of the value
194+
startPos = startPos + Len(key)
316195

317-
318-
' Extract "finish_reason"
319-
If InStr(1, strJson, """finish_reason"":""") > 0 Then
320-
intStartPos = InStr(1, strJson, """finish_reason"":""") + Len("""finish_reason"":""")
321-
intEndPos = InStr(intStartPos, strJson, """")
322-
mstrFinishReason = Trim(Mid(strJson, intStartPos, intEndPos - intStartPos))
323-
End If
324-
325-
' Extract "index"
326-
If InStr(1, strJson, """index"":") > 0 Then
327-
intStartPos = InStr(1, strJson, """index"":") + Len("""index"":")
328-
intEndPos = InStr(intStartPos, strJson, ",")
329-
mintIndex = CInt(Trim(Mid(strJson, intStartPos, intEndPos - intStartPos)))
330-
End If
331-
End Sub
196+
' Find the end position of the value
197+
Dim endPos As Integer
198+
endPos = InStr(startPos, Json, delimiter)
199+
If endPos = 0 Then Exit Function
200+
201+
' Extract the value
202+
ExtractJsonValue = Mid(Json, startPos, endPos - startPos)
203+
End Function
332204

333205

334206
Public Function GetFileNameFromImageURL(ByVal strImageUrl As String)
@@ -381,5 +253,3 @@ Public Function GetImageURLFromImageCreationJSON(ByVal strResponseJson As String
381253

382254
End Function
383255

384-
385-

0 commit comments

Comments
 (0)