DeepSeek:解释应用、API及调用方法:

DeepSeek培训内容,解释应用、API及调用方法:


一、什么是应用?

定义:应用(Application)是解决特定需求的软件程序
例子

  • 微信(聊天)、支付宝(支付)、DeepSeek(AI服务)。
  • 可以是手机App、网页、或后台服务(如AI模型)。

核心作用:帮助用户完成具体任务,如翻译、推荐、数据分析。


二、什么是API?

定义:API(应用程序接口)是不同软件间通信的桥梁,允许开发者调用外部功能。

餐馆比喻

  • 菜单:API提供可用的功能列表(如“翻译文本”)---Get Post。
  • 点菜:你发送请求(如要翻译的文本)。
  • 上菜:API返回结果(如翻译后的文本)。

DeepSeek的API:提供AI能力(如生成文本、智能对话),无需自己开发模型,直接调用即可。


三、如何调用API?

核心步骤

  1. 获取API密钥:DS官网、阿里云百炼等。
  2. 查阅文档:找到API的地址(URL)、参数和格式。
  3. 发送请求:用代码发送HTTP请求(常用POST/GET)。
  4. 处理结果:接收返回的数据(通常为JSON格式),提取所需信息。

示例:用Python调用DeepSeek API

# 导入需要的包
from openai import OpenAI

# 初始化OpenAI客户端
client = OpenAI(
    api_key="your-api-key", # 获取API Key
    base_url="http://your-api-base-url/v1" # 获取URL
)

#调用模型
completion = client.chat.completions.create(
    model="deepseek-r1",  # 此处以 deepseek-r1 为例,可按需更换模型名称。
    messages=[
        {'role': 'user', 'content': '9.9和9.11谁大'}
        ]
)

# 通过reasoning_content字段打印思考过程
print("思考过程:")
print(completion.choices[0].message.reasoning_content)
# 通过content字段打印最终答案
print("最终答案:")
print(completion.choices[0].message.content)
输出示例

2、多轮对话:

# 导入包
import os
from openai import OpenAI

# 初始化OpenAI客户端
client = OpenAI(
    api_key="your-api-key", # 获取API Key
    base_url="http://your-api-base-url/v1" # 获取URL
)

# 通过 messages 数组实现上下文管理
messages = [
    {'role': 'user', 'content': '你好'}
]

# 调用模型
completion = client.chat.completions.create(
    model="deepseek-r1",  # 此处以 deepseek-r1 为例,可按需更换模型名称。
    messages=messages
)

print("="*20+"第一轮对话"+"="*20)
# 通过reasoning_content字段打印思考过程
print("="*20+"思考过程"+"="*20)
print(completion.choices[0].message.reasoning_content)
# 通过content字段打印最终答案
print("="*20+"最终答案"+"="*20)
print(completion.choices[0].message.content)

messages.append({'role': 'assistant', 'content': completion.choices[0].message.content})
messages.append({'role': 'user', 'content': '你是谁'})
print("="*20+"第二轮对话"+"="*20)
completion = client.chat.completions.create(
    model="deepseek-r1",  # 此处以 deepseek-r1 为例,可按需更换模型名称。
    messages=messages
)
# 通过reasoning_content字段打印思考过程
print("="*20+"思考过程"+"="*20)
print(completion.choices[0].message.reasoning_content)
# 通过content字段打印最终答案
print("="*20+"最终答案"+"="*20)
print(completion.choices[0].message.content)
输出示例

3、流式输出:

from openai import OpenAI
import os

# 初始化OpenAI客户端
client = OpenAI(
    api_key="your-api-key", # 获取API Key
    base_url="http://your-api-base-url/v1" # 获取URL
)

def main():
    reasoning_content = ""  # 定义完整思考过程
    answer_content = ""     # 定义完整回复
    is_answering = False   # 判断是否结束思考过程并开始回复

    # 创建聊天完成请求
    stream = client.chat.completions.create(
        model="deepseek-r1",  # 此处以 deepseek-r1 为例,可按需更换模型名称
        messages=[
            {"role": "user", "content": "9.9和9.11谁大"}
        ],
        stream=True # 流式输出
        # 解除以下注释会在最后一个chunk返回Token使用量
        # stream_options={
        #     "include_usage": True
        # }
    )

    print("\n" + "=" * 20 + "思考过程" + "=" * 20 + "\n")

    for chunk in stream:
        # 处理usage信息
        if not getattr(chunk, 'choices', None):
            print("\n" + "=" * 20 + "Token 使用情况" + "=" * 20 + "\n")
            print(chunk.usage)
            continue

        delta = chunk.choices[0].delta

        # 检查是否有reasoning_content属性
        if not hasattr(delta, 'reasoning_content'):
            continue

        # 处理空内容情况
        if not getattr(delta, 'reasoning_content', None) and not getattr(delta, 'content', None):
            continue

        # 处理开始回答的情况
        if not getattr(delta, 'reasoning_content', None) and not is_answering:
            print("\n" + "=" * 20 + "完整回复" + "=" * 20 + "\n")
            is_answering = True

        # 处理思考过程
        if getattr(delta, 'reasoning_content', None):
            print(delta.reasoning_content, end='', flush=True)
            reasoning_content += delta.reasoning_content
        # 处理回复内容
        elif getattr(delta, 'content', None):
            print(delta.content, end='', flush=True)
            answer_content += delta.content

    # 如果需要打印完整内容,解除以下的注释
    """
    print("=" * 20 + "完整思考过程" + "=" * 20 + "\n")
    print(reasoning_content)
    print("=" * 20 + "完整回复" + "=" * 20 + "\n")
    print(answer_content)
    """

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"发生错误:{e}")
输出示例

四、常见问题

  1. API密钥泄露怎么办?

    • 密钥相当于密码,需保密,不要上传到公开平台(如GitHub)。
  2. 如何知道API地址和参数?

    • DS官方文档,示例和参数说明通常很详细。
    • 阿里云百炼平台。
  3. 返回的数据看不懂?

    • 打印completion.json()查看结构。

五、总结

  • 应用:解决需求的软件(如DeepSeek提供AI服务)。
  • API:通过“菜单”调用外部功能,无需自己造轮子。
  • 调用流程:拿密钥 → 读文档 → 发请求 → 处理结果。

通过API,你可以快速将DeepSeek的AI能力集成到自己的应用中! 🚀

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容