Private Sub MyAccessAI() 'Sub for the AI commandobutton Dim request As Object Dim response As String Dim text As String, API As String, api_key As String Dim DisplayText As String Dim status_code As Long Dim prompt As String ' API Info API = "https://api.openai.com/v1/chat/completions" api_key = "sk-MyAPI-key" 'API key" If api_key = "" Then MsgBox "Error: API key is blank!" Exit Sub End If ' Read data from table Dim db As DAO.Database Dim rs As DAO.Recordset Dim resultString As String prompt = AIFråga 'The question string from form If Trim(prompt) = "" Then MsgBox "Error: Prompt is blank!" Exit Sub End If ' Clean input text text = Replace(prompt, Chr(34), Chr(39)) text = Replace(text, vbLf, " ") ' Create HTTP request Set request = CreateObject("MSXML2.XMLHTTP") With request .Open "POST", API, False .setRequestHeader "Content-Type", "application/json" .setRequestHeader "Authorization", "Bearer " & api_key .send "{""model"": ""gpt-4o"", ""messages"": [{""content"":""" & text & """,""role"":""user""}]," _ & """temperature"": 1, ""top_p"": 0.7, ""max_tokens"": 2048}" status_code = .Status response = .responseText End With ' Extract content (you need to implement ExtractContent function) If status_code = 200 Then DisplayText = ExtractContent(response) 'MsgBox DisplayText Else MsgBox "API Error: " & response Set request = Nothing Exit Sub End If AISvar = DisplayText 'The answer string from form Set request = Nothing Call cmdSave_Click ' Call Sub for saving the record to the table 'Me.Requery 'Me.Refresh End Sub Function ExtractContent(jsonString As String) As String Dim startPos As Long Dim endPos As Long Dim Content As String startPos = InStr(jsonString, """content"": """) + Len("""content"": """) endPos = InStr(startPos, jsonString, "},") - 2 Content = Mid(jsonString, startPos, endPos - startPos) Content = Trim(Replace(Content, "\""", Chr(34))) 'Fix for forumulas as response If Left(Trim(Content), 1) = "=" Then Content = "'" & Content End If Content = Replace(Content, vbCrLf, "") Content = Replace(Content, vbLf, "") Content = Replace(Content, vbCr, "") Content = Replace(Content, "\n\n", " ") If Right(Content, 1) = """" Then Content = Left(Content, Len(Content) - 1) End If Content = Left(Content, Len(Content) - 51) ExtractContent = Content End Function Private Sub cmdSave_Click() 'Save the record to the table If Me.Dirty Then If MsgBox("Do you want to save record to table?", vbYesNo + vbQuestion, "Confirm Save") = vbYes Then DoCmd.RunCommand acCmdSaveRecord Else Me.Undo End If End If End Sub