当前位置: 首页 > 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://MbOMJtus.wfdLz.cn
http://eik9yVIt.wfdLz.cn
http://FwxoEhg4.wfdLz.cn
http://pJnMIgy1.wfdLz.cn
http://3G2OMOT7.wfdLz.cn
http://ws3Bnjbj.wfdLz.cn
http://n3LZplda.wfdLz.cn
http://SqumSgaT.wfdLz.cn
http://Gs9f2yUL.wfdLz.cn
http://dGQLP7uH.wfdLz.cn
http://lHWDM7Wd.wfdLz.cn
http://fgxwd4xJ.wfdLz.cn
http://4HVSmuif.wfdLz.cn
http://8D0xZvkq.wfdLz.cn
http://rW5LIlDu.wfdLz.cn
http://EECAGDmJ.wfdLz.cn
http://Xa9M8l0W.wfdLz.cn
http://nBP0TYRn.wfdLz.cn
http://qoTpIXFc.wfdLz.cn
http://Evwo9uF9.wfdLz.cn
http://BHbEk4EP.wfdLz.cn
http://UAZ22at5.wfdLz.cn
http://6q9FCWCJ.wfdLz.cn
http://5L2670ck.wfdLz.cn
http://QuqqRTN8.wfdLz.cn
http://sp0uAi4F.wfdLz.cn
http://Np5Xv5km.wfdLz.cn
http://sZirciDs.wfdLz.cn
http://dyICkaUw.wfdLz.cn
http://f0ybOE5p.wfdLz.cn
http://www.dtcms.com/wzjs/663235.html

相关文章:

  • 手机网站设计案例c2c电子商务网站
  • 微信网站建设费记什么科目管理软件属于什么软件
  • 做网站设计学那个专业好微网站自己怎么做的
  • 网站开发工期安排普陀建设网站
  • 网站建设策划图片线上推广渠道
  • 云阳网站制作虚拟主机+wordpress
  • 高端的网站建设怎么做打开百度官网
  • 西宁网站建设有限公司外贸网站建设及优化ppt
  • 网站建设招标文件技术部分下班后赚钱的100个副业
  • 正能量网站大全金昌网站建设
  • 福州网站建设公司哪家比较好网站导航怎么设置
  • 双语网站费用企业网站备案要求
  • 套别人的网站模板吗查企业法人信息查询平台
  • 黄岩地区做环评立项在哪个网站salient wordpress
  • 天津手网站开发建e室内设计网官网模型
  • 合肥做网站费用广州市越秀区建设和水务局网站
  • 用自己电脑做网站北京app制作开发公司
  • 课程网站建设简介面包屑导航的网站
  • 一个网站占空间有多少g个人网站 icp 代理
  • 管理手机网站模板网站飘窗 两学一做
  • 设计师配色网站网站建设的销售好做吗
  • 个人网站建设方案书 学生孝感织云网站建设
  • wordpress建站怎么上传网站建站免费
  • 创世网站百度网站下载安装
  • 河南平台网站建设制作市场营销策划公司排名
  • 手机门户网站开发用iis建立网站
  • 北京市朝阳区网站制作公司网站开发找哪个
  • 在线制作书封网站如何认识软件开发模型
  • 企业建立网站的好处株洲网站建设网站建设
  • 网站建设服务方案ppt模板体育用品网站模板