当前位置: 首页 > 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…...

地震勘探——干扰波识别、井中地震时距曲线特点

目录 干扰波识别反射波地震勘探的干扰波 井中地震时距曲线特点 干扰波识别 有效波&#xff1a;可以用来解决所提出的地质任务的波&#xff1b;干扰波&#xff1a;所有妨碍辨认、追踪有效波的其他波。 地震勘探中&#xff0c;有效波和干扰波是相对的。例如&#xff0c;在反射波…...

UE5 学习系列(三)创建和移动物体

这篇博客是该系列的第三篇&#xff0c;是在之前两篇博客的基础上展开&#xff0c;主要介绍如何在操作界面中创建和拖动物体&#xff0c;这篇博客跟随的视频链接如下&#xff1a; B 站视频&#xff1a;s03-创建和移动物体 如果你不打算开之前的博客并且对UE5 比较熟的话按照以…...

为什么需要建设工程项目管理?工程项目管理有哪些亮点功能?

在建筑行业&#xff0c;项目管理的重要性不言而喻。随着工程规模的扩大、技术复杂度的提升&#xff0c;传统的管理模式已经难以满足现代工程的需求。过去&#xff0c;许多企业依赖手工记录、口头沟通和分散的信息管理&#xff0c;导致效率低下、成本失控、风险频发。例如&#…...

cf2117E

原题链接&#xff1a;https://codeforces.com/contest/2117/problem/E 题目背景&#xff1a; 给定两个数组a,b&#xff0c;可以执行多次以下操作&#xff1a;选择 i (1 < i < n - 1)&#xff0c;并设置 或&#xff0c;也可以在执行上述操作前执行一次删除任意 和 。求…...

【SQL学习笔记1】增删改查+多表连接全解析(内附SQL免费在线练习工具)

可以使用Sqliteviz这个网站免费编写sql语句&#xff0c;它能够让用户直接在浏览器内练习SQL的语法&#xff0c;不需要安装任何软件。 链接如下&#xff1a; sqliteviz 注意&#xff1a; 在转写SQL语法时&#xff0c;关键字之间有一个特定的顺序&#xff0c;这个顺序会影响到…...

Nginx server_name 配置说明

Nginx 是一个高性能的反向代理和负载均衡服务器&#xff0c;其核心配置之一是 server 块中的 server_name 指令。server_name 决定了 Nginx 如何根据客户端请求的 Host 头匹配对应的虚拟主机&#xff08;Virtual Host&#xff09;。 1. 简介 Nginx 使用 server_name 指令来确定…...

现代密码学 | 椭圆曲线密码学—附py代码

Elliptic Curve Cryptography 椭圆曲线密码学&#xff08;ECC&#xff09;是一种基于有限域上椭圆曲线数学特性的公钥加密技术。其核心原理涉及椭圆曲线的代数性质、离散对数问题以及有限域上的运算。 椭圆曲线密码学是多种数字签名算法的基础&#xff0c;例如椭圆曲线数字签…...

Android Bitmap治理全解析:从加载优化到泄漏防控的全生命周期管理

引言 Bitmap&#xff08;位图&#xff09;是Android应用内存占用的“头号杀手”。一张1080P&#xff08;1920x1080&#xff09;的图片以ARGB_8888格式加载时&#xff0c;内存占用高达8MB&#xff08;192010804字节&#xff09;。据统计&#xff0c;超过60%的应用OOM崩溃与Bitm…...

[ACTF2020 新生赛]Include 1(php://filter伪协议)

题目 做法 启动靶机&#xff0c;点进去 点进去 查看URL&#xff0c;有 ?fileflag.php说明存在文件包含&#xff0c;原理是php://filter 协议 当它与包含函数结合时&#xff0c;php://filter流会被当作php文件执行。 用php://filter加编码&#xff0c;能让PHP把文件内容…...

安卓基础(Java 和 Gradle 版本)

1. 设置项目的 JDK 版本 方法1&#xff1a;通过 Project Structure File → Project Structure... (或按 CtrlAltShiftS) 左侧选择 SDK Location 在 Gradle Settings 部分&#xff0c;设置 Gradle JDK 方法2&#xff1a;通过 Settings File → Settings... (或 CtrlAltS)…...