使用go调用openAI的API

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	chat()
	// image()
}

func chat() {
	client := &http.Client{}

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

	req, _ := http.NewRequest("POST", "https://api.openai.com/v1/chat/completions", bytes.NewReader([]byte(body)))
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Authorization", "Bearer your secret key")
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
	}
	r, _ := ioutil.ReadAll(resp.Body)
	fmt.Printf(string(r))
}

func image() {
	client := &http.Client{}

	var body = `
	{
	  "prompt": "A cute baby sea otter",
	  "n": 2,
	  "size": "1024x1024"
	}
`
	req, err := http.NewRequest("POST", "https://api.openai.com/v1/images/generations", bytes.NewReader([]byte(body)))

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Authorization", "Bearer your secret key")

	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("B:", err)
	}
	r, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("C:", err)
	}
	fmt.Println(string(r))
}

你可能感兴趣的:(golang,java,开发语言)