langchain循序渐进之langchain 安装及使用

langchain循序渐进之langchain 安装及使用

pip安装langchain

pip install langchain

安装langsmith(可选)

langsmith官方提示是用来观察大模型复杂调用情况,可选项。

[LangSmith]点击注册然后把秘钥填进去就行,这里我略过了

export LANGCHAIN_TRACING_V2="true"  
export LANGCHAIN_API_KEY="..."

体验langchain 几个过程

  • 构建一个简单的 LLM 链
  • 构建一个检索链
  • 构建一个能感知对话上线文的检索链
  • 构建一个包含智能体的检索链

试用一个简单的 LLM 链

安装langchain-openai

pip install langchain-openai

设置秘钥

export OPENAI_API_KEY="..."

使用前初始化

from langchain_openai import ChatOpenAI

llm = ChatOpenAI()

一旦你已经安装并初始化了所选的大型语言模型(LLM),我们就可以尝试使用它了!让我们问它"LangSmith是什么"——这是训练数据中不存在的内容,所以它可能不会有很好的回答。

llm.invoke("how can langsmith help with testing?")

我们还可以使用prompt提示模板来引导它的响应。提示模板将原始用户输入转换为更适合大型语言模型(LLM)的输入。

from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([    ("system", "You are a world class technical documentation writer."),    ("user", "{input}")])

我们可以直接传递文档来自己运行这个流程:

from langchain_core.documents import Document

document_chain.invoke({
    "input": "how can langsmith help with testing?",
    "context": [Document(page_content="langsmith can let you visualize test results")]
})

prompt和llm一起使用

from langchain_core.output_parsers import StrOutputParser  
output_parser = StrOutputParser()
// prompt 是提示,llm|output_parser将大语言模型输出的结构化chatmodel 变为字符串输出
chain = prompt | llm | output_parser
chain.invoke({"input": "how can langsmith help with testing?"})


目前整理如下,注意api_key要替换成自己的,并且有余额才行,无余额会报错

from langchain_openai import ChatOpenAI

llm = ChatOpenAI()
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a world class technical documentation writer."),
    ("user", "{input}")
])
from langchain_core.output_parsers import StrOutputParser

output_parser = StrOutputParser()
chain = prompt | llm | output_parser
result = chain.invoke({"input": "how can langsmith help with testing?"})
print(result)


我这里打印的结果是这样的(貌似每次输出都不一样啊,这里仅供参考)

Langsmith can help with testing in several ways:

Automated Testing: Langsmith can be used to generate test data for automated testing scripts. By creating realistic and diverse test data, Langsmith can help ensure comprehensive test coverage.

Performance Testing: Langsmith can generate large volumes of data to simulate real-world usage scenarios, allowing for performance testing of systems and applications under load.

Data Validation: Langsmith can be used to validate the accuracy and integrity of data by generating test data sets that cover various edge cases and boundary conditions.

Regression Testing: Langsmith can help streamline the testing process by quickly generating test data for regression testing, ensuring that new code changes do not introduce unexpected bugs or issues.

Overall, Langsmith can be a valuable tool for testing teams to improve the efficiency and effectiveness of their testing processes.

问题
注意chantgpt 需要有付费账号并有余额才行,否则会报错如下

openai.RateLimitError: Error code: 429 - {'error': {'message': 'You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.', 'type': 'insufficient_quota', 'param': None, 'code': 'insufficient_quota'}}


构建一个检索链 Retrieval Chain

为了恰当地回答原始问题(“langsmith如何帮助测试?”),我们需要为大型语言模型(LLM)提供额外的上下文。这可以通过检索来实现。当你有太多数据无法直接传递给LLM时,检索就很有用。然后,你可以使用检索器仅获取最相关的部分并将其传递进去。
在这个过程中,我们将从检索器中查找相关文档,然后将它们传递给提示。检索器可以由任何内容支持——SQL表、互联网等——但在这个例子中,我们将填充一个向量存储并使用它作为检索器。有关向量存储的更多信息,请参阅相关文档。
首先,我们需要加载我们想要索引的数据。为此,我们将使用WebBaseLoader。这需要安装BeautifulSoup:

pip install beautifulsoup4


之后我们可以导入并使用它

from langchain_community.document_loaders import WebBaseLoader
loader = WebBaseLoader("https://docs.smith.langchain.com/user_guide")
docs = loader.load()


接下来,我们需要将数据索引到向量存储中。这需要几个组件,即[embedding model]。

对于嵌入模型,我们再次提供通过API访问或运行本地模型的示例。 以openAI 为例

from langchain_openai import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()


安装向量数据库

pip install faiss-cpu


有了向量数据库我们就可以构建索引了

from langchain_community.vectorstores import FAISS
from langchain_text_splitters import RecursiveCharacterTextSplitter


text_splitter = RecursiveCharacterTextSplitter()
documents = text_splitter.split_documents(docs)
vector = FAISS.from_documents(documents, embeddings)


既然我们已经将数据索引到向量存储中,接下来我们将创建一个检索链。这个链将接受一个输入问题,查找相关文档,然后将这些文档与原始问题一起传递给大型语言模型(LLM),并请求它回答原始问题。

首先,让我们设置这个链,该链将接受一个问题以及检索到的文档,并生成一个答案。

from langchain.chains.combine_documents import create_stuff_documents_chain

prompt = ChatPromptTemplate.from_template("""Answer the following question based only on the provided context:

<context>
{context}
</context>

Question: {input}""")

from langchain_openai import ChatOpenAI
llm = ChatOpenAI()

document_chain = create_stuff_documents_chain(llm, prompt)


然而,我们希望文档首先来自我们刚刚设置的检索器。这样,我们就可以使用检索器动态选择最相关的文档,并将这些文档传递给给定的问题。

from langchain.chains import create_retrieval_chain

retriever = vector.as_retriever()
retrieval_chain = create_retrieval_chain(retriever, document_chain)


我们现在可以调用这个链。这将返回一个字典——大型语言模型(LLM)的响应位于“answer”键中。

response = retrieval_chain.invoke({"input": "how can langsmith help with testing?"})
print(response["answer"])

# LangSmith offers several features that can help with testing:...


最终我这里打印的返回是这样的(貌似每次输出都不一样啊,这里仅供参考):

LangSmith can help with testing in several ways:

Prototyping: LangSmith allows for quick experimentation between prompts, model types, retrieval strategies, and other parameters, enabling rapid understanding of how the model is performing and debugging where it is failing during the prototyping phase.

Debugging: LangSmith tracing provides clear visibility and debugging information at each step of an LLM sequence, making it easier to identify and root-cause issues when things go wrong.

Initial Test Set: Developers can create datasets and use them to run tests on their LLM applications. LangSmith also facilitates running custom evaluations to score test results.

Comparison View: LangSmith offers a user-friendly comparison view for test runs to track and diagnose regressions in test scores across multiple revisions of an application.

Playground: LangSmith provides a playground environment for rapid iteration and experimentation, allowing developers to quickly test out different prompts and models, and log every playground run in the system for future use.

Beta Testing: LangSmith enables the collection of data on how LLM applications are performing in real-world scenarios, aiding in the curation of test cases to track regressions/improvements and the development of automatic evaluations.

Capturing Feedback: Users can gather human feedback on the responses produced by their applications and attach feedback scores to logged traces, then filter on traces that have a specific feedback tag and score.

Adding Runs to a Dataset: LangSmith enables the addition of runs as examples to datasets, expanding test coverage on real-world scenarios as the application progresses through the beta testing phase.

Overall, LangSmith supports testing by providing visibility, debugging tools, test creation and execution capabilities, comparison views, and environments for rapid iteration and experimentation.

构建一个能感知对话上下文的检索链

到目前为止,我们创建的链只能回答单个问题。人们正在构建的LLM应用程序的主要类型之一是聊天机器人。那么我们如何将这个链变成一个可以回答后续问题的链呢? 我们仍然可以使用 create_retrieval_chain 函数,但我们需要更改两件事:

  1. 检索方法现在不应该只适用于最近的输入,而应该考虑整个历史。
  2. 最终的LLM链同样应该考虑整个历史

更新检索器

为了更新检索,我们将创建一个新的链。这个链将接收最新的输入(input)和对话历史(chat_history),并使用LLM生成搜索查询。

from langchain.chains import create_history_aware_retriever
from langchain_core.prompts import MessagesPlaceholder
# First we need a prompt that we can pass into an LLM to generate this search query
prompt = ChatPromptTemplate.from_messages([
    MessagesPlaceholder(variable_name="chat_history"),
    ("user", "{input}"),
    ("user", "Given the above conversation, generate a search query to look up to get information relevant to the conversation")
])
retriever_chain = create_history_aware_retriever(llm, retriever, prompt)


试用一下更新后检索器的效果

from langchain_core.messages import HumanMessage, AIMessage

chat_history = [HumanMessage(content="Can LangSmith help test my LLM applications?"), AIMessage(content="Yes!")]
retriever_chain.invoke({
    "chat_history": chat_history,
    "input": "Tell me how"
})


如果输出没问题,那么我们生成一个新的检索链

prompt = ChatPromptTemplate.from_messages([
    ("system", "Answer the user's questions based on the below context:\n\n{context}"),
    MessagesPlaceholder(variable_name="chat_history"),
    ("user", "{input}"),
])
document_chain = create_stuff_documents_chain(llm, prompt)

retrieval_chain = create_retrieval_chain(retriever_chain, document_chain)


调用新的检索链

chat_history = [HumanMessage(content="Can LangSmith help test my LLM applications?"), AIMessage(content="Yes!")]
retrieval_chain.invoke({
    "chat_history": chat_history,
    "input": "Tell me how"
})


输出如下(貌似每次输出都不一样啊,这里仅供参考):

LangSmith can help test your LLM applications by providing features like creating datasets for test cases, running custom evaluations, offering comparison views for different configurations, providing a playground environment for rapid iteration and experimentation, supporting beta testing with feedback collection and annotation queues, enabling feedback scoring on logged traces, allowing annotation of traces with different criteria, adding runs to datasets for real-world scenario coverage, and offering monitoring, A/B testing, automations, and thread views for multi-turn interactions.

如何学习AI大模型?

我在一线互联网企业工作十余年里,指导过不少同行后辈。帮助很多人得到了学习和成长。

我意识到有很多经验和知识值得分享给大家,也可以通过我们的能力和经验解答大家在人工智能学习中的很多困惑,所以在工作繁忙的情况下还是坚持各种整理和分享。但苦于知识传播途径有限,很多互联网行业朋友无法获得正确的资料得到学习提升,故此将并将重要的AI大模型资料包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来。

www.zeeklog.com  - langchain循序渐进之langchain 安装及使用

第一阶段: 从大模型系统设计入手,讲解大模型的主要方法;

第二阶段: 在通过大模型提示词工程从Prompts角度入手更好发挥模型的作用;

第三阶段: 大模型平台应用开发借助阿里云PAI平台构建电商领域虚拟试衣系统;

第四阶段: 大模型知识库应用开发以LangChain框架为例,构建物流行业咨询智能问答系统;

第五阶段: 大模型微调开发借助以大健康、新零售、新媒体领域构建适合当前领域大模型;

第六阶段: 以SD多模态大模型为主,搭建了文生图小程序案例;

第七阶段: 以大模型平台应用与开发为主,通过星火大模型,文心大模型等成熟大模型构建大模型行业应用。

www.zeeklog.com  - langchain循序渐进之langchain 安装及使用

👉学会后的收获:👈
• 基于大模型全栈工程实现(前端、后端、产品经理、设计、数据分析等),通过这门课可获得不同能力;

• 能够利用大模型解决相关实际项目需求: 大数据时代,越来越多的企业和机构需要处理海量数据,利用大模型技术可以更好地处理这些数据,提高数据分析和决策的准确性。因此,掌握大模型应用开发技能,可以让程序员更好地应对实际项目需求;

• 基于大模型和企业数据AI应用开发,实现大模型理论、掌握GPU算力、硬件、LangChain开发框架和项目实战技能, 学会Fine-tuning垂直训练大模型(数据准备、数据蒸馏、大模型部署)一站式掌握;

• 能够完成时下热门大模型垂直领域模型训练能力,提高程序员的编码能力: 大模型应用开发需要掌握机器学习算法、深度学习框架等技术,这些技术的掌握可以提高程序员的编码能力和分析能力,让程序员更加熟练地编写高质量的代码。

www.zeeklog.com  - langchain循序渐进之langchain 安装及使用
1.AI大模型学习路线图
2.100套AI大模型商业化落地方案
3.100集大模型视频教程
4.200本大模型PDF书籍
5.LLM面试题合集
6.AI产品经理资源合集

👉获取方式:
😝有需要的小伙伴,可以保存图片到wx扫描二v码免费领取【保证100%免费】🆓

www.zeeklog.com  - langchain循序渐进之langchain 安装及使用

Read more

安装 启动 使用 Neo4j的超详细教程

安装 启动 使用 Neo4j的超详细教程

最近在做一个基于知识图谱的智能生成项目。需要用到Neo4j图数据库。写这篇文章记录一下Neo4j的安装及其使用。 一.Neo4j的安装 1.首先安装JDK,配环境变量。(参照网上教程,很多) Neo4j是基于Java的图形数据库,运行Neo4j需要启动JVM进程,因此必须安装JAVA SE的JDK。从Oracle官方网站下载 Java SE JDK。我使用的版本是JDK1.8 2.官网上安装neo4j。 官方网址:https://neo4j.com/deployment-center/  在官网上下载对应版本。Neo4j应用程序有如下主要的目录结构: bin目录:用于存储Neo4j的可执行程序; conf目录:用于控制Neo4j启动的配置文件; data目录:用于存储核心数据库文件; plugins目录:用于存储Neo4j的插件; 3.配置环境变量 创建主目录环境变量NEO4J_HOME,并把主目录设置为变量值。复制具体的neo4j文件地址作为变量值。 配置文档存储在conf目录下,Neo4j通过配置文件neo4j.conf控制服务器的工作。默认情况下,不需

企业微信群机器人Webhook配置全攻略:从创建到发送消息的完整流程

企业微信群机器人Webhook配置全攻略:从创建到发送消息的完整流程 在数字化办公日益普及的今天,企业微信作为国内领先的企业级通讯工具,其群机器人功能为团队协作带来了极大的便利。本文将手把手教你如何从零开始配置企业微信群机器人Webhook,实现自动化消息推送,提升团队沟通效率。 1. 准备工作与环境配置 在开始创建机器人之前,需要确保满足以下基本条件: * 企业微信账号:拥有有效的企业微信管理员或成员账号 * 群聊条件:至少包含3名成员的群聊(这是创建机器人的最低人数要求) * 网络环境:能够正常访问企业微信服务器 提示:如果是企业管理员,建议先在"企业微信管理后台"确认机器人功能是否已对企业开放。某些企业可能出于安全考虑会限制此功能。 2. 创建群机器人 2.1 添加机器人到群聊 1. 打开企业微信客户端,进入目标群聊 2. 点击右上角的群菜单按钮(通常显示为"..."或"⋮") 3. 选择"添加群机器人"选项 4.

Flowise物联网融合:与智能家居设备联动的应用设想

Flowise物联网融合:与智能家居设备联动的应用设想 1. Flowise:让AI工作流变得像搭积木一样简单 Flowise 是一个真正把“AI平民化”落地的工具。它不像传统开发那样需要写几十行 LangChain 代码、配置向量库、调试提示词模板,而是把所有这些能力打包成一个个可拖拽的节点——就像小时候玩乐高,你不需要懂塑料怎么合成,只要知道哪块该拼在哪,就能搭出一座城堡。 它诞生于2023年,短短一年就收获了45.6k GitHub Stars,MIT协议开源,意味着你可以放心把它用在公司内部系统里,甚至嵌入到客户交付的产品中,完全不用担心授权问题。最打动人的不是它的技术多炫酷,而是它真的“不挑人”:产品经理能搭出知识库问答机器人,运营同学能配出自动抓取竞品文案的Agent,连刚学Python两周的实习生,也能在5分钟内跑通一个本地大模型的RAG流程。 它的核心逻辑很朴素:把LangChain里那些抽象概念——比如LLM调用、文档切分、向量检索、工具调用——变成画布上看得见、摸得着的方块。你拖一个“Ollama LLM”节点,再拖一个“Chroma Vector

OpenClaw配置Bot接入飞书机器人+Kimi2.5

OpenClaw配置Bot接入飞书机器人+Kimi2.5

上一篇文章写了Ubuntu_24.04下安装OpenClaw的过程,这篇文档记录一下接入飞书机器+Kimi2.5。 准备工作 飞书 创建飞书机器人 访问飞书开放平台:https://open.feishu.cn/app,点击创建应用: 填写应用名称和描述后就直接创建: 复制App ID 和 App Secret 创建成功后,在“凭证与基础信息”中找到 App ID 和 App Secret,把这2个信息复制记录下来,后面需要配置到openclaw中 配置权限 点击【权限管理】→【开通权限】 或使用【批量导入/导出权限】,选择导入,输入以下内容,如下图 点击【下一步,确认新增权限】即可开通所需要的权限。 配置事件与回调 说明:这一步的配置需要先讲AppId和AppSecret配置到openclaw成功之后再设置订阅方式,