LoginSignup
13
9

More than 1 year has passed since last update.

ChatGPT API(gpt-3.5-turbo)を GoLang から使ってみる

Posted at

はじめに

こんにちは!この記事では、OpenAIが提供するChatGPT APIを使い、Golangで実装した方法について紹介します。このAPIは、自然言語に対する返答を生成する機械学習モデルを提供します。

以下は、ChatGPT APIの使い方のリンクです。ここで提供されている情報に沿って、Golangのサンプルプログラムを作成しました。

こちらがGithubのリポジトリになります。ご自由にご活用ください。

以下のはChatGPTのAPIの使い方です。
https://platform.openai.com/docs/api-reference/chat/create

main.go

main.go
package main

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
)

const openaiURL = "https://api.openai.com/v1/chat/completions"

var messages []Message

func main() {
	apiKey := "YOUR_API_KEY"

	reader := bufio.NewReader(os.Stdin)

	for {
		fmt.Print("Ask a question: ")
		question, _ := reader.ReadString('\n')
		question = strings.TrimSpace(question)

		if question == "exit" {
			break
		}

		messages = append(messages, Message{
			Role:    "user",
			Content: question,
		})

		response := getOpenAIResponse(apiKey)
		fmt.Println(response.Choices[0].Messages.Content)
		print("\n")
	}
}

func getOpenAIResponse(apiKey string) OpenaiResponse {
	requestBody := OpenaiRequest{
		Model:    "gpt-3.5-turbo",
		Messages: messages,
	}

	requestJSON, _ := json.Marshal(requestBody)

	req, err := http.NewRequest("POST", openaiURL, bytes.NewBuffer(requestJSON))
	if err != nil {
		panic(err)
	}

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+apiKey)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			panic(err)
		}
	}(resp.Body)

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}

	var response OpenaiResponse
	err = json.Unmarshal(body, &response)
	if err != nil {
		println("Error: ", err.Error())
		return OpenaiResponse{}
	}

	messages = append(messages, Message{
		Role:    "assistant",
		Content: response.Choices[0].Messages.Content,
	})

	return response
}

structs.go

structs.go
package main

type OpenaiRequest struct {
	Model    string    `json:"model"`
	Messages []Message `json:"messages"`
}

type OpenaiResponse struct {
	ID      string   `json:"id"`
	Object  string   `json:"object"`
	Created int      `json:"created"`
	Choices []Choice `json:"choices"`
	Usages  Usage    `json:"usage"`
}

type Choice struct {
	Index        int     `json:"index"`
	Messages     Message `json:"message"`
	FinishReason string  `json:"finish_reason"`
}

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

type Usage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
}

makefile

makefike
APP_NAME=chatgpt-turbo-sample-code

all: clean build

build:
	go build -o $(APP_NAME)

clean:
	rm -f $(APP_NAME)

run:
	./$(APP_NAME)

.PHONY: all build clean run

実行方法

bash
make
./chatgpt-turbo-sample-code

結果

demo.png

13
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
9