Using Assistant in VB.net

using:


 Private Async Sub btnSendtoAI_Click(sender As Object, e As EventArgs) Handles btnSendToAI.Click
        Dim userInput As String = txtUserPrompt.Text
        If Not String.IsNullOrWhiteSpace(userInput) Then
            Try
                Dim response As String = Await GetAssistantResponseAsync(userInput)
                MessageBox.Show(response)
            Catch ex As Exception
                MessageBox.Show($"Error: {ex.Message}")
            End Try
        Else
            MessageBox.Show("Please enter a message.")
        End If
    End Sub

    Private Async Function GetAssistantResponseAsync(prompt As String) As Task(Of String)
        Dim apiUrl As String = $"https://api.openai.com/v1/assistants/{ASSIST_ID}/messages"
        Dim client As HttpClient = Nothing

        Try
            client = New HttpClient()
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {API_KEY}")

            Dim requestData As New JObject(
                New JProperty("messages", New JArray(
                    New JObject(
                        New JProperty("role", "user"),
                        New JProperty("content", prompt)
                    )
                )),
                New JProperty("max_tokens", 1000)
            )

            Dim jsonData As String = requestData.ToString()
            Dim content As New StringContent(jsonData, Encoding.UTF8, "application/json")

            Dim response As HttpResponseMessage = Await client.PostAsync(apiUrl, content)
            Dim responseString As String = Await response.Content.ReadAsStringAsync()

            Dim jsonResponse As JObject = JObject.Parse(responseString)
            Dim generatedText As String = jsonResponse("choices")(0)("message")("content").ToString().Trim()

            Return generatedText
        Catch ex As Exception
            MessageBox.Show($"Error: {ex.Message}")
            Return $"Error: {ex.Message}"
        Finally
            If client IsNot Nothing Then
                client.Dispose()
            End If
        End Try

Keep getting “invalid URL error: type: invalid_request_error, param: null, code: null”

Set up Assistant to use File Search, and gpt-4o-mini

Welcome to the community!

Did you check out the official docs?

https://platform.openai.com/docs/api-reference/messages/listMessages?lang=curl

Thanks. I have a working function for chat using: api.openai.com\v1\chat\completions but did not get how to use api.openai.com\v1\assistants\{ASSIST_ID} with Assistant, and add header info “OpenAI-Beta: assistants=v2” and “model: gpt-4o-mini” I’m not sure how to convert curl to vb.net.

I’m fairly sure chatgpt - or the playground in a pinch - can do a solid job here :thinking:

Did you know transformers (LLMs) originally emerged from work in machine translation?

Starting with curl can get you almost anywhere :slight_smile:

Found a working solution through C3 to vb.net conversion… and some trial-error.
Posting what I have for anyone that might suggest improvements/edits:

 Private Sub AskAI_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        _openAIKey = API_KEY
        _assistant_id = ASSIST_ID
        _httpClient = New HttpClient()
        _httpClient.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Bearer", _openAIKey)
        _httpClient.DefaultRequestHeaders.Add("OpenAI-Beta", "assistants=v2")
        _httpClient.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
    End Sub

    Private Async Sub btnSendtoAI_Click(sender As Object, e As EventArgs) Handles btnSendToAI.Click
        Try
            Await CreateThread()
            Dim quest As String = txtQuestion.Text
            If quest.Length > 0 Then
                RichTextBox1.Text = "Wait while thinking..."
                Await AskQuestion(quest)
                ' Check status until complete
                Dim status As StatusModel = Nothing
                Do
                    status = Await CheckStatus()
                    Await Task.Delay(1000) ' Wait for 1 second before checking again
                Loop While status IsNot Nothing AndAlso status.status <> "completed"
                Dim answer = Await GetAnswer()
                DisplayMessageInRichTextBox(answer)
            Else
                MessageBox.Show("You must enter a question first!")
                txtQuestion.Text = ""
                RichTextBox1.Text = ""
                txtQuestion.Focus()
            End If
        Catch ex As Exception
            MessageBox.Show("An error occurred: " & ex.Message)
        End Try
    End Sub
    Private Function CleanText(input As String) As String
        ' Regex to match patterns like " "
        Dim pattern As String = "【\d+:\d+†source】"
        Return System.Text.RegularExpressions.Regex.Replace(input, pattern, String.Empty).Trim()
    End Function
    Private Sub DisplayMessageInRichTextBox(answer As AnswerModel)
        Dim richTextBox As RichTextBox = RichTextBox1 ' Assuming your RichTextBox is named RichTextBox1
        richTextBox.Clear()

        If answer IsNot Nothing AndAlso answer.data IsNot Nothing Then
            For Each message In answer.data
                For Each content In message.content
                    If content.type = "text" Then
                        Dim value As String = CleanText(content.text.value)
                        ' Apply formatting based on your needs
                        richTextBox.AppendText(value & Environment.NewLine)
                        ' Example of formatting
                        ' You can add more sophisticated formatting rules here
                        richTextBox.SelectionStart = richTextBox.TextLength
                        richTextBox.SelectionLength = value.Length
                        richTextBox.SelectionFont = New Drawing.Font(richTextBox.Font, FontStyle.Bold)
                        richTextBox.SelectionColor = Color.Blue
                        richTextBox.SelectionLength = 0
                    End If
                Next
            Next
        Else
            richTextBox.AppendText("No message received.")
        End If
        EnableAll()
    End Sub

    Public Async Function CreateThread() As Task
        Dim requestData = New With {Key .assistant_id = ASSIST_ID}
        Dim content = New StringContent(JsonSerializer.Serialize(requestData), Encoding.UTF8, "application/json")
        Dim response = Await _httpClient.PostAsync("https://api.openai.com/v1/threads", Nothing)
        Dim responseContent = Await response.Content.ReadAsStringAsync()
        Dim result = JsonSerializer.Deserialize(Of IdModel)(responseContent)
        threadsId = result.id
    End Function
    Public Async Function AskQuestion(ByVal txt As String) As Task
        Dim messageData = New With {Key .role = "user", Key .content = txt}
        Dim content = New StringContent(JsonSerializer.Serialize(messageData), Encoding.UTF8, "application/json")
        Dim response = Await _httpClient.PostAsync($"https://api.openai.com/v1/threads/{threadsId}/messages", content)
        Dim responseContent = Await response.Content.ReadAsStringAsync()
        Dim runData = New With {Key .assistant_id = _assistant_id}
        content = New StringContent(JsonSerializer.Serialize(runData), Encoding.UTF8, "application/json")
        response = Await _httpClient.PostAsync($"https://api.openai.com/v1/threads/{threadsId}/runs", content)
        responseContent = Await response.Content.ReadAsStringAsync()
        Dim result = JsonSerializer.Deserialize(Of IdModel)(responseContent)
        runId = result.id
    End Function
    Public Async Function CheckStatus() As Task(Of StatusModel)
        Dim response = Await _httpClient.GetAsync($"https://api.openai.com/v1/threads/{threadsId}/runs/{runId}")
        Dim responseContent = Await response.Content.ReadAsStringAsync()
        Dim result = JsonSerializer.Deserialize(Of StatusModel)(responseContent)
        Return result
    End Function

    Public Async Function GetAnswer() As Task(Of AnswerModel)
        Dim response = Await _httpClient.GetAsync($"https://api.openai.com/v1/threads/{threadsId}/messages")
        Dim responseContent = Await response.Content.ReadAsStringAsync()
        Return JsonSerializer.Deserialize(Of AnswerModel)(responseContent)
    End Function