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

SkyWalking 10.2.0 SWCK 配置过程

SkyWalking 10.2.0 & SWCK 配置过程 skywalking oap-server & ui 使用Docker安装在K8S集群以外&#xff0c;K8S集群中的微服务使用initContainer按命名空间将skywalking-java-agent注入到业务容器中。 SWCK有整套的解决方案&#xff0c;全安装在K8S群集中。 具体可参…...

DeepSeek 赋能智慧能源:微电网优化调度的智能革新路径

目录 一、智慧能源微电网优化调度概述1.1 智慧能源微电网概念1.2 优化调度的重要性1.3 目前面临的挑战 二、DeepSeek 技术探秘2.1 DeepSeek 技术原理2.2 DeepSeek 独特优势2.3 DeepSeek 在 AI 领域地位 三、DeepSeek 在微电网优化调度中的应用剖析3.1 数据处理与分析3.2 预测与…...

工业安全零事故的智能守护者:一体化AI智能安防平台

前言&#xff1a; 通过AI视觉技术&#xff0c;为船厂提供全面的安全监控解决方案&#xff0c;涵盖交通违规检测、起重机轨道安全、非法入侵检测、盗窃防范、安全规范执行监控等多个方面&#xff0c;能够实现对应负责人反馈机制&#xff0c;并最终实现数据的统计报表。提升船厂…...

Java 8 Stream API 入门到实践详解

一、告别 for 循环&#xff01; 传统痛点&#xff1a; Java 8 之前&#xff0c;集合操作离不开冗长的 for 循环和匿名类。例如&#xff0c;过滤列表中的偶数&#xff1a; List<Integer> list Arrays.asList(1, 2, 3, 4, 5); List<Integer> evens new ArrayList…...

Redis相关知识总结(缓存雪崩,缓存穿透,缓存击穿,Redis实现分布式锁,如何保持数据库和缓存一致)

文章目录 1.什么是Redis&#xff1f;2.为什么要使用redis作为mysql的缓存&#xff1f;3.什么是缓存雪崩、缓存穿透、缓存击穿&#xff1f;3.1缓存雪崩3.1.1 大量缓存同时过期3.1.2 Redis宕机 3.2 缓存击穿3.3 缓存穿透3.4 总结 4. 数据库和缓存如何保持一致性5. Redis实现分布式…...

【Zephyr 系列 10】实战项目:打造一个蓝牙传感器终端 + 网关系统(完整架构与全栈实现)

🧠关键词:Zephyr、BLE、终端、网关、广播、连接、传感器、数据采集、低功耗、系统集成 📌目标读者:希望基于 Zephyr 构建 BLE 系统架构、实现终端与网关协作、具备产品交付能力的开发者 📊篇幅字数:约 5200 字 ✨ 项目总览 在物联网实际项目中,**“终端 + 网关”**是…...

算法:模拟

1.替换所有的问号 1576. 替换所有的问号 - 力扣&#xff08;LeetCode&#xff09; ​遍历字符串​&#xff1a;通过外层循环逐一检查每个字符。​遇到 ? 时处理​&#xff1a; 内层循环遍历小写字母&#xff08;a 到 z&#xff09;。对每个字母检查是否满足&#xff1a; ​与…...

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

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

R 语言科研绘图第 55 期 --- 网络图-聚类

在发表科研论文的过程中&#xff0c;科研绘图是必不可少的&#xff0c;一张好看的图形会是文章很大的加分项。 为了便于使用&#xff0c;本系列文章介绍的所有绘图都已收录到了 sciRplot 项目中&#xff0c;获取方式&#xff1a; R 语言科研绘图模板 --- sciRplothttps://mp.…...

shell脚本质数判断

shell脚本质数判断 shell输入一个正整数,判断是否为质数(素数&#xff09;shell求1-100内的质数shell求给定数组输出其中的质数 shell输入一个正整数,判断是否为质数(素数&#xff09; 思路&#xff1a; 1:1 2:1 2 3:1 2 3 4:1 2 3 4 5:1 2 3 4 5-------> 3:2 4:2 3 5:2 3…...