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

DeepSeek结合Langchain的基本用法

DeepSeek结合Langchain的基本用法

  • DeepSeek 基于Openai接口规范的Prompt应答
  • Deepseek结合Langchain
  • DeepSeek 基于langchain的结构化返回

DeepSeek 基于Openai接口规范的Prompt应答

首先我们需要先基于pip 安装

pip install openai

最开始我们先熟悉如何使用openai的接口规范,基于deepseek来实现的基础问答。代码接口如下:


from openai import OpenAI
client = OpenAI(api_key=api_key, base_url="https://api.deepseek.com")def get_completion(prompt, model="deepseek-chat"):# messages = [{"role": "user", "content": prompt}]response = client.chat.completions.create(model=model,messages=[{"role": "system", "content": "You are a helpful assistant"},{"role": "user", "content": prompt},],stream=False)return responseresp = get_completion("What is 1+1?")
print(resp)
print(resp.choices[0].message.content)

我们这类 1+ 1 等于几,大模型回答如下:
在这里插入图片描述
往往为了复用某些功能,就需要我们针对某一类问题设计模版,能够基于不同的问题,替换不同的具体问题,如何来使用模版功能,如下所示这里我们需要转换文本,使用一种新的表达style 基于 llm改造文本内容:

# 模版开发
customer_email = """
Arrr, I be fuming that me blender lid \
flew off and splattered me kitchen walls \
with smoothie! And to make matters worse,\
the warranty don't cover the cost of \
cleaning up me kitchen. I need yer help \
right now, matey!
"""
style = """American English \
in a calm and respectful tone
"""
prompt = f"""Translate the text \
that is delimited by triple backticks 
into a style that is {style}.
text: ```{customer_email}```
"""response = get_completion(prompt)
print(response)
print('------------')print(response.choices[0].message.content)

在这里插入图片描述

Deepseek结合Langchain

首先我们需要先基于pip 安装

pip install langchain_openai langchain

我们实现上述类似逻辑,通过llm 基于同一段文本进行改造转换, 实现如下:


from langchain_openai import ChatOpenAIchat = ChatOpenAI(model='deepseek-chat',openai_api_key=api_key,openai_api_base='https://api.deepseek.com',max_tokens=1024
)template_string = """Translate the text \
that is delimited by triple backticks \
into a style that is {style}. \
text: ```{text}```
"""from langchain.prompts import ChatPromptTemplate
prompt_template = ChatPromptTemplate.from_template(template_string)
customer_style = """American English \
in a calm and respectful tone
"""
customer_email = """
Arrr, I be fuming that me blender lid \
flew off and splattered me kitchen walls \
with smoothie! And to make matters worse, \
the warranty don't cover the cost of \
cleaning up me kitchen. I need yer help \
right now, matey!
"""
customer_messages = prompt_template.format_messages(style=customer_style,text=customer_email)
# Call the LLM to translate to the style of the customer message
# Reference: chat = ChatOpenAI(temperature=0.0)
customer_response = chat.invoke(customer_messages, temperature=0)
print(customer_response.content)service_reply = """Hey there customer, \
the warranty does not cover \
cleaning expenses for your kitchen \
because it's your fault that \
you misused your blender \
by forgetting to put the lid on before \
starting the blender. \
Tough luck! See ya!
"""service_style_pirate = """\
a polite tone \
that speaks in English Pirate\
"""service_messages = prompt_template.format_messages(style=service_style_pirate,text=service_reply)service_response = chat.invoke(service_messages, temperature=0)
print(service_response.content)

在这里插入图片描述

DeepSeek 基于langchain的结构化返回

如何将llm返回的信息按照特定的结构返回信息,比如返回json数据格式。 我们还是按照上面的例子来进行改造: 首先我们返回的数据结构长什么样子:
在这里插入图片描述
因此需要设计输出的schema要求:


gift_schema = ResponseSchema(name="gift",description="Was the item purchased\as a gift for someone else? \Answer True if yes,\False if not or unknown.")
delivery_days_schema = ResponseSchema(name="delivery_days",description="How many days\did it take for the product\to arrive? If this \information is not found,\output -1.")response_schemas = [gift_schema,delivery_days_schema]

我们定义了返回的数据结构,gift True or False, delivery_days 返回时间 默认值-1.

from langchain_openai import ChatOpenAI
from langchain.output_parsers import ResponseSchema
from langchain.output_parsers import StructuredOutputParser
from langchain.prompts import ChatPromptTemplatechat = ChatOpenAI(model='deepseek-chat',openai_api_key=api_key,openai_api_base='https://api.deepseek.com',max_tokens=1024
)gift_schema = ResponseSchema(name="gift",description="Was the item purchased\as a gift for someone else? \Answer True if yes,\False if not or unknown.")
delivery_days_schema = ResponseSchema(name="delivery_days",description="How many days\did it take for the product\to arrive? If this \information is not found,\output -1.")response_schemas = [gift_schema,delivery_days_schema]
output_parser = StructuredOutputParser.from_response_schemas(response_schemas)
print(output_parser)
format_instructions = output_parser.get_format_instructions()
print(format_instructions)customer_review = """\
This leaf blower is pretty amazing.  It has four settings:\
candle blower, gentle breeze, windy city, and tornado. \
It arrived in two days, just in time for my wife's \
anniversary present. \
I think my wife liked it so much she was speechless. \
So far I've been the only one using it, and I've been \
using it every other morning to clear the leaves on our lawn. \
It's slightly more expensive than the other leaf blowers \
out there, but I think it's worth it for the extra features.
"""review_template = """\
For the following text, extract the following information:gift: Was the item purchased as a gift for someone else? \
Answer True if yes, False if not or unknown.delivery_days: How many days did it take for the product \
to arrive? If this information is not found, output -1.Format the output as JSON with the following keys:
gift
delivery_daystext: {text}
"""prompt = ChatPromptTemplate.from_template(template=review_template)
messages = prompt.format_messages(text=customer_review,format_instructions=format_instructions)response = chat.invoke(messages, temperature=0)
output_dict = output_parser.parse(response.content)
print(output_dict)

在这里插入图片描述

相关文章:

DeepSeek结合Langchain的基本用法

DeepSeek结合Langchain的基本用法 DeepSeek 基于Openai接口规范的Prompt应答Deepseek结合LangchainDeepSeek 基于langchain的结构化返回 DeepSeek 基于Openai接口规范的Prompt应答 首先我们需要先基于pip 安装 pip install openai最开始我们先熟悉如何使用openai的接口规范&a…...

Redis持久化的两种方式:RDB和AOF

redis中的数据存储在缓存中,如果没有持久化的策略,Redis一旦宕机,那么将会导致数据丢失;因此redis提供了以下两种持久化方式:RDB和AOF 一般来说,大部分公司对这两种方式都是同时开启的 一、RDB RDB策略全…...

每日一题——131.分割回文串

题目链接&#xff1a;131. 分割回文串 - 力扣&#xff08;LeetCode&#xff09; 代码&#xff1a; class Solution { private:vector<vector<string>> result;vector<string> path;void backtracking (const string& s,int startindex){if(startindex …...

内容中台赋能人工智能技术提升业务创新能力

内容概要 在当今快速变化的市场环境中&#xff0c;企业需要不断寻求创新以保持竞争力。内容中台作为一种新型的内容管理架构&#xff0c;能够极大地提升企业在内容创建、管理和分发方面的效率。通过与人工智能技术的深度融合&#xff0c;企业能够将海量的数据和信息转化为有价…...

第七节 文件与流

基本的输入输出&#xff08;iostream&#xff09; C标准库提供了一组丰富的输入/输出功能&#xff0c;C的I/O发生在流中&#xff0c;流是字节序列。如果字节流是从设备&#xff08;键盘、磁盘驱动器、网络连接等&#xff09;流向内存&#xff0c;叫做输入操作。如果字节流是从…...

软件工程 项目管理

软件项目管理中可以分成两部分: 软件创新 软件项目管理项目是定义明确的任务&#xff0c;这是为了实现某个目标&#xff08;例如&#xff0c;软件开发和交付&#xff09;进行的一系列操作的集合。一个项目可以表征为: 每个项目都可以有一个独特而鲜明的目标。 项目不是日常活…...

通过类加载和初始化的一些题目理解Java类加载过程

通过题目重点理解&#xff1a;Class加载流程和运行时区域 目录 子类和父类static变量父子类加载顺序2class.forName初始化 子类和父类static变量 class Parent {static int a 1;static int b 2;static int c;static {c 3;System.out.println("parent static block&quo…...

LLMs之DeepSeek r1:TinyZero的简介、特点、安装和使用方法、案例应用Logic-RL的简介、安装和使用方法、案例应用之详细攻略

LLMs之DeepSeek r1&#xff1a;TinyZero的简介、特点、安装和使用方法、案例应用Logic-RL的简介、安装和使用方法、案例应用之详细攻略 目录 TinyZero的简介 1、TinyZero的特点 TinyZero的安装和使用方法 1、安装 创建 conda 环境 数据准备 (倒计时任务) 多GPU (适用于 …...

爬取豆瓣电影 Top250 数据的脚本及调整方法

以下是一个完整的 Python 脚本,用于爬取豆瓣电影 Top250 的数据,包括电影名称、评分和短评。同时,我将提供应对豆瓣页面结构更新和反爬虫机制的调整方法。 安装必要的库 首先,确保安装了必要的库: bash复制 pip install requests beautifulsoup4 pandas示例代码 Pyth…...

Deepseek 接入Word处理对话框(隐藏密钥)

硅基流动邀请码&#xff1a;1zNe93Cp 邀请链接&#xff1a;网页链接 亲测deepseek接入word&#xff0c;自由调用对话&#xff0c;看截图有兴趣的复用代码&#xff08;当然也可以自己向deepseek提问&#xff0c;帮助你完成接入&#xff0c;但是提问逻辑不一样给出的答案是千差万…...

Jupyter Notebook自动保存失败等问题的解决

一、未生成配置文件 需要在命令行中&#xff0c;执行下面的命令自动生成配置文件 jupyter notebook --generate-config 执行后会在 C:\Users\用户名\.jupyter目录中生成文件 jupyter_notebook_config.py 二、在网页端打开Jupyter Notebook后文件保存失败&#xff1b;运行代码…...

基于机器学习时序库pmdarima实现时序预测

目录 一、Pmdarima实现单变量序列预测1.1 核心功能与特性1.2 技术优势对比1.3 python案例1.3.1 时间序列交叉验证1.3.1.1 滚动交叉验证1.3.1.2 滑窗交叉验证 时间序列相关参考文章&#xff1a; 时间序列预测算法—ARIMA 基于VARMAX模型的多变量时序数据预测 基于机器学习时序库…...

Dart语言的云计算

Dart语言在云计算中的应用 引言 云计算作为一种新兴的计算模式&#xff0c;为各行各业带来了重大变革。借助于云计算&#xff0c;用户可以通过互联网获取和使用各种资源&#xff0c;如计算能力、存储、数据库等。随着云计算的快速发展&#xff0c;编程语言的选择变得愈发重要…...

每日一题--数组中只出现一次的两个数字

数组中只出现一次的两个数字 题目描述数据范围提示 示例示例1示例2 题解解题思路位运算方法步骤&#xff1a; 代码实现代码解析时间与空间复杂度按位与操作获取最小位1的原理为什么选择最低有效的 1 位而不是其他位&#xff1f; 题目描述 一个整型数组里除了两个数字只出现一次…...

【数据】数据领域常用名词解释(第一批40个)+ 例子

导读&#xff1a;这些名词解释是基于数据领域的基本原理、技术方法、行业实践以及政策规范等多方面因素综合制定的&#xff0c;旨在为社会各界提供统一、权威的参考标准&#xff0c;推动数据领域的健康有序发展。 目录 数据 原始数据 数据资源 数据要素 数据产品和服务 数…...

Java | RESTful 接口规范

关注&#xff1a;CodingTechWork 引言 作为一名程序员&#xff0c;制定清晰、一致且高效的 RESTful 接口规范对于团队的开发效率和项目的长期维护至关重要。本文将详细介绍 RESTful 接口的设计理念、请求方法分类、核心规范&#xff0c;以及正确和错误的示例&#xff0c;帮助团…...

Baklib优化数字化内容管理用科技提升商业效率与增值潜力

内容概要 在当今数字化迅速发展的时代&#xff0c;数字化内容管理已成为企业提升竞争力的重要手段。Baklib作为一款强大的智能优化内容管理系统&#xff0c;通过先进的科技手段&#xff0c;帮助企业在内容管理和数据整合方面实现高效运作。Baklib 是什么类型的工具&#xff0c…...

【AI日记】25.02.09

【AI论文解读】【AI知识点】【AI小项目】【AI战略思考】【AI日记】【读书与思考】【AI应用】 探索 探索 AI 应用 读书 书名&#xff1a;理解公司&#xff1a;产权、激励与治理作者&#xff1a;张维迎 律己 探索&#xff1a;8 小时作息&#xff1a;2:00-10:00短视频娱乐&am…...

Chrome浏览器原理及优化

1. 相关面试题 1.1. 请说说从输入 URL 到页面渲染完成的全过程 1. 输入URL,用户在浏览器的地址栏输入一个URL,并按下回车键; 2. DNS解析; 浏览器需要将域名转换为服务器的IP地址,以建立连接。 (1). 如果浏览器缓存、操作系统缓存或路由器缓存中已有该域名的IP地址,…...

2025_2_9 C语言中队列

1.队列&#xff08;先进先出&#xff09; 队列也是一种受限制的线性结构 它只能在一端添加元素&#xff0c;在另一端访问&#xff0c;删除元素 &#xff08;队首插入&#xff0c;队尾删除&#xff09; 因为链表实现没有数组实现快&#xff0c;所以队列大多数是用数组实现的 q…...

浏览器访问 AWS ECS 上部署的 Docker 容器(监听 80 端口)

✅ 一、ECS 服务配置 Dockerfile 确保监听 80 端口 EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]或 EXPOSE 80 CMD ["python3", "-m", "http.server", "80"]任务定义&#xff08;Task Definition&…...

Python爬虫实战:研究MechanicalSoup库相关技术

一、MechanicalSoup 库概述 1.1 库简介 MechanicalSoup 是一个 Python 库,专为自动化交互网站而设计。它结合了 requests 的 HTTP 请求能力和 BeautifulSoup 的 HTML 解析能力,提供了直观的 API,让我们可以像人类用户一样浏览网页、填写表单和提交请求。 1.2 主要功能特点…...

MPNet:旋转机械轻量化故障诊断模型详解python代码复现

目录 一、问题背景与挑战 二、MPNet核心架构 2.1 多分支特征融合模块(MBFM) 2.2 残差注意力金字塔模块(RAPM) 2.2.1 空间金字塔注意力(SPA) 2.2.2 金字塔残差块(PRBlock) 2.3 分类器设计 三、关键技术突破 3.1 多尺度特征融合 3.2 轻量化设计策略 3.3 抗噪声…...

基于距离变化能量开销动态调整的WSN低功耗拓扑控制开销算法matlab仿真

目录 1.程序功能描述 2.测试软件版本以及运行结果展示 3.核心程序 4.算法仿真参数 5.算法理论概述 6.参考文献 7.完整程序 1.程序功能描述 通过动态调整节点通信的能量开销&#xff0c;平衡网络负载&#xff0c;延长WSN生命周期。具体通过建立基于距离的能量消耗模型&am…...

【Java学习笔记】Arrays类

Arrays 类 1. 导入包&#xff1a;import java.util.Arrays 2. 常用方法一览表 方法描述Arrays.toString()返回数组的字符串形式Arrays.sort()排序&#xff08;自然排序和定制排序&#xff09;Arrays.binarySearch()通过二分搜索法进行查找&#xff08;前提&#xff1a;数组是…...

8k长序列建模,蛋白质语言模型Prot42仅利用目标蛋白序列即可生成高亲和力结合剂

蛋白质结合剂&#xff08;如抗体、抑制肽&#xff09;在疾病诊断、成像分析及靶向药物递送等关键场景中发挥着不可替代的作用。传统上&#xff0c;高特异性蛋白质结合剂的开发高度依赖噬菌体展示、定向进化等实验技术&#xff0c;但这类方法普遍面临资源消耗巨大、研发周期冗长…...

在四层代理中还原真实客户端ngx_stream_realip_module

一、模块原理与价值 PROXY Protocol 回溯 第三方负载均衡&#xff08;如 HAProxy、AWS NLB、阿里 SLB&#xff09;发起上游连接时&#xff0c;将真实客户端 IP/Port 写入 PROXY Protocol v1/v2 头。Stream 层接收到头部后&#xff0c;ngx_stream_realip_module 从中提取原始信息…...

第25节 Node.js 断言测试

Node.js的assert模块主要用于编写程序的单元测试时使用&#xff0c;通过断言可以提早发现和排查出错误。 稳定性: 5 - 锁定 这个模块可用于应用的单元测试&#xff0c;通过 require(assert) 可以使用这个模块。 assert.fail(actual, expected, message, operator) 使用参数…...

Python爬虫(一):爬虫伪装

一、网站防爬机制概述 在当今互联网环境中&#xff0c;具有一定规模或盈利性质的网站几乎都实施了各种防爬措施。这些措施主要分为两大类&#xff1a; 身份验证机制&#xff1a;直接将未经授权的爬虫阻挡在外反爬技术体系&#xff1a;通过各种技术手段增加爬虫获取数据的难度…...

今日科技热点速览

&#x1f525; 今日科技热点速览 &#x1f3ae; 任天堂Switch 2 正式发售 任天堂新一代游戏主机 Switch 2 今日正式上线发售&#xff0c;主打更强图形性能与沉浸式体验&#xff0c;支持多模态交互&#xff0c;受到全球玩家热捧 。 &#x1f916; 人工智能持续突破 DeepSeek-R1&…...