Why Go and ChatGPT Are the Perfect Duo?
\nHave you ever wondered how quickly you can "teach" your Go program to communicate with a user like a real person? Or maybe you want to automate content generation, create an intelligent assistant, or simply add a "special touch" to your service? Integration with the ChatGPT API in Go is not just a trendy fad, but a powerful tool that opens doors to the world of artificial intelligence. Go, with its speed and simplicity, is ideal for creating fast and reliable requests to neural networks. In this article, we will not just cover the theory, but write real code that you can immediately use in your projects.
\n\nLaying the Groundwork: What Do You Need to Start?
\nBefore diving into the code, let's make sure we have everything we need. You will need:
\n- \n
- Installed Go (version 1.21 or higher to use all modern features). \n
- OpenAI API key. You can get it on the OpenAI platform. Treat it like your bank card password — keep it secret! \n
- Basic understanding of HTTP requests and data structures in Go. \n
We will write all the code from the article in a single file main.go to keep the structure simple. Let's go!
Step 1: Creating an HTTP Client and Sending the First Request
\nThe heart of our integration will be the standard net/http package. It is lightweight, fast, and requires no third-party dependencies. Our task is to send a POST request to the endpoint https://api.openai.com/v1/chat/completions with the correct body and headers.
Request Structure
\nThe ChatGPT API expects JSON in a specific format. Let's create Go structures that exactly match this format:
\npackage main\n\nimport (\n "bytes"\n "encoding/json"\n "fmt"\n "io"\n "net/http"\n "os"\n)\n\ntype ChatMessage struct {\n Role string `json:"role"`\n Content string `json:"content"`\n}\n\ntype ChatRequest struct {\n Model string `json:"model"`\n Messages []ChatMessage `json:"messages"`\n}\n\ntype ChatResponse struct {\n Choices []struct {\n Message ChatMessage `json:"message"`\n } `json:"choices"`\n}\nNotice the json:"..." tags. They ensure that Go correctly "packs" (serializes) our data into JSON that OpenAI will understand.
The Sender Function
\nNow let's write a function that handles all the "dirty" work: forms the request, sends it, and parses the response.
\nfunc askChatGPT(apiKey, prompt string) (string, error) {\n reqBody := ChatRequest{\n Model: "gpt-3.5-turbo",\n Messages: []ChatMessage{\n {Role: "user", Content: prompt},\n },\n }\n\n jsonData, err := json.Marshal(reqBody)\n if err != nil {\n return "", fmt.Errorf("marshaling error: %w", err)\n }\n\n request, err := http.NewRequest("POST", "https://api.openai.com/v1/chat/completions", bytes.NewBuffer(jsonData))\n if err != nil {\n return "", fmt.Errorf("request creation error: %w", err)\n }\n\n request.Header.Set("Content-Type", "application/json")\n request.Header.Set("Authorization", "Bearer "+apiKey)\n\n client := &http.Client{}\n response, err := client.Do(request)\n if err != nil {\n return "", fmt.Errorf("request execution error: %w", err)\n }\n defer response.Body.Close()\n\n body, err := io.ReadAll(response.Body)\n if err != nil {\n return "", fmt.Errorf("response reading error: %w", err)\n }\n\n // Check the status code\n if response.StatusCode != http.StatusOK {\n return "", fmt.Errorf("API returned an error: %s, body: %s", response.Status, string(body))\n }\n\n var chatResp ChatRes