Sub TranslateText_to_eng(thaiText As String)
' Create the JSON payload
Dim messages As List
messages.Initialize
' Add the system message
Dim systemMessage As Map
systemMessage.Initialize
systemMessage.Put("role", "system")
systemMessage.Put("content", "You are a professional translator. Translate text from Thai to English. Only return the English translation, nothing else.")
messages.Add(systemMessage)
Dim userMessage As Map
userMessage.Initialize
userMessage.Put("role", "user")
userMessage.Put("content", thaiText )
messages.Add(userMessage)
Dim json As Map
json.Initialize
json.Put("model", "gpt-4o-mini")
json.Put("messages", messages)
json.Put("max_tokens", 300)
json.Put("temperature", 0.0)
Dim jsonString As String = CreateJSON(json)
' Initialize HttpJob
Dim http As HttpJob
http.Initialize("TranslateText", Me)
http.PostString(ChatGPT_API_URL, jsonString)
http.GetRequest.SetContentType("application/json")
http.GetRequest.SetHeader("Authorization", "Bearer " & ChatGPT_API_Key)
End Sub
Sub JobDone(Job As HttpJob)
If Job.Success Then
Try
Dim result As String = Job.GetString
' Log the entire response for debugging
Log("API Response: " & result)
ProcessResponse(result)
Catch
ToastMessageShow("Error processing the response.", False)
End Try
Else
ToastMessageShow("Error: " & Job.ErrorMessage, False)
End If
Job.Release
End Sub
Sub ProcessResponse(responseString As String)
Try
Dim parser As JSONParser
parser.Initialize(responseString)
' Parse the root object
Dim root As Map = parser.NextObject
' Get the choices list
Dim choices As List = root.Get("choices")
' Get the first choice
Dim firstChoice As Map = choices.Get(0)
' Get the message map from the first choice
Dim message As Map = firstChoice.Get("message")
' Extract the content field from the message
Dim translation As String = message.Get("content")
' Display the translation in the second text box
If(translate_dirn="en>th") Then
outmsg.Text = translation.Trim
End If
If(translate_dirn="th>en") Then
txtmsg.Text = translation.Trim
End If
' Optionally log the translation for debugging
Log("Translation: " & translation)
Catch
ToastMessageShow("Error processing the response.", False)
Log("Response Parsing Error: " & LastException.Message)
End Try
End Sub
Sub CreateJSON(map As Map) As String
Dim json As JSONGenerator
json.Initialize(map)
Return json.ToString
End Sub