基于go的chatgpt api来啦!!!


写在前面

周末在家发现无意间能访问chatgpt了,然后看了一下它的api,使用go语言封装了一下,方便大家使用

准备条件

接口

参考官方文档Api reference,官方文档提供了http接口,header,request,response都写的非常清楚,本人先通过postman都一一测试过

下面详细介绍几个接口

聊天

url

https://api.openai.com/v1/chat/completions

request

{
  "model": "gpt-3.5-turbo",
  "messages": [{"role": "user", "content": "Hello!"}]
}

response

{
  "id": "chatcmpl-123",
  "object": "chat.completion",
  "created": 1677652288,
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": "\n\nHello there, how may I assist you today?",
    },
    "finish_reason": "stop"
  }],
  "usage": {
    "prompt_tokens": 9,
    "completion_tokens": 12,
    "total_tokens": 21
  }
}

画图

url

https://api.openai.com/v1/images/generations

request

{
  "prompt": "A cute baby sea otter",
  "n": 2,
  "size": "1024x1024"
}

response

{
  "created": 1589478378,
  "data": [
    {
      "url": "https://..."
    },
    {
      "url": "https://..."
    }
  ]
}

情感分析

url

https://api.openai.com/v1/moderations

request

{
  "input": "I want to kill them."
}

response

{
  "id": "modr-5MWoLO",
  "model": "text-moderation-001",
  "results": [
    {
      "categories": {
        "hate": false,
        "hate/threatening": true,
        "self-harm": false,
        "sexual": false,
        "sexual/minors": false,
        "violence": true,
        "violence/graphic": false
      },
      "category_scores": {
        "hate": 0.22714105248451233,
        "hate/threatening": 0.4132447838783264,
        "self-harm": 0.005232391878962517,
        "sexual": 0.01407341007143259,
        "sexual/minors": 0.0038522258400917053,
        "violence": 0.9223177433013916,
        "violence/graphic": 0.036865197122097015
      },
      "flagged": true
    }
  ]
}

更多接口请参考官方文档

go sdk

├── README.md
├── common
│   ├── const.go // 定义常量
│   ├── error.go // 定义error code
│   └── logger.go // 封装日志组件github.com/rs/zerolog
├── config
│   ├── config.go // 配置
│   └── config.yaml
├── example
│   └── main.go // 示例
├── go.mod
├── go.sum
├── openai
│   ├── chat_completions.go // 实现聊天接口
│   ├── completions.go 
│   ├── embeddings.go 
│   ├── image.go // 实现画图接口
│   ├── model // 定义相关结构体,主要是返回值中会用到
│   │   ├── chat_completions.go
│   │   ├── completions.go
│   │   ├── embeddings.go
│   │   ├── image.go
│   │   ├── model.go
│   │   └── moderations.go
│   ├── model.go
│   ├── moderations.go // 实现情感分析接口
│   ├── openai.go // 定义对外的ai能力的interface以及封装内部默认ai实例以函数形式对外提供服务
│   ├── openai_test.go
│   ├── req_resp.go // 定义http请求的request,response
│   └── util.go // 获取各个接口的url
└── pkg
    └── http
        ├── const.go
        └── http.go // 封装http请求

示例

package main

import (
	"context"
	"fmt"
	"openai-go/openai"
)

func main() {
	// 一定要设置环境变量OPEN_API_KEY
	ai := openai.New(nil)
	ctx := context.Background()
	// 1.聊天
	input := "你是谁"
	count := 2 // 表示生成2个答案
	result, err := ai.ChatCompletions(ctx, input, 2)
	if err != nil {
		panic(err)
	} else {
		fmt.Println(result)
		// [我是一个人工智能语言模型,被称为OpenAI的GPT-3。 我是AI语言模型,一个能够自动回答问题和生成文本的人工智能程序。]
	}

	// 2.生成图片
	input = "韩国美女"
	result, err = ai.Images(ctx, input, count)
	if err != nil {
		panic(err)
	} else {
		fmt.Println(result)
		// 	[
		//	https://oaidalleapiprodscus.blob.core.windows.net/private/org-9MT5FUMC11U2zbyI5yIjpL1P/user-938N4hMdCq02FcSfB224yezE/img-YxKQf13QBxt9eFO31LAvmlKx.png?st=2023-03-26T13%3A02%3A42Z&se=2023-03-26T15%3A02%3A42Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2023-03-25T16%3A32%3A34Z&ske=2023-03-26T16%3A32%3A34Z&sks=b&skv=2021-08-06&sig=eVoEHWLcQ8pwjm7WVPkTMMgF8wv67XjnT5Ryq24kQiw%3D
		//	https://oaidalleapiprodscus.blob.core.windows.net/private/org-9MT5FUMC11U2zbyI5yIjpL1P/user-938N4hMdCq02FcSfB224yezE/img-O1n2SlAlljmLfnQPg1rbB9ZX.png?st=2023-03-26T13%3A02%3A42Z&se=2023-03-26T15%3A02%3A42Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2023-03-25T16%3A32%3A34Z&ske=2023-03-26T16%3A32%3A34Z&sks=b&skv=2021-08-06&sig=BDGjc4SzkLcEblytsLso0UMdL0s4u/xPxdCkmo/q2bk%3D
		//	]
	}
}

美女。。。

感兴趣的同学可以start,download或者提pr,可以一起完善这个chatgpt-go-sdk

参考

[1]chatgpt-go-sdk

[2]官方文档Api reference


文章作者: Alex
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Alex !
  目录