当前位置: 首页 > wzjs >正文

佛山骏域网站建设北京米兰广告设计有限公司

佛山骏域网站建设,北京米兰广告设计有限公司,游戏工作室加盟,假网站连接怎么做的目录 1.deepseek官方API调用文档1.访问格式2.curl组装 2.go代码1. config 配置2.模型相关3.错误处理4.deepseekAPI接口实现5. 调用使用 3.响应实例 1.deepseek官方API调用文档 1.访问格式 现在我们来解析这个curl 2.curl组装 // 这是请求头要加的参数-H "Content-Type:…

目录

  • 1.deepseek官方API调用文档
    • 1.访问格式
    • 2.curl组装
  • 2.go代码
      • 1. config 配置
      • 2.模型相关
      • 3.错误处理
      • 4.deepseekAPI接口实现
      • 5. 调用使用
  • 3.响应实例

1.deepseek官方API调用文档

1.访问格式

在这里插入图片描述
现在我们来解析这个curl

2.curl组装

// 这是请求头要加的参数-H "Content-Type: application/json" \-H "Authorization: Bearer <DeepSeek API Key>" \// 这是请求体要加的参数
-d '{"model": "deepseek-chat","messages": [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Hello!"}],"stream": false}'

这个里面可以看出,user角色使我们要输入的问题,stream选择是否为流式响应

2.go代码

1. config 配置

type Config struct {BaseURL    stringAPIKey     stringHTTPClient *http.Client
}

2.模型相关

type Model interface {Chat(ctx context.Context, req Request) (*Response, error)Stream(ctx context.Context, req Request) (<-chan Response, error)
}type Request struct {Model    string    `json:"model"`Messages []Message `json:"messages"`Stream   bool      `json:"stream"`
}type Message struct {Role    string `json:"role"`Content string `json:"content"`
}type Response struct {Content string `json:"content"`
}

3.错误处理

// Error 标准错误类型
type Error struct {Code    intMessage stringModel   string
}func (e *Error) Error() string {return fmt.Sprintf("[%s] %d: %s", e.Model, e.Code, e.Message)
}

4.deepseekAPI接口实现

type DeepSeek struct {Cfg ai.Config
}func NewDeepSeek(cfg ai.Config) *DeepSeek {return &DeepSeek{Cfg: cfg}
}func (d *DeepSeek) Stream(ctx context.Context, request ai.Request) (<-chan ai.Response, error) {return d.handleStreaming(ctx, request)
}func (d *DeepSeek) Chat(ctx context.Context, request ai.Request) (*ai.Response, error) {doRequest, err := d.doRequest(ctx, request, false)if err != nil {return nil, err}return d.parseResponse(doRequest)
}func (d *DeepSeek) parseResponse(resp *http.Response) (*ai.Response, error) {all, err := io.ReadAll(resp.Body)if err != nil {return nil, fmt.Errorf("io.ReadAll failed, err: %v\n", err)}defer resp.Body.Close()return &ai.Response{Content: string(all)}, nil
}// 私有方法
func (d *DeepSeek) doRequest(ctx context.Context, req ai.Request, stream bool) (*http.Response, error) {req.Stream = streambody, _ := json.Marshal(req)httpReq, err := http.NewRequestWithContext(ctx,"POST",d.Cfg.BaseURL+"/chat/completions",bytes.NewReader(body),)// 设置请求头httpReq.Header.Set("Content-Type", "application/json")httpReq.Header.Set("Authorization", "Bearer "+apiKey)resp, err := d.Cfg.HTTPClient.Do(httpReq)if err != nil {return nil, &ai.Error{Model:   "deepseek",Code:    http.StatusInternalServerError,Message: fmt.Sprintf("HTTP error: %v", err),}}if resp.StatusCode != http.StatusOK {return nil, &ai.Error{Model:   "deepseek",Code:    http.StatusInternalServerError,Message: fmt.Sprintf("failed to request: %v", err),}}return resp, nil
}func (d *DeepSeek) handleStreaming(ctx context.Context, req ai.Request) (<-chan ai.Response, error) {ch := make(chan ai.Response)go func() {defer close(ch)// 发起流式请求resp, err := d.doRequest(ctx, req, true)if err != nil {ch <- ai.Response{Content: "request error!"}return}defer resp.Body.Close()scanner := bufio.NewScanner(resp.Body)for scanner.Scan() {select {case <-ctx.Done():ch <- ai.Response{Content: "ctx done!"}returndefault:// 解析事件流event := parseEvent(scanner.Bytes())if event != nil {ch <- *event}}}}()return ch, nil
}func parseEvent(line []byte) *ai.Response {// 处理事件流格式if !bytes.HasPrefix(line, []byte("data: ")) {return nil}payload := bytes.TrimPrefix(line, []byte("data: "))if string(payload) == "[DONE]" {return nil}// 解析响应结构var chunk struct {Choices []struct {Delta struct {Content string `json:"content"`}FinishReason string `json:"finish_reason"`}}if err := json.Unmarshal(payload, &chunk); err != nil {return nil}if len(chunk.Choices) > 0 {content := chunk.Choices[0].Delta.ContentfinishReason := chunk.Choices[0].FinishReasonif content != "" {return &ai.Response{Content: content}}if finishReason == "stop" {return nil}}return nil
}

5. 调用使用

func main() {cfg := ai.Config{BaseURL:    "https://api.deepseek.com/",APIKey:     "key",HTTPClient: &http.Client{},}// 初始化deepseekd := deepseek.NewDeepSeek(cfg)// 封装请求体body := ai.Request{Model:    "deepseek-chat",Messages: []ai.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)for chunk := range stream {fmt.Printf(chunk.Content)}
}

3.响应实例

// 同步
{"id":"","object":"chat.completion","created":,"model":"deepseek-chat","choices":[{"index":0,"message":{"role":"assistant","content":"您好!我是由中国的深度求索(DeepSeek)公司开发的何任何问题,我会尽我所能为您提供帮助。"},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":37,"total_tokens":47,"prompt_tokens_details":{"cached_tokens":0},"prompt_cache_hit_tokens":0,"proms":10},"system_fingerprint":"fp_3a5770e1b4"}// 流式
您好!我是由中国的深度求索(DeepSeek)公司开发的智能助手DeepSeek-V3。如您有任何任何问题,我会尽我所能为您提供帮助。

代码地址:https://gitee.com/li-zhuoxuan/go_ai


文章转载自:

http://5I7bGd5x.tnLnq.cn
http://X4Ijzv2d.tnLnq.cn
http://Z32Ljjur.tnLnq.cn
http://mIjoSZqJ.tnLnq.cn
http://mFmLGwVy.tnLnq.cn
http://WuNItTVA.tnLnq.cn
http://WgkLJTC0.tnLnq.cn
http://RH2z2YIT.tnLnq.cn
http://T7j0FBmD.tnLnq.cn
http://5UximSX8.tnLnq.cn
http://n0hOL5fP.tnLnq.cn
http://yhcfcjBB.tnLnq.cn
http://WyV77jP9.tnLnq.cn
http://vLswLdED.tnLnq.cn
http://HBJOzhSO.tnLnq.cn
http://oQDZW522.tnLnq.cn
http://2npJrrYO.tnLnq.cn
http://p66MnPDL.tnLnq.cn
http://4hD3jqB7.tnLnq.cn
http://ukw8rVgm.tnLnq.cn
http://K2yPFo98.tnLnq.cn
http://L3xxFV5j.tnLnq.cn
http://7grhUzfG.tnLnq.cn
http://t9OTDD5z.tnLnq.cn
http://PS0LeMqV.tnLnq.cn
http://h4VqXb84.tnLnq.cn
http://gucs0r4g.tnLnq.cn
http://q4Gaik5y.tnLnq.cn
http://5fugu0c0.tnLnq.cn
http://U1YquUI5.tnLnq.cn
http://www.dtcms.com/wzjs/728843.html

相关文章:

  • 长春建设网站展览展厅设计案例
  • 上海做网站要多少钱app下载排行榜
  • 女性做网站很有名的室内装饰设计师国家职业技能标准
  • 做网站编程用什么语言好苏州网站开发的企业
  • 广告网站设计哪家快arcengine网站开发
  • 最简单的制作网站搭建WordPress教程
  • 资阳房产网站建设东莞核酸检测时间
  • asp.net 开发网站开发长沙小程序公司
  • 网站制作的核心要点是什么erp系统软件有哪些
  • 继电器做网站东莞大型企业网站建设
  • 网站设计软件开发网站建设课程报告
  • 做网站的无锡英文版企业网站布局设计
  • 国外哪些网站可以注册域名尚层装饰官网
  • 郑州自助建站模板如何建设高等数学课程网站
  • 宿州网站开发公司宁波seo排名方案优化
  • 宜春市网站建设大连市城市建设投资集团网站
  • 什么是静态网站小程序开发平台找哪家好
  • 长春网站设计价格阿里巴巴网官网首页
  • 网站建设与维护成绩查询itme收录优美图片官网
  • 万云网络网站seo是什么意思为什么要做seo
  • 百度和阿里哪个厉害做网站宝安住房和建设局网站电话
  • 上海市城乡住房建设厅网站网站建设分哪些类别
  • 山东舜玉建设工程有限公司网站网站设计方案模板
  • 网站域名到期会怎么样做猎头顾问 经常看哪些网站
  • 手机网站怎么优化广州专业网站设计定制
  • 郑州网站优化顾问汽车网站建设开题报告
  • 建站域名哪个网站做任务可以赚钱
  • 国外有哪做交互设计网站网站建设技术服务清单
  • 杭州网站设计制作江苏个人备案网站内容
  • 建设高端网站大连网站制作培训