本文主要是介绍python通过curl实现访问deepseek的API,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
《python通过curl实现访问deepseek的API》这篇文章主要为大家详细介绍了python如何通过curl实现访问deepseek的API,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编...
API申请和充值
下面是deepeek的API网站
https://platform.deepseek.com/
进去先注册,是不是手机账号密码都不重要,都一样,完事充值打米,主要是打米后左侧API Keys里面创建一个API Keys,注意自己手抄一个Key,那个你自己完了也打不开而是一堆******,记不住只能重新生成
本地curl访问代码脚本
部分参数意义和选项在代码里标注了
import subprocess import json import os def call_deepseek_api(prompt, api_key="sk-0d83************f3a3461486", model="deepseek-chat", temperature=0.7, max_tokens=1000 ): """ 使用cURL调用DeepSeek API 参数: - prompt: 提示文本 - api_key: DeepSeek API密钥,如果未提供则从环境变量获取 - model: 要使用的模型名称 通过指定 model='deepseek-chat' 即可调用 DeepSeek-V3。 通过指定 model='deepseek-reasoner',即可调用 DeepSeek-R1。 - temperature: 控制随机性的温度参数(随机性,越低越选择概率高的答案,最高1,最低0,0.7时均衡,0.2时死板,1时灵活) - max_tokens: 生成的最大token数(计费是通过token,模型的分词器(Tokenizer)决定,粗略的说,1 个单词 ≈ 1.3 个 Token,1 个汉字 ≈ 1~1.5 个 Token,单次费用=输入token*0.0001+输出token*0.0003 返回: - API响应的JSON解析结果 """ # 如果未提供API密钥,则从环境变量获取 if api_key is None: api_key = os.environ.get("DEEPSEEK_API_KEY") if not api_key: raise ValueError("需要提供DeepSeek API密钥") # 构建API请求的JSON数据 request_data = { "model": model, "messages": [{"role": "user", "content": prompt}], "temperaphpture": temperature, "max_tokens": max_tokens, "stream":False } # 构建cURL命令 #这里可能存在一个问题,访问地址可能是"https://api.deepseek.com/chat/completions" curl_cmd = [ "curl", "-X", "POST", "https://api.deepseek.com/v1/chat/completions", "-H", f"Authorization: Bearer {api_key}", "-H", "Content-Type: application/json", "-d", json.dumps(request_data) ] try: # 执行cURL命令 result = jssubprocess.run( curl_cmd, capture_output=True, text=True, encoding='utf-php8', check=True ) # 解析JSON响应 response = json.loads(result.stdout) return response except subprocess.CalledProcessError as e: print(f"API请求失败: {e.stderr}") raise except json.JSONDecodeError: print(f"无法解析API响应: {result.stdout}") raise # 使用示例 if __name__ == "__main__": # 方式1: 通过环境变量设置API密钥 # os.environ["DEEPSEEK_API_KEY"] = "your_api_key_here" # 方式2: 直接在函数调用中提供API密钥 api_key = "sk-0d8*******f3a3461486" # 调用API try: response = call_deepseek_api( prompt="你好,请介绍一下你自己", api_key=api_key ) # 打印API返回的内容 if "choices" in response and len(response["choices"]) > 0: message = response["choices"][0]["message"]["content"] print("API响应:") print(message) else: print("API返回格式异常:", responsChina编程e) except Exception as e: print(f"发生错误: {e}")
这里是上面代码尝试跑起来的结果
到此这篇关于python通过curl实现访问deepseek的API的文章就介绍到这了,更多相关python访问deepseek API内容请搜索编程China编程(www.chinasem.cn)以前的文章或继续浏览www.chinasem.cn下面的相关文章希望大家以后多多支持China编程(www.chinasem.cn)!
这篇关于python通过curl实现访问deepseek的API的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!