golang调用deepseekr1
1.官方文档
2.请求看一下
因为deepseek官方API的deepssek-r1响应太慢,于是用了腾讯的API来测试
func main() {
cfg := config.Config{
BaseURL: "https://api.lkeap.cloud.tencent.com",
APIKey: "API-KEY",
HTTPClient: &http.Client{},
}
// 初始化deepseek
d := deepseek.NewDeepSeek(cfg)
// 封装请求体
body := model.Request{
Model: "deepseek-r1",
Messages: []model.Message{{Role: "system", Content: "You are a helpful assistant."}, {Role: "user", Content: "你是谁"}},
}
// 同步调用
chat, err := d.Chat(context.Background(), body)
if err != nil {
panic(err)
}
fmt.Println(chat.Content)
// 流式调用
//stream, _ := d.Stream(context.Background(), body)
//console.ConsoleContent(stream)
}
响应的格式
{"id":"ab6e60c5df865a38a","object":"chat.completion","created":1739782294,"model":"deepseek-r1","choices":[{"index":0,"message":{"role":"assistant","content":"\n\n您好!我是DeepSeek-R1,一个由深度求索公司开发的智能学,代码和逻辑推理等理工类问题。我会保持诚实,如果不知道答案会明确告知,并始终聚焦于提供最有帮助的信息。","reasoning_content":"\n嗯,用户问我是谁,我需要用中文回答。首先,我要明确自己的身份,是DeepSeek-R1,一个由深度求索公司开发,可能无法提供最新信息。同时,要避免使用复杂术语,保持口语化,让回答更自然。可能用户刚接触我,所以需要简洁明了,不需要太长的解释。还要注意语气友好,表现出愿意帮助的态度。有没有遗漏什么?比如是否需要提到公司背景或者隐私政策?不过ens":230,"total_tokens":246}}
发现跟deepseek-chat的响应只是多路一个reasoning_content,在响应上面加上就可以了
type Response struct {
Content string `json:"content"`
ReasoningContent string `json:"reasoning_content"` // 思考回答
}
3.改造后的整个访问流程
1. 调用流式请求
stream, _ := d.Stream(context.Background(), body)
2. 发起流式请求
func (d *DeepSeek) Stream(ctx context.Context, request model.Request) (<-chan model.Response, error) {
return http_parse.HandleStreaming(ctx, request, &d.Cfg)
}
3. 响应处理
func HandleStreaming(ctx context.Context, req model.Request, c *config.Config) (<-chan model.Response, error) {
ch := make(chan model.Response)
go func() {
defer close(ch)
// 发起流式请求
resp, err := DoRequest(ctx, req, true, c)
if err != nil {
ch <- model.Response{Content: "request error!"}
return
}
defer resp.Body.Close()
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
select {
case <-ctx.Done():
ch <- model.Response{Content: "ctx done!"}
return
default:
// 解析事件流
event := ParseEvent(scanner.Bytes())
if event != nil {
ch <- *event
}
}
}
}()
return ch, nil
}
4. 打印结果
func Content(ch <-chan model.Response) {
for chunk := range ch {
if chunk.ReasoningContent != "" {
fmt.Printf(chunk.ReasoningContent)
continue
}
// 打印回答
fmt.Printf(chunk.Content)
}
}
4.代码地址
https://gitee.com/li-zhuoxuan/go_ai