Go 示例

以下是使用 Go 语言调用 AI2API 的示例代码。

基础请求

package main

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

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

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

func main() {
    reqBody := ChatRequest{
        Model: "gpt-3.5-turbo",
        Messages: []Message{
            {Role: "user", Content: "你好"},
        },
    }

    jsonData, _ := json.Marshal(reqBody)
    
    req, _ := http.NewRequest("POST", 
        "https://api.ai2api.top/v1/chat/completions", 
        bytes.NewBuffer(jsonData))
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("X-API-Key", "YOUR_API_KEY")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    var result map[string]interface{}
    json.NewDecoder(resp.Body).Decode(&result)
    
    fmt.Println(result)

封装客户端

package ai2api

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

type Client struct {
    APIKey string
    BaseURL string
}

func NewClient(apiKey string) *Client {
    return &Client{
        APIKey: apiKey,
        BaseURL: "https://api.ai2api.top",
    }
}

func (c *Client) Chat(model, message string) (string, error) {
    reqBody := map[string]interface{}{
        "model": model,
        "messages": []map[string]string{
            {"role": "user", "content": message},
        },
    }

    jsonData, _ := json.Marshal(reqBody)
    req, _ := http.NewRequest("POST", 
        fmt.Sprintf("%s/v1/chat/completions", c.BaseURL), 
        bytes.NewBuffer(jsonData))
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("X-API-Key", c.APIKey)

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()

    var result map[string]interface{}
    json.NewDecoder(resp.Body).Decode(&result)
    
    choices := result["choices"].([]interface{})
    message := choices[0].(map[string]interface{})["message"]
    return message.(map[string]interface{})["content"].(string), nil
}

使用示例

package main

import (
    "fmt"
    "ai2api"
)

func main() {
    client := ai2api.NewClient("YOUR_API_KEY")
    
    response, err := client.Chat("gpt-3.5-turbo", "你好")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    
    fmt.Println("Response:", response)
}