deepseek 调用方法


c

1. deepseek 调用方法

1.1. API_KEY设置

  1. 设置URL = "https://deepseek.com/chat/completions/"

  2. 导入系统变量,借助os

    os.getenv("变量名称", default = 默认值)
    

1.2. 请求头

  1. authorization : Bearer API_KEY, 认证信息
  2. Content-Type: application/json, 请求内容格式,post 仅能使用Json
header = {
    "authorization": f"Bearer {API_KEY}"
    "Content-Type": "application/json",
}

1.3. 请求内容payload

  1. model: 选择模型
  2. messages: 发送的内容数组
    1. role:角色
    2. content: 内容
  3. temperature: 设置为 0 ,模型输出更加稳定, 1,模型输出更发散
payload = {
    "model": deepseek-chat,
    "messages":[
        {"role": "system", "content":"命令要求" }{"role": "User", "content": "用户输入"},
        {"role": ""}
    ]
}

1.4. 发送请求

发送内容,使用post请求

resp = requests.post(url, header = header, payload = payload, timeout =timeout)

1.5. response 返回内容

返回内容在resp.json()['choices'][0]['message']['content'], 提取出结果并返回

image-20250902102742498

2. 翻译

  1. 将文本块切分成小段,指定分块大小,存放在数组中

  2. 对分段后每一段进行翻译

    2.1. for 遍历

    1. for i in 迭代器

      迭代器: 列表等

    2. for idx, ck in enumerate(n):

    3. for i in range(1, n) :

      范围是[1,n)

3. day3

  1. 输入错误: EOFerror

  2. requests.post 发送请求时,需要包裹在try

  3. requests发送数据,解析数据检查

    1. 检查requests是否接收

      except requests.exception.RequestException as e

    2. 检查网络是否

      resp.ok

    3. 数据转换是否成json

      except ValueError

    4. 是否可以从数据中提取出值

      `except {KeyError, IndexError, TypeError}

3.1. 使用超时重传发送

如果遇到rest请求错误,或者返回的resq状态码有问题,使用退避算法,进行规避n次,超过则返回

  1. 重复遍历n
  2. 如果遇到请求错误,查看是否超过重复次数,没有,time.sleep一段时间后,再次运行重传
  3. 超过重复请求后,返回错误

4. day4

4.1. markdown 渲染

使用rich

from rich.console import Console
from rich.markdown import Markdown

console = Console()
markdown_string = """"""
markdown = Markdown(markdown_string)
console

4.2. 输出markdown 到word 文件中

  1. 首先检查文件目录存在
  import os
  output_dir = os.path.dirname(output_file)
  if output_dir and not os.path.exist(output_dir):
         os.makedirs(output_dir)
  1. 使用pypandoc输出
import pypandoc
"""
    to: "目标格式"
    format:"当前格式"
    outputfile: "输出文件"
"""
pypandoc.convert_text(makedown_string, to= 'docx', format = 'markdown', outputfile = output_filepath)
  1. 同时可以尝试检查ImportError , Exception等错误

4.2.1. 直接调用pandoc 命令行工具

  1. 创建临时文件.md存储markdown内容

    temp_md_file = "temp.md"
    with open(temp_md_file, 'w', encoding= 'utf-8') as f:
        f.write(m_str)
    
  2. 使用subprocess.run执行命令

    import subprocess
    command = ['pandoc', '-f', 'markdown', 't','doc', 'o', output_filename, temp_md_file]
    result = subprocess.run(command, capture_output = True, text = True, encoding = 'utf-8')
    if result.returncode == 0:
        return "转换正确"
    
  3. 最后删除临时文件

    if os.path.exist(temp_md_file):
        os.remove(temp_md_file)
    

5. 9.8

win11 主要文件夹路径

任务栏:C:\Users\用户名\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar

开始菜单:C:\ProgramData\Microsoft\Windows\Start Menu\Programs

IE开始菜单C:\Users\用户名\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu

6. 9.10

6.1. path类

from pathlib import Path
p_path = Path(路径)
# 组合路径
config_path = p_path / "config.txt" 
.name # 文件名
.suffix # 文件后缀
.stem # 无后缀的文件名
.parent # 父目录
.is_absolute # 是否为祖先路径
.revolve() # 转换为相对路径


# 创建文件
# parents=True 会创建所有不存在的父目录
# exist_ok=True 避免目录已存在时报错
Path(路径).mkdir(exist_ok = True, parents = True)
Path(路径).touch()  # 创建空文件

p_path.write_text(str) # 写入文件
content = file.read_text() # 读取文件内容

文章作者: 小白菜
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小白菜 !
评论
  目录