🤖Chatbot con OpenAI API e VB.NET

Questa guida mostra come creare un chatbot desktop con VB.NET + Windows Forms, utilizzando le API di OpenAI. Il codice include:

Nota:

il progetto richiede .NET Framework (4.0 o superiore). Per TLS 1.2 devi forzare il protocollo come mostrato nel codice.


1. Struttura della Form

Disegna una form Windows Forms con i seguenti controlli:


2. Codice completo commentato (frmGPTChat.vb)


Imports System.Net
Imports System.IO
Imports System.Configuration
Imports System.Web.Script.Serialization

Public Class frmGPTChat

' Variabile che conterrà la chiave API
Dim sApiKey As String

' Cronologia della chat (lista di messaggi, con ruolo "user"/"assistant")
Dim chatHistory As New List(Of Dictionary(Of String, String))()

' Evento Load della Form -> controlla che sia stata inserita la chiave API nell'apposita textbox
' utile se mandiamo la chiave API programmaticamente da un altro form
Private Sub frmGPTChat_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
sApiKey = TextBox1.Text
If sApiKey = "" Then
MsgBox("Please make sure you enter your OpenAI API key in the input box.")
End If
End Sub

' Evento click del pulsante "Invia"
Private Sub btnSend_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSend.Click
Dim sQuestion As String = txtQuestion.Text
sApiKey = TextBox1.Text

' Se non c'è input, avviso utente
If sQuestion = "" Then
MsgBox("Type in your question!")
txtQuestion.Focus()
Exit Sub
End If

' Mostra la domanda scritta dall'utente nel RichTextBox (colore viola, bold)
AppendTextWithFormatting("Me: " & sQuestion & vbCrLf, Color.Violet, True)

' Pulizia textbox input
txtQuestion.Text = ""

Try
' Invia domanda all'API
Dim answer As String = SendMsg(sQuestion)

' Mostra risposta nel RichTextBox (nero, testo normale)
AppendTextWithFormatting("Chat GPT: " & answer & vbCrLf, Color.Black, False)
Catch ex As Exception
' In caso di errore API / rete mostro un messaggio in rosso
AppendTextWithFormatting("Error: " & ex.Message & vbCrLf, Color.Red, False)
End Try

' Riga vuota per rendere leggibile la chat
AppendTextWithFormatting("", Color.Black, False)
txtAnswer.AppendText("" & vbCrLf)
End Sub

' Supporto: inserisce testo nella RichTextBox con formattazione custom
Private Sub AppendTextWithFormatting(ByVal text As String, ByVal textColor As Color, ByVal isBold As Boolean)
Dim originalColor As Color = txtAnswer.SelectionColor
Dim originalFont As Font = txtAnswer.SelectionFont

' Impostazioni di colore / stile
txtAnswer.SelectionColor = textColor
txtAnswer.SelectionFont = If(isBold, New Font(originalFont, FontStyle.Bold),
New Font(originalFont, FontStyle.Regular))

' Aggiungo testo
txtAnswer.AppendText(text)

' Ripristino config iniziali
txtAnswer.SelectionColor = originalColor
txtAnswer.SelectionFont = originalFont

' Sposto cursore in fondo e scroll automatico
txtAnswer.SelectionStart = txtAnswer.TextLength
txtAnswer.ScrollToCaret()
End Sub

' Funzione che invia la domanda alle API (via HTTPS TLS) e restituisce solo il "content" della risposta
Function SendMsg(ByVal sQuestion As String) As String
' Storicizzo la domanda
chatHistory.Add(New Dictionary(Of String, String) From {
{"role", "user"},
{"content", sQuestion}
})

' 🔐 Connessione sicura TLS1.1 + TLS1.2
ServicePointManager.SecurityProtocol = CType(3072, SecurityProtocolType) Or CType(768, SecurityProtocolType)

' Endpoint OpenAI Chat Completions
Dim apiEndpoint As String = "https://api.openai.com/v1/chat/completions"

' Configurazione richiesta
Dim request As HttpWebRequest = WebRequest.Create(apiEndpoint)
request.Method = "POST"
request.ContentType = "application/json"
request.Headers.Add("Authorization", "Bearer " & sApiKey)

' Corpo JSON della richiesta (incluso storico chat)
Dim requestBody As String = BuildRequestBody()

' Scrivo il JSON nella richiesta
Using streamWriter As New StreamWriter(request.GetRequestStream())
streamWriter.Write(requestBody)
End Using

' Invio e leggo la risposta
Dim response As HttpWebResponse = request.GetResponse()
Dim streamReader As New StreamReader(response.GetResponseStream())
Dim sJson As String = streamReader.ReadToEnd()

' Deserializzo la risposta
Dim oJavaScriptSerializer As New JavaScriptSerializer()
Dim responseDict As Dictionary(Of String, Object) = _
oJavaScriptSerializer.Deserialize(Of Dictionary(Of String, Object))(sJson)

' Validazione
If Not responseDict.ContainsKey("choices") Then
Throw New Exception("Invalid API response. Raw response: " & sJson)
End If

' Estraggo solo il campo content
Dim chatGPTResponse As String = responseDict("choices")(0)("message")("content").ToString().Trim()

' Storicizzo anche la risposta
chatHistory.Add(New Dictionary(Of String, String) From {
{"role", "assistant"},
{"content", chatGPTResponse}
})

Return chatGPTResponse
End Function

' Funzione che costruisce il JSON da mandare (inclusa la chat history)
Private Function BuildRequestBody() As String
Dim requestBody As String = "{" &
" ""model"": ""gpt-4o-mini"", " &
" ""max_tokens"": 8192, " &
" ""temperature"": 0.1, " &
" ""messages"": " & New JavaScriptSerializer().Serialize(chatHistory) &
" }"
Return requestBody
End Function

' Pulsante che esporta l'intera chat in un file .TXT
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim saveFileDialog As New SaveFileDialog()
saveFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
saveFileDialog.Title = "Save Chat Log"

If saveFileDialog.ShowDialog() = DialogResult.OK Then
Using writer As New StreamWriter(saveFileDialog.FileName)
writer.Write(txtAnswer.Text)
End Using
MessageBox.Show("Chat log exported successfully.", "Export Complete")
End If
Catch ex As Exception
MessageBox.Show("Error saving the file: " & ex.Message, "Error")
End Try
End Sub

End Class

3. Flusso generale

  1. L'utente inserisce la chiave API e formula una domanda.
  2. Il testo viene aggiunto allo storico e mostrato a schermo.
  3. La domanda viene inviata alle API OpenAI in JSON.
  4. La risposta (sempre in JSON) viene deserializzata con JavaScriptSerializer.
  5. Si estrae solo il message.content, che viene mostrato e aggiunto alla cronologia.
  6. Facoltativamente l'utente può salvare l'intera chat su file TXT.

4. Conclusione

Con questa implementazione completiamo un chatbot semplice ma potente in VB.NET, con gestione sicura della connessione e visualizzazione chiara delle conversazioni. Da qui puoi espandere la GUI, aggiungere pulsanti, cronologia persistente o altre feature!