LoginSignup
2
0

More than 1 year has passed since last update.

ChatGPTのAPIをGolangで実装する

Last updated at Posted at 2023-03-06
gpt.go
package gpt

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
)

type IGpt interface {
	GenerateText(message []Chat) (string, error)
}

type Gpt struct {
	apiKey string
	model  string
}

func NewGpt(apiKey string, model string) IGpt {
	return &Gpt{
		apiKey: apiKey,
		model:  model,
	}
}

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

func (gpt *Gpt) GenerateText(messages []Chat) (string, error) {
	url := "https://api.openai.com/v1/chat/completions"

	// Escape any double quotes in the message
	// escapedMessage := fmt.Sprintf("%q", message)

	jsonData, err := json.Marshal(messages)
	if err != nil {
		fmt.Println("Error marshaling JSON:", err)
		return "", errors.New("error marshaling JSON")
	}

	jsonString := string(jsonData)
	jsonStr := []byte(fmt.Sprintf(`{
		"model": "%s",
		"messages": %s
	}`, gpt.model, jsonString))

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
	if err != nil {
		return "error before sending a request to api", err
	}
	if gpt.apiKey == "" {
		return "invalid_api_key", err
	}

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

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return "error after sending a request to api", err
	}
	defer resp.Body.Close()

	var m map[string]interface{}

	err = json.NewDecoder(resp.Body).Decode(&m)
	if err != nil {

		return "error after sending a request to api", err
	}
	if errVal, ok := m["error"].(map[string]interface{}); ok {

		errorCode := errVal["code"].(string)

		return errorCode, errors.New(errorCode)
	}

	content := m["choices"].([]interface{})[0].(map[string]interface{})["message"].(map[string]interface{})["content"].(string)
	return content, err
}

テストコード

gpt_test.go

package gpt_test

// test code
import (
	"fmt"
	"os"
	"testing"

	gpt "gowhale/Gpt"

	"github.com/joho/godotenv"
)

func TestSample(t *testing.T) {
	fmt.Println("TestSample")
	// load the env file
	err := godotenv.Load("../.env")
	if err != nil {
		t.Fatalf("Error loading .env file: %v", err)
	}
	// print the env variable of OPENAI_API_KEY
	// gpt-4-0314
	openai := gpt.NewGpt(os.Getenv("OPENAI_API_KEY"), "gpt-4-0314")
	chat := []gpt.Chat{
		{
			Role:    "user",
			Content: "hello",
		},
	}
	fmt.Println(openai.GenerateText(chat))
	// openai2 := gpt.NewGpt(os.Getenv("OPENAI_API_KEY"), "gpt-4")
	// fmt.Println(openai2.GenerateText("Hello!!"))

}


2
0
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
2
0