golang调用claude api实现ai'问答示例代码

代码语言:golang

所属分类:其他

代码描述:golang调用claude api实现ai'问答示例代码

代码标签: golang 调用 claude api ai' 问答 示例 代码

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

package main
//申请key地址:https://console.anthropic.com/account/keys
import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

const (
    apiURL = "https://api.anthropic.com/v1/messages"
    apiKey = "YOUR_API_KEY_HERE"
)

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

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

type Response struct {
    Content []struct {
        Text string `json:"text"`
    } `json:"content"`
}

func main() {
    // 创建请求体
    reqBody := Request{
        Model: "claude-3-opus-20240229",
        Messages: []Message{
            {Role: "user", Content: "What is the capital of France?"},
        },
    }

    // 将请求体转换为JSON
    jsonData, err := json.Marshal(reqBody)
    if err != nil {
        fmt.Println("Error marshalling JSON:", err)
        return
    }

    // 创建HTTP请求
    req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(.........完整代码请登录后点击上方下载按钮下载查看

网友评论0