﻿B4J=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=9.96
@EndOfDesignText@
Sub Class_Globals
	Private fx As JFX
	Private mtoken As String
	Private morganization As String
	Private mdownloadpath As String
	Private massistantID As String
	
	Public regelwerkID As String = "file-sCryP7pgGhB43HmmzQ06wGuc"
	Public assistantBlimsKatzeID As String = "asst_TQdhpQHjZAmzjrUu38vBH3eV"
	Public mlogfilepath As String	
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize(organization As String, downloadpath As String)
	'mtoken = "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"
	morganization = organization
	mdownloadpath = downloadpath
	mtoken = GetEnvironmentVariable("OpenAItoken", "")
	If mtoken<>"" Then
		Log($"Token set from Environment. -> ${mtoken.SubString2(0,10)}[..]"$)
	End If
End Sub
public Sub getAssistant() As String
	Return massistantID
End Sub
public Sub setAssistant(assistant_id As String)
	massistantID = assistant_id
End Sub
public Sub getLogfilepath() As String
	Return massistantID
End Sub
public Sub setLogfilepath(path As String)
	mlogfilepath = path
End Sub

' "id": "chatcmpl-97O3aAXaGVnlLBt7Go8AHZ9F2ORug"

'Documentation: <link>CreateAssistant|https://platform.openai.com/docs/api-reference/assistants</link>
Public Sub CreateAssistant(name As String, model As String, instructions As String, tools As List, fileIDs As List, metadata As Map) As ResumableSub
	'For complete documentation you should look at:
	'https://platform.openai.com/docs/api-reference/assistants
 
	Try
		'Dim model As String = "gpt-3.5-turbo"
		Dim m As Map = CreateMap("model": model, "name":name,"instructions":instructions)
		'Dim tools As List
		'tools.Initialize
		'tools.Add(CreateMap("type": "retrieval"))
		If tools.IsInitialized And tools.Size > 0 Then
			m.Put("tools",tools)
		End If
		If fileIDs.IsInitialized And fileIDs.Size > 0 Then
			m.Put("file_ids",fileIDs)			
		End If
		If metadata.IsInitialized Then
			m.Put("metadata",metadata)
		End If
		
		Dim jgen As JSONGenerator
		jgen.Initialize(m)
  
		'Uncomment this line if you want to see raw input string
		'Log(jgen.ToString)

		Dim response As String
  
		Dim req As HttpJob
		req.Initialize("", Me)
		req.PostString("https://api.openai.com/v1/assistants", jgen.ToString)
		req.GetRequest.SetHeader("Authorization", "Bearer "&mtoken)
		' ccess the Assistants API. Please try again by setting the header 'OpenAI-Beta: assistants=v1'.",
		req.GetRequest.SetHeader("OpenAI-Beta", "assistants=v1")
		
		'And if you have an organisation key...
		'If your account default organisation is "Personal" then you can supply
		'a blank organisation key - or just comment this line out
		'req.GetRequest.SetHeader("OpenAI-Organization", "org-xxx")
		req.GetRequest.SetHeader("OpenAI-Organization", morganization)
		req.GetRequest.SetContentType("application/json")
  
		Wait For (req) JobDone(req As HttpJob)
  
		If req.Success Then
      
			'Uncomment this line if you want to see raw JSON response
			Dim res As String = req.GetString
			If mlogfilepath<> "" Then
				File.WriteString(mlogfilepath,$"Assistant-${DateTime.Now}.json"$,res)
			End If
			response = res  
		Else
      
			response = "ERROR: " & req.ErrorMessage
  
		End If
  
		req.Release
 
	Catch
  
		response = "ERROR: " & LastException
 
	End Try
 
	Return response

End Sub
'Documentation: <link>CreateAssistantFile|https://platform.openai.com/docs/api-reference/assistants/createAssistantFile</link>
Public Sub CreateAssistantFile(assistant_id As String, fileID As String) As ResumableSub
	'For complete documentation you should look at:
	'https://platform.openai.com/docs/api-reference/assistants/createAssistantFile
 
	Try
		Dim m As Map = CreateMap("file_id": fileID)
		
		Dim jgen As JSONGenerator
		jgen.Initialize(m)
  
		'Uncomment this line if you want to see raw input string
		'Log(jgen.ToString)

		Dim response As String
  
		Dim req As HttpJob
		req.Initialize("", Me)
		req.PostString($"https://api.openai.com/v1/assistants/${assistant_id}/files"$, jgen.ToString)
		req.GetRequest.SetHeader("Authorization", "Bearer "&mtoken)
		' ccess the Assistants API. Please try again by setting the header 'OpenAI-Beta: assistants=v1'.",
		req.GetRequest.SetHeader("OpenAI-Beta", "assistants=v1")
		
		'And if you have an organisation key...
		'If your account default organisation is "Personal" then you can supply
		'a blank organisation key - or just comment this line out
		'req.GetRequest.SetHeader("OpenAI-Organization", "org-xxx")
		req.GetRequest.SetHeader("OpenAI-Organization", morganization)
		req.GetRequest.SetContentType("application/json")
  
		Wait For (req) JobDone(req As HttpJob)
  
		If req.Success Then
      
			'Uncomment this line if you want to see raw JSON response
			Dim res As String = req.GetString
			Log(res)
  
		Else
      
			response = "ERROR: " & req.ErrorMessage
  
		End If
  
		req.Release
 
	Catch
  
		response = "ERROR: " & LastException
 
	End Try
 
	Return response

End Sub

'Documentation: <link>ModifyAssistant|https://platform.openai.com/docs/api-reference/assistants/modifyAssistant</link>
Public Sub ModifyAssistant(assistID As String, model As String, name As String, description As String, instructions As String) As ResumableSub
 	Dim assistID As String = assistantBlimsKatzeID
	'For complete documentation you should look at:
	'https://platform.openai.com/docs/api-reference/assistants/modifyAssistant
 
	Try
		'Dim model As String = "gpt-3.5-turbo"
		'Dim m As Map = CreateMap("model": model, "name":"BlimsKatze2","instructions":"Du bist ein höflicher Assistent. Wenn Du eine Frage gestellt bekommst lieferst du den Eintrag aus den Dateien mit der höchsten Relevanz zurück.")
		Dim m As Map = CreateMap("model": model)
		m.Put("name",name)
		m.Put("description",description)
		m.Put("instructions",instructions)

		Dim tools As List
		tools.Initialize
		tools.Add(CreateMap("type": "retrieval"))

		m.Put("tools",tools)
		Dim jgen As JSONGenerator
		jgen.Initialize(m)
  
		'Uncomment this line if you want to see raw input string
		'Log(jgen.ToString)

		Dim response As String
  
		Dim req As HttpJob
		req.Initialize("", Me)
		req.PostString($"https://api.openai.com/v1/assistants/${assistID}"$, jgen.ToString)
		req.GetRequest.SetHeader("Authorization", "Bearer "&mtoken)
		' ccess the Assistants API. Please try again by setting the header 'OpenAI-Beta: assistants=v1'.",
		req.GetRequest.SetHeader("OpenAI-Beta", "assistants=v1")
		
		'And if you have an organisation key...
		'If your account default organisation is "Personal" then you can supply
		'a blank organisation key - or just comment this line out
		'req.GetRequest.SetHeader("OpenAI-Organization", "org-xxx")
		req.GetRequest.SetHeader("OpenAI-Organization", "org-UcpwxkbVjyKMTjQMOR9tyijE")
		req.GetRequest.SetContentType("application/json")
  
		Wait For (req) JobDone(req As HttpJob)
  
		If req.Success Then
      
			'Uncomment this line if you want to see raw JSON response
			Dim res As String = req.GetString
			Log(res)
			Dim parser As JSONParser
			parser.Initialize(res)
  
		Else
      
			response = "ERROR: " & req.ErrorMessage
  
		End If
  
		req.Release
 
	Catch
  
		response = "ERROR: " & LastException
 
	End Try
 
	Return response

End Sub
'Documentation: <link>ListAssistants|https://platform.openai.com/docs/api-reference/assistants/listAssistants</link>
Public Sub ListAssistants() As ResumableSub
 
	'For complete documentation you should look at:
	'https://platform.openai.com/docs/api-reference/assistants/listAssistants
 
	Try
  

		Dim response As String
  
		Dim req As HttpJob
		req.Initialize("", Me)
		req.Download($"https://api.openai.com/v1/assistants?order=desc&limit=20"$)
		req.GetRequest.InitializeGet($"https://api.openai.com/v1/assistants?order=desc&limit=20"$)
		req.GetRequest.SetHeader("Authorization", "Bearer "&mtoken)
		req.GetRequest.SetHeader("OpenAI-Beta", "assistants=v1")
		'req.GetRequest.SetContentType("application/json")

		Wait For (req) JobDone(req As HttpJob)
  
		If req.Success Then
      
			'Uncomment this line if you want to see raw JSON response
			Dim res As String = req.GetString
			response = res
			'{
			'"object": "list",
			'"data": [
			'{
			'"id": "asst_TQdhpQHjZAmzjrUu38vBH3eV",
			'"object": "assistant",
			'"created_at": 1711707288,
			'"name": "BlimsKatze",
			'"description": "BlimsKatze zitiert aus dem Regelwerk.",
			'"model": "gpt-3.5-turbo",
			'"instructions": "Du bist ein höflicher Assistent. Wenn Du eine Frage gestellt bekommst lieferst du den Wer aus Content vom Eintrag aus den Dateien mit der höchsten Relevanz im feld Kategorie zurück.",
			'"tools": [
			'{
			'"type": "retrieval"
			'}
			'],
			'"file_ids": [
			'"file-FvTD7W2B5Wt4XC5BIh95L9LQ"
			'],
			'"metadata": {}
			'}
			'],
			'"first_id": "asst_TQdhpQHjZAmzjrUu38vBH3eV",
			'"last_id": "asst_TQdhpQHjZAmzjrUu38vBH3eV",
			'"has_more": False
			'}
			
			'Log(res)
			'Dim parser As JSONParser
			'parser.Initialize(res)
  
		Else
      
			response = "ERROR: " & req.ErrorMessage
  
		End If
  
		req.Release
 
	Catch
  
		response = "ERROR: " & LastException
 
	End Try
 
	Return response

End Sub

'Documentation: <link>ListAssistantFiles|https://platform.openai.com/docs/api-reference/assistants/listAssistantFiles</link>
Public Sub ListAssistantFiles(assistant_id As String) As ResumableSub
 
	Try
  

		Dim response As String
  
		Dim req As HttpJob
		req.Initialize("", Me)
		req.Download($"https://api.openai.com/v1/assistants/${assistant_id}/files"$)
		req.GetRequest.InitializeGet($"https://api.openai.com/v1/assistants/${assistant_id}/files"$)
		req.GetRequest.SetHeader("Authorization", "Bearer "&mtoken)
		req.GetRequest.SetHeader("OpenAI-Beta", "assistants=v1")
		'And if you have an organisation key...
		'If your account default organisation is "Personal" then you can supply
		'a blank organisation key - or just comment this line out
		req.GetRequest.SetHeader("OpenAI-Organization", morganization)
		'req.GetRequest.SetContentType("application/json")
  
		Wait For (req) JobDone(req As HttpJob)
  
		If req.Success Then
      
			'Uncomment this line if you want to see raw JSON response
			Dim res As String = req.GetString
			response = res
			'Log(res)
			'Dim parser As JSONParser
			'parser.Initialize(res)
			'{
			'"object": "list",
			'"data": [
			'{
			'"id": "file-FvTD7W2B5Wt4XC5BIh95L9LQ",
			'"object": "assistant.file",
			'"created_at": 1711808146,
			'"assistant_id": "asst_TQdhpQHjZAmzjrUu38vBH3eV"
			'}
			'],
			'"first_id": "file-FvTD7W2B5Wt4XC5BIh95L9LQ",
			'"last_id": "file-FvTD7W2B5Wt4XC5BIh95L9LQ",
			'"has_more": False
			'}
			
		Else
      
			response = "ERROR: " & req.ErrorMessage
  
		End If
  
		req.Release
 
	Catch
  
		response = "ERROR: " & LastException
 
	End Try
 
	Return response

End Sub

'Documentation: <link>UploadFile|https://platform.openai.com/docs/api-reference/files/create</link>
Public Sub UploadFile(fpath As String, ffilename As String, fpurpose As String) As ResumableSub
	Try
  
		Dim m As Map = CreateMap("purpose": fpurpose)
		Dim response As String
  
		Dim f As MultipartFileData
		f.Initialize
		f.Dir = fpath
		f.FileName = ffilename
		f.KeyName = "file"
		Dim files As List
		files.Initialize
		files.Add(f)
		
		Dim req As HttpJob
		req.Initialize("", Me)
		
		req.PostMultipart("https://api.openai.com/v1/files",m,files)
		req.GetRequest.SetHeader("Authorization", "Bearer "&mtoken)
		'And if you have an organisation key...
		'If your account default organisation is "Personal" then you can supply
		'a blank organisation key - or just comment this line out
		'req.GetRequest.SetHeader("OpenAI-Organization", "org-xxx")
		req.GetRequest.SetHeader("OpenAI-Organization", morganization)
		'req.GetRequest.SetContentType("application/json")
  
		Wait For (req) JobDone(req As HttpJob)
  
		If req.Success Then
      
			'Uncomment this line if you want to see raw JSON response
			Dim res As String = req.GetString
			Log(res)
			'{
			'"object": "file",
			'"id": "file-CmmdoryU4ZYdax25iVJ3bKzQ",
			'"purpose": "assistants",
			'"filename": "regelwerk.jsonl",
			'"bytes": 5543,
			'"created_at": 1711830706,
			'"status": "processed",
			'"status_details": Null
			'}
			
  
		Else
      
			response = "ERROR: " & req.ErrorMessage
  
		End If
  
		req.Release
 
	Catch
  
		response = "ERROR: " & LastException
 
	End Try
 
	Return response

End Sub



'Documentation: <link>Query|https://platform.openai.com/docs/api-reference/chat</link>
Public Sub ChatCompletion(uniqueuser As String, system_string As String, query_string As String) As ResumableSub
 
	'For complete documentation you should look at:
	'https://platform.openai.com/docs/api-reference/chat
 
	Try
  

		Dim model As String = "gpt-3.5-turbo"
		Dim msgs As List
		msgs.Initialize
		msgs.Add(CreateMap("role":"system","content":system_string))
		msgs.Add(CreateMap("role":"user","content":query_string))
		'msgs.Add(CreateMap("role":"user","content":"Füge auch ein schönes Reiseziel in Deutschland in die Antwort mit auf."))		
		'msgs.Add(CreateMap("role":"user","content":"Füge auch ein Deutsche Biersorte als Empfehlung mit auf."))		
		Dim m As Map = CreateMap("model": model, "user":uniqueuser, "messages":msgs)
		Dim jgen As JSONGenerator
		jgen.Initialize(m)
  

		'Uncomment this line if you want to see raw input string
		Log(jgen.ToString)

  
		Dim response As String
  
		Dim req As HttpJob
		req.Initialize("", Me)
		req.PostString("https://api.openai.com/v1/chat/completions", jgen.ToString)
		req.GetRequest.SetHeader("Authorization", "Bearer "&mtoken)
		'And if you have an organisation key...
		'If your account default organisation is "Personal" then you can supply
		'a blank organisation key - or just comment this line out
		'req.GetRequest.SetHeader("OpenAI-Organization", "org-xxx")
		req.GetRequest.SetHeader("OpenAI-Organization", morganization)
		req.GetRequest.SetContentType("application/json")
  
		Wait For (req) JobDone(req As HttpJob)
  
		If req.Success Then
      
			'Uncomment this line if you want to see raw JSON response
			Log(req.GetString)
			Dim res As String = req.GetString
			response = res
			If mlogfilepath<> "" Then
				File.WriteString(mlogfilepath,$"Chatcompletion-${DateTime.Now}.json"$,res)
			End If

		Else
      
			response = "ERROR: " & req.ErrorMessage
  
		End If
  
		req.Release
 
	Catch
  
		response = "ERROR: " & LastException
 
	End Try
 
	Return response

End Sub


'Documentation: <link>CreateThreadAndRun|https://platform.openai.com/docs/api-reference/runs/createThreadAndRun</link>
Public Sub CreateThreadAndRun(assistant_id As String, query_string As String, fileids As List) As ResumableSub
 
	'For complete documentation you should look at:
	'https://platform.openai.com/docs/api-reference/runs/createThreadAndRun
 
	Try
  
		' Consider using 'gpt-4-turbo-preview', 'gpt-3.5-turbo', or a later model.",
		Dim model As String = "'gpt-3.5-turbo"
		Dim msgs As List
		msgs.Initialize
		'fileids
		Dim usermap As Map = CreateMap("role":"user","content":query_string)
		If fileids.IsInitialized And fileids.Size>0 Then
			usermap.Put("file_ids",fileids)
		End If
		msgs.Add(usermap)
		Dim thread As Map
		thread.Initialize
		thread.Put("messages",msgs)
		
		Dim m As Map = CreateMap("model":model,"assistant_id": assistant_id, "thread":thread)
		m.Put("stream",True)

		Dim jgen As JSONGenerator
		jgen.Initialize(m)
  

		'Uncomment this line if you want to see raw input string
		Log(jgen.ToString)

  
		Dim response As String
  
		Dim req As HttpJob
		req.Initialize("", Me)
		req.PostString("https://api.openai.com/v1/threads/runs", jgen.ToString)
		req.GetRequest.SetHeader("Authorization", "Bearer "&mtoken)
		'And if you have an organisation key...
		'If your account default organisation is "Personal" then you can supply
		'a blank organisation key - or just comment this line out
		'req.GetRequest.SetHeader("OpenAI-Organization", "org-xxx")
		req.GetRequest.SetHeader("OpenAI-Organization", morganization)
		req.GetRequest.SetHeader("OpenAI-Beta", "assistants=v1")
		req.GetRequest.SetContentType("application/json")
  
		Wait For (req) JobDone(req As HttpJob)
  
		If req.Success Then
      
			'Uncomment this line if you want to see raw JSON response
			Dim res As String = req.GetString
			'Log(res)
			response = res
			If mlogfilepath<> "" Then
				File.WriteString(mlogfilepath,$"Assistant-run-${DateTime.Now}.txt"$,res)
			End If

			'response = ParseJson(req.GetString)
  
		Else
      
			response = "ERROR: " & req.ErrorMessage
  
		End If
  
		req.Release
 
	Catch
  
		response = "ERROR: " & LastException
 
	End Try
 
	Return response

End Sub

'Documentation: <link>CreateThread|https://platform.openai.com/docs/api-reference/threads/createThread</link>
Public Sub CreateThread(system_string As String, query_string As String) As ResumableSub
 
	'For complete documentation you should look at:
	'https://platform.openai.com/docs/api-reference/threads/createThread
 
	Try
  

		'Dim model As String = "gpt-3.5-turbo"
		Dim msgs As List
		msgs.Initialize
		'msgs.Add(CreateMap("role":"system","content":system_string))
		msgs.Add(CreateMap("role":"user","content":query_string,"file_ids":Array As String(regelwerkID)))
		Dim thread As Map
		thread.Initialize
		thread.Put("messages",msgs)

		Dim jgen As JSONGenerator
		jgen.Initialize(thread)
  

		'Uncomment this line if you want to see raw input string
		Log(jgen.ToString)

  
		Dim response As String
  
		Dim req As HttpJob
		req.Initialize("", Me)
		req.PostString("https://api.openai.com/v1/threads", jgen.ToString)
		req.GetRequest.SetHeader("Authorization", "Bearer "&mtoken)
		'And if you have an organisation key...
		'If your account default organisation is "Personal" then you can supply
		'a blank organisation key - or just comment this line out
		'req.GetRequest.SetHeader("OpenAI-Organization", "org-xxx")
		req.GetRequest.SetHeader("OpenAI-Organization", morganization)
		req.GetRequest.SetHeader("OpenAI-Beta", "assistants=v1")
		req.GetRequest.SetContentType("application/json")
  
		Wait For (req) JobDone(req As HttpJob)
  
		If req.Success Then
      
			'Uncomment this line if you want to see raw JSON response
			Dim res As String = req.GetString
			Log(res)
			response = res
			If mlogfilepath<> "" Then
				File.WriteString(mlogfilepath,$"createthread-${DateTime.Now}.json"$,res)
			End If

			'response = ParseJson(req.GetString)
  
		Else
      
			response = "ERROR: " & req.ErrorMessage
  
		End If
  
		req.Release
 
	Catch
  
		response = "ERROR: " & LastException
 
	End Try
 
	Return response

End Sub

'Documentation: <link>RetrieveMessage|https://platform.openai.com/docs/api-reference/messages/getMessage</link>
Public Sub RetrieveMessage(thread_id As String, message_id As String) As ResumableSub
 
	'For complete documentation you should look at:
	'https://platform.openai.com/docs/api-reference/messages/getMessage
 

	Try
  

		Dim response As String
  
		Dim req As HttpJob
		req.Initialize("", Me)
		req.Download($"https://api.openai.com/v1/threads/${thread_id}/messages/${message_id}"$)
		req.GetRequest.SetHeader("Authorization", "Bearer "&mtoken)
		'And if you have an organisation key...
		'If your account default organisation is "Personal" then you can supply
		'a blank organisation key - or just comment this line out
		req.GetRequest.SetHeader("OpenAI-Organization", morganization)
		req.GetRequest.SetHeader("OpenAI-Beta", "assistants=v1")
		'req.GetRequest.SetContentType("application/json")
  
		Wait For (req) JobDone(req As HttpJob)
  
		If req.Success Then
      
			'Uncomment this line if you want to see raw JSON response
			Dim res As String = req.GetString
			Log(res)
			response = res

			'response = ParseJson(req.GetString)
  
		Else
      
			response = "ERROR: " & req.ErrorMessage
  
		End If
  
		req.Release
 
	Catch
  
		response = "ERROR: " & LastException
 
	End Try
 
	Return response

End Sub

'Documentation: <link>|</link>
Public Sub CreateRun(thread_id As String) As ResumableSub
 
	'For complete documentation you should look at:
	'https://platform.openai.com/docs/api-reference/runs/createRun
 
	Try
  

		'Dim model As String = "gpt-3.5-turbo"
		Dim run As Map
		run.Initialize
		run.Put("assistant_id",assistantBlimsKatzeID)
		run.Put("model","gpt-3.5-turbo")

		Dim jgen As JSONGenerator
		jgen.Initialize(run)
  

		'Uncomment this line if you want to see raw input string
		Log(jgen.ToString)

  
		Dim response As String
  
		Dim req As HttpJob
		req.Initialize("", Me)
		req.PostString($"https://api.openai.com/v1/threads/${thread_id}/runs"$, jgen.ToString)
		req.GetRequest.SetHeader("Authorization", "Bearer "&mtoken)
		'And if you have an organisation key...
		'If your account default organisation is "Personal" then you can supply
		'a blank organisation key - or just comment this line out
		'req.GetRequest.SetHeader("OpenAI-Organization", "org-xxx")
		req.GetRequest.SetHeader("OpenAI-Organization", morganization)
		req.GetRequest.SetHeader("OpenAI-Beta", "assistants=v1")
		req.GetRequest.SetContentType("application/json")
  
		Wait For (req) JobDone(req As HttpJob)
  
		If req.Success Then
      
			'Uncomment this line if you want to see raw JSON response
			Dim res As String = req.GetString
			Log(res)
			response = res

			'response = ParseJson(req.GetString)
  
		Else
      
			response = "ERROR: " & req.ErrorMessage
  
		End If
  
		req.Release
 
	Catch
  
		response = "ERROR: " & LastException
 
	End Try
 
	Return response

End Sub

'Documentation: <link>|</link>
Public Sub RetrieveRun(thread_id As String, run_id As String) As ResumableSub
 
	'For complete documentation you should look at:
	'https://platform.openai.com/docs/api-reference/runs/getRun
 
	Try
  

		Dim response As String
  
		Dim req As HttpJob
		req.Initialize("", Me)
		req.Download($"https://api.openai.com/v1/threads/${thread_id}/runs/${run_id}"$)
		req.GetRequest.InitializeGet($"https://api.openai.com/v1/threads/${thread_id}/runs/${run_id}"$)
		req.GetRequest.SetHeader("Authorization", "Bearer "&mtoken)
		'And if you have an organisation key...
		'If your account default organisation is "Personal" then you can supply
		'a blank organisation key - or just comment this line out
		req.GetRequest.SetHeader("OpenAI-Organization", morganization)
		req.GetRequest.SetHeader("OpenAI-Beta", "assistants=v1")
		'req.GetRequest.SetContentType("application/json")
  
		Wait For (req) JobDone(req As HttpJob)
  
		If req.Success Then
      
			'Uncomment this line if you want to see raw JSON response
			Dim res As String = req.GetString
			Log(res)
			response = res

			'response = ParseJson(req.GetString)
  
		Else
      
			response = "ERROR: " & req.ErrorMessage
  
		End If
  
		req.Release
 
	Catch
  
		response = "ERROR: " & LastException
 
	End Try
 
	Return response

End Sub

'Documentation: <link>|</link>
Public Sub ListRunSteps(thread_id As String, run_id As String) As ResumableSub
 
	'For complete documentation you should look at:
	'https://platform.openai.com/docs/api-reference/runs/getRun
	'https://api.openai.com/v1/threads/{thread_id}/runs/{run_id}/steps
 
	Try
  

		Dim response As String
  
		Dim req As HttpJob
		req.Initialize("", Me)
		req.Download($"https://api.openai.com/v1/threads/${thread_id}/runs/${run_id}/steps"$)
		req.GetRequest.SetHeader("Authorization", "Bearer "&mtoken)
		'And if you have an organisation key...
		'If your account default organisation is "Personal" then you can supply
		'a blank organisation key - or just comment this line out
		req.GetRequest.SetHeader("OpenAI-Organization", morganization)
		req.GetRequest.SetHeader("OpenAI-Beta", "assistants=v1")
		'req.GetRequest.SetContentType("application/json")
  
		Wait For (req) JobDone(req As HttpJob)
  
		If req.Success Then
      
			'Uncomment this line if you want to see raw JSON response
			Dim res As String = req.GetString
			Log(res)
			response = res

			'response = ParseJson(req.GetString)
  
		Else
      
			response = "ERROR: " & req.ErrorMessage
  
		End If
  
		req.Release
 
	Catch
  
		response = "ERROR: " & LastException
 
	End Try
 
	Return response

End Sub

' inputpath and inputfilename: points to the sourcefile to transcript
' model: ID of the model to use. Only whisper-1 (which is powered by our open 
' source Whisper V2 model) is currently available.
' language: The language of the input audio. Supplying the input language 
' in ISO-639-1 format will improve accuracy and latency.
' prompt: An optional text to guide the model's style or continue a previous 
' audio segment. The prompt should match the audio language. prompt is set 
' when the value is not ""
' response_format: The format of the transcript output, in one of these options:
' json, text, srt, verbose_json, or vtt.
'Documentation: <link>createTranscriptions|'https://platform.openai.com/docs/api-reference/audio/createTranscription</link>
Public Sub createTranscription(inputpath As String, inputfilename As String, model As String, language As String, prompt As String, response_format As String) As ResumableSub
 
	Dim m As Map = CreateMap("model": model)
	If language<>"" Then
		m.Put("language",language)
	End If
	If prompt<>"" Then
		m.Put("prompt",prompt)
	End If
	If response_format<>"" Then
		m.Put("response_format",response_format)
	End If


	Dim response As String

  
	Dim f As MultipartFileData
	f.Initialize
	f.Dir = inputpath
	f.FileName = inputfilename
	f.KeyName = "file"
	Dim files As List
	files.Initialize
	files.Add(f)
		
	Dim req As HttpJob
	req.Initialize("", Me)
		
	req.PostMultipart("https://api.openai.com/v1/audio/transcriptions",m,files)
	req.GetRequest.SetHeader("Authorization", "Bearer "&mtoken)
	'And if you have an organisation key...
	'If your account default organisation is "Personal" then you can supply
	'a blank organisation key - or just comment this line out
	'req.GetRequest.SetHeader("OpenAI-Organization", "org-xxx")
	req.GetRequest.SetHeader("OpenAI-Organization", morganization)
	'req.GetRequest.SetContentType("application/json")
  
	Wait For (req) JobDone(req As HttpJob)
  
	If req.Success Then
      
		'Uncomment this line if you want to see raw JSON response
		Dim res As String = req.GetString
		Log(res)
		If mlogfilepath<> "" Then
			File.WriteString(mlogfilepath,$"Assistant-transcription-${DateTime.Now}.json"$,res)
		End If
		response = res			
  
	Else
      
		response = "ERROR: " & req.ErrorMessage
  
	End If
	req.Release
	return response  

End Sub


' - prompt
'   
' - model 
'   can be "tts-1" or "tts-1-hd"
' - voice 
'   can be one of "alloy", "echo", "fable", "onyx", "nova" or "shimmer"
' - format 
'   The format to audio in. Supported formats are 
'   "mp3", "opus", "aac", "flac", "wav", and "pcm".
'Documentation: <link>QuerySpeech|'https://platform.openai.com/docs/api-reference/audio/createSpeech</link>
Public Sub createSpeech(prompt As String, model As String, voice As String, format As String,spee As String) As ResumableSub
 
	'For complete documentation you should look at:
	'https://platform.openai.com/docs/api-reference/audio/createSpeech
 
	Try
  
		'The speed of the generated audio. Select a value from 0.25 to 4.0. 1.0 is the default.
		Dim m As Map = CreateMap("model": model, "input":prompt,"voice":voice,"response_format":format)
		Dim jgen As JSONGenerator
		jgen.Initialize(m)
		'Uncomment this line if you want to see raw input string
		Log(jgen.ToString)

		Dim response As String
  
		Dim req As HttpJob
		req.Initialize("", Me)
		req.PostString("https://api.openai.com/v1/audio/speech", jgen.ToString)
		req.GetRequest.SetHeader("Authorization", "Bearer "&mtoken)
		'And if you have an organisation key...
		'If your account default organisation is "Personal" then you can supply
		'a blank organisation key - or just comment this line out
		'req.GetRequest.SetHeader("OpenAI-Organization", "org-xxx")
		req.GetRequest.SetHeader("OpenAI-Organization",morganization)
		req.GetRequest.SetContentType("application/json")
  
		Wait For (req) JobDone(req As HttpJob)
  
		If req.Success Then
      
			'Uncomment this line if you want to see raw JSON response
			Log($"Audio-Request Successfully()"$)
      
			Dim filename As String = $"audio-${DateTime.Now}.${format}"$
			Dim out As OutputStream = File.OpenOutput(mdownloadpath, filename, False)
			File.Copy2(req.GetInputStream, out)
			out.Close '<------ very important
			Log("File written to "&File.Combine(mdownloadpath,filename))	
			response = filename
		Else
      
			response = "ERROR: " & req.ErrorMessage
  
		End If
  
		req.Release
 
	Catch
  
		response = "ERROR: " & LastException
 
	End Try
 
	Return response

End Sub

'The size of the generated images. 
'Must be one of 256x256, 512x512, or 1024x1024 for dall-e-2. 
' Must be one of 1024x1024, 1792x1024, or 1024x1792 for dall-e-3 models.
'Documentation: <link>Image|https://platform.openai.com/docs/api-reference/images</link>
Public Sub QueryImage(prompt As String, size As String) As ResumableSub
 
	'For complete documentation you should look at:
	'https://platform.openai.com/docs/api-reference/images
 
	Try
  
		Dim model As String = "dall-e-3"
		'Dim msgs As List
		'msgs.Initialize
		'msgs.Add(CreateMap("role":"system","content":system_string))
		'msgs.Add(CreateMap("role":"user","content":query_string))		
		Dim m As Map = CreateMap("model": model, "n":1,"size":size,"response_format":"url","user":"DonManfred","prompt":prompt)
		Dim jgen As JSONGenerator
		jgen.Initialize(m)
		'Uncomment this line if you want to see raw input string
		Log(jgen.ToString)

		Dim response As String
  
		Dim req As HttpJob
		req.Initialize("", Me)
		req.PostString("https://api.openai.com/v1/images/generations", jgen.ToString)
		req.GetRequest.SetHeader("Authorization", "Bearer "&mtoken)
		'And if you have an organisation key...
		'If your account default organisation is "Personal" then you can supply
		'a blank organisation key - or just comment this line out
		'req.GetRequest.SetHeader("OpenAI-Organization", "org-xxx")
		req.GetRequest.SetHeader("OpenAI-Organization",morganization)
		req.GetRequest.SetContentType("application/json")
  
		Wait For (req) JobDone(req As HttpJob)
  
		If req.Success Then
      
			'Uncomment this line if you want to see raw JSON response
			Log($"Request Successfully()"$)
			Log(req.GetString)
      
			response = req.GetString 'ParseJson(req.GetString)
  
			Dim parser As JSONParser
			parser.Initialize(response)
			Dim jRoot As Map = parser.NextObject
			Dim created As Int = jRoot.Get("created")
			Dim data As List = jRoot.Get("data")
			For Each coldata As Map In data
				Dim revised_prompt As String = coldata.Get("revised_prompt")
				Dim url As String = coldata.Get("url")
				DownloadImage(url,mdownloadpath, "Img-"&created&".png")
			Next
	
		Else
      
			response = "ERROR: " & req.ErrorMessage
  
		End If
  
		req.Release
 
	Catch
  
		response = "ERROR: " & LastException
 
	End Try
 
	Return response

End Sub
' Used by QueryImage API
Sub DownloadImage(url As String, dest As String, filename As String)
	Dim j As HttpJob
	j.Initialize("", Me) 'name is empty as it is no longer needed
	j.Download(url)
	Wait For (j) JobDone(j As HttpJob)
	If j.Success Then
		Log("Current link: " & url)
		Dim out As OutputStream = File.OpenOutput(dest, filename, False)
		File.Copy2(j.GetInputStream, out)
		out.Close '<------ very important
		Log("File written to "&File.Combine(dest,filename))
	End If
	j.Release

End Sub
'I did as JohnC suggested in:
'https://www.b4x.com/android/forum/threads/lost-in-chatgpt-json.146738/post-930211
'and asked ChatGPT:
'using b4a how do I parse this json string: "{""id"":""chatcmpl-6t2JQdgU1ypn0ayhONAkE6bAEoGkz"",""object"":""chat.completion"",""created"":1678574948,""model"":""gpt-3.5-turbo-0301"",""usage"":{""prompt_tokens"":25,""completion_tokens"":110,""total_tokens"":135},""choices"":[{""message"":{""role"":""assistant"",""content"":""Ahoy matey, ye be askin' a great question. The worst investment be ones that promise quick riches without flappin' yer sails too much, like the \""get rich quick\"" schemes, ponzi schemes Or pyramid schemes. These scams be all about misuse of trust And deceivin' the inexperienced. They be luring investors with high promised returns, but in the end, they just take yer doubloons and disappear into the horizon. Stay away from such crooks and keep yer treasure safe, me hearty!""},""finish_reason"":""stop"",""index"":0}]}" for content
'and it responded with this - except it used a variable named "object" which
'B4A objected to that I had to change to "object_string"
'I also had to change the management of the variable "content" so the subroutine would return a result
Sub ParseJson(json As String) As String
	Dim parser As JSONParser
	parser.Initialize(json)
	Dim root As Map
	root = parser.NextObject
	Dim id As String
	id = root.Get("id")
	Dim object_string As String
	object_string = root.Get("object")
	Dim created As Long
	created = root.Get("created")
	Dim model As String
	model = root.Get("model")
	Dim usage As Map
	usage = root.Get("usage")
	Dim promptTokens As Int
	promptTokens = usage.Get("prompt_tokens")
	Dim completionTokens As Int
	completionTokens = usage.Get("completion_tokens")
	Dim totalTokens As Int
	totalTokens = usage.Get("total_tokens")
	Dim choices As List
	choices = root.Get("choices")
	Dim choiceIndex As Int
	Dim content As String
	For choiceIndex = 0 To choices.Size - 1
		Dim choice As Map
		choice = choices.Get(choiceIndex)
		Dim message As Map
		message = choice.Get("message")
		Dim role As String
		role = message.Get("role")
		If content <> "" Then content = content & CRLF
		content = content & message.Get("content")
		Dim finishReason As String
		finishReason = choice.Get("finish_reason")
		Log("Choice " & choiceIndex)
		Log("Role: " & role)
		Log("Content: " & content)
		Log("Finish Reason: " & finishReason)
	Next
	Return content
End Sub