利用go-openai免费使用 chatanywhere 提供的GPT-3.5-Turbo

569 阅读1分钟

利用go-openai免费使用 chatanywhere 提供的GPT-3.5-Turbo

1 申请免费 KEY

GPT-API-free地址

1.1 点击申请免费 KEY

Pasted image 20240813172803.jpeg

1.2 获取 KEY

Pasted image 20240805153302.jpeg

实际获取的是 ChatAnywhere API 中的 key
ChatAnywhere 地址, 可以在地址上查看使用情况。
获取的这个 KEY 不能直接在 openai 上使用,需要将地址换成 chatanywhere 中可用的地址:

Note

1.3 测试 API 密钥(非必须)

可以使用此站提供的命令,填写好自己的 API KEY,测试 API 请求是否正常。

curl https://api.chatanywhere.tech/v1/chat/completions -H 'Content-Type: application/json' -H 'Authorization: Bearer YOUR_API_KEY' -d '{ "model": "gpt-3.5-turbo","messages": [{"role": "user", "content": "Say this is a test!"}],  "temperature": 0.7}'

如果提示 401 Authorization Required,则测试不通过。
正常情况下会返回 JSON 代码。如下:

{  
    "id": "chatcmpl-abc123",  
    "object": "chat.completion",  
    "created": 1677858242,  
    "model": "gpt-3.5-turbo-0301",  
    "usage": {  
        "prompt_tokens": 13,  
        "completion_tokens": 7,  
        "total_tokens": 20  
    },  
    "choices": [  
        {  
            "message": {  
                "role": "assistant",  
                "content": "\n\nThis is a test!"  
            },  
            "finish_reason": "stop",  
            "index": 0  
        }  
    ]  
}

2 利用 go-openai

go-openai地址

2.1 Go-get 下载 go-openai 包

$ go get github.com/sashabaranov/go-openai
go: downloading github.com/sashabaranov/go-openai v1.28.1
go: upgraded github.com/sashabaranov/go-openai v1.27.1 => v1.28.1

2.2 测试代码

package main

import (
	"context"
	"fmt"

	openai "github.com/sashabaranov/go-openai"
)

func main() {

	config := openai.DefaultConfig("replace your key") //替换为你的API key
	config.BaseURL = "https://replace host"            //替换为你的API host
	client := openai.NewClientWithConfig(config)

	resp, err := client.CreateChatCompletion(
		context.Background(),
		openai.ChatCompletionRequest{
			Model: openai.GPT3Dot5Turbo,
			Messages: []openai.ChatCompletionMessage{
				{
					Role:    openai.ChatMessageRoleUser,
					Content: "Hello!",
				},
			},
		},
	)

	if err != nil {
		fmt.Printf("ChatCompletion error: %v\n", err)
		return
	}

	fmt.Println(resp.Choices[0].Message.Content)
}