Golang试用阿里通义千问大语言模型

一、控制台配置通义千问密匙

官方操作指南地址

控制台地址

注意:一个密匙申请之后,官方给了一个月期限共计100万条Token的额度

 二、代码阶段

1、DashScopRequest 结构体 

type EngineRole string

const (
    EngineRoleUser      EngineRole = "user"
    EngineRoleSystem    EngineRole = "system"
    EngineRoleAssistant EngineRole = "assistant"
    EngineRoleTool      EngineRole = "tool"
)
type Message struct {
    Name      string              `json:"name"`
    Role      EngineRole          `json:"role"`
    Content   string              `json:"content"`
    ToolCalls interface{}         `json:"tool_calls"`
}

type Input struct {
    Prompt   string            `json:"prompt"`
    Messages []Message         `json:"messages"`
    History  map[string]string `json:"history"`
}

type Parameter struct {
    ResultFormat      string      `json:"result_format"`      //用于指定返回结果的格式
    Seed              *int64      `json:"seed"`               //生成时使用的随机数种子
    MaxTokens         *int64      `json:"max_tokens"`         //用于限制模型生成token的数量
    TopP              *float64    `json:"top_p"`              //生成时,核采样方法的概率阈值。
    TopK              *int64      `json:"top_k"`              //生成时,采样候选集的大小。
    RepetitionPenalty *float64    `json:"repetition_penalty"` //用于控制模型生成时连续序列中的重复度
    PresencePenalty   *float64    `json:"presence_penalty"`   //用户控制模型生成时整个序列中的重复度
    Temperature       *float64    `json:"temperature"`        //用于控制随机性和多样性的程度。
    Stop              interface{} `json:"stop"`               //string类型当模型将要生成指定的stop词语时停止。
    EnableSearch      *bool       `json:"enable_search"`      //启用互联网搜索
    //IncrementalOutput bool        `json:"incremental_output"` //控制在流式输出模式下是否开启增量输出
    //Tools             interface{} `json:"tools"`
    //ToolChoice     interface{} `json:"tool_choice"`
}

type DashScopeRequest struct {
    Model      string    `json:"model"`
    Input      Input     `json:"input"`
    Parameters Parameter `json:"parameters"`
}

2、DashResponse结构体

type Usage struct {
    TotalTokens  int `json:"total_tokens"`
    OutputTokens int `json:"output_tokens"`
    InputTokens  int `json:"input_tokens"`
}

type Choice struct {
    FinishReason string  `json:"finish_reason"`
    Message      Message `json:"message"`
}

type Output struct {
    Text         string   `json:"text"`
    FinishReason string   `json:"finish_reason"`
    Choices      []Choice `json:"choices"`
}

type DashScopeResponse struct {
    Output    Output `json:"output"`
    Usage     Usage  `json:"usage"`
    RequestId string `json:"request_id"`
}

3、DashScopErr 结构体

type DashScopeErr struct {
    Code      string `json:"code"`
    Message   string `json:"message"`
    RequestID string `json:"request_id"`
}

4、核心方法

var DashScopeUrl = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation"
func TongYiHttp(ctx context.Context, request DashScopeRequest) (*DashScopeResponse, *DashScopeErr, error) {
    // 构建请求
    payload, err := json.Marshal(request)
    if err != nil {
        return nil, nil, err
    }
    req, err := http.NewRequest("POST", DashScopeUrl, bytes.NewBuffer(payload))
    if err != nil {
        return nil, nil, err
    }

    // 设置请求头部
    req.Header.Set("Authorization", "YOUR API KEY") //就是你的API-KEY
    req.Header.Set("Content-Type", "application/json")

    // 发送请求
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return nil, nil, err
    }
    defer resp.Body.Close()

    // 检查HTTP响应状态码是否为200
    if resp.StatusCode != http.StatusOK {
        var errResp DashScopeErr
        err = json.NewDecoder(resp.Body).Decode(&errResp)
        if err != nil {
            return nil, nil, err
        }
        return nil, &errResp, nil
    }

    // 读取响应数据
    response := DashScopeResponse{}
    err = json.NewDecoder(resp.Body).Decode(&response)
    if err != nil {
        return nil, nil, err
    }
    return response, nil, nil
}

 三、调用测试(多轮对话),我使用了一个默认的大语言模型

func TestDashScope(t *testing.T) {
    // 构建请求数据
    ctx := context.Background()
    request := DashScopeRequest{
        Model: "qwen-turbo",
        Input: Input{
            Messages: []Message{
                {
                    Role:    EngineRoleUser,
                    Content: "1+1=?",
                },
                {
                    Role:    EngineRoleAssistant,
                    Content: "2",
                },
                {
                    Role:    EngineRoleUser,
                    Content: "2+1=?",
                },
                {
                    Role:    EngineRoleAssistant,
                    Content: "3",
                },
                {
                    Role:    EngineRoleUser,
                    Content: "帮我总结我们之间的对话",
                },
            },
        },
        Parameters: Parameter{
            ResultFormat: "message",
        },
    }

    tyResp, _, _ := TongYiHttp(ctx, request)
    fmt.Println(tyResp.Output)
}

同时自己玩的时候发现一个比较明显的缺点,如果你问简单问题响应在几百毫秒之内,涉及到复杂一点或者多轮对话响应时间明显增加。

要做特定业务方向的话得进行模型定制以及自己喂数据训练(仁者见仁,智者见智了)

 

posted @ 2024-07-29 22:53  FCmmmmmm  阅读(37)  评论(0编辑  收藏  举报