LangChain笔记

很好的LLM知识博客:

https://lilianweng.github.io/posts/2023-06-23-agent/

LangChain的prompt hub:

https://smith.langchain.com/hub

一. Q&A

1. Q&A

os.environ["OPENAI_API_KEY"] = “OpenAI的KEY” # 把openai-key放到环境变量里;

from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4-0125-preview")

text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200) # 相邻chunk之间是200字符。(可以指定按照\n还是句号来分割)
splits = text_splitter.split_documents(docs) # 文档切块
vectorstore = Chroma.from_documents(documents=splits, embedding=OpenAIEmbeddings()) # 使用openai的embedding来对文档做向量化;使用Chroma向量库;

retriever = vectorstore.as_retriever()
prompt = hub.pull("rlm/rag-prompt")  # 从hub上拉取现成的prompt

rag_chain = (
{"context": retriever | format_docs, "question": RunnablePassthrough()}
| prompt
| llm
| StrOutputParser()
)  # 用竖线"|"来串联起各个组件;

2. Chat history

用LangChain封装好的组件,把2个子chain连接在一起。

Query改写的目的:

  Q1:"任务分解指的是什么?"

  A: "..."
  Q2: "它分为哪几步?"

有了Query改写,Q2可被改写为"任务分解分为哪几步?", 进而使用其作为query查询到有用的doc;

2.5 Serving

和FastAPI集成:

from fastapi import FastAPI
from langserve import add_routes


# 4. Create chain
chain = prompt_template | model | parser


# 4. App definition
app = FastAPI(
  title="LangChain Server",
  version="1.0",
  description="A simple API server using LangChain's Runnable interfaces",
)

# 5. Adding chain route

add_routes(
    app,
    chain,
    path="/chain",
)

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="localhost", port=8000)

3. Streaming

LangChain支持流式输出。

4.1 Wiki

langchain提供现成的Wikipedia数据库;已经向量化完毕封装在类里了。

from langchain_community.retrievers import WikipediaRetriever
wiki = WikipediaRetriever(top_k_results=6, doc_content_chars_max=2000)

4. Citation

让模型给出answer来自于context中docs的哪些片段。

可以在prompt里让模型给出answer的同时,也给出引用doc的id和文字片段。

例如:(注意"VERBATIM", 一字不差的)

You're a helpful AI assistant. Given a user question and some Wikipedia article snippets, \
answer the user question and provide citations. If none of the articles answer the question, just say you don't know.

Remember, you must return both an answer and citations. A citation consists of a VERBATIM quote that \
justifies the answer and the ID of the quote article. Return a citation for every quote across all articles \
that justify the answer. Use the following format for your final output:

<cited_answer>
    <answer></answer>
    <citations>
        <citation><source_id></source_id><quote></quote></citation>
        <citation><source_id></source_id><quote></quote></citation>
        ...
    </citations>
</cited_answer>

Here are the Wikipedia articles:{context}"""
prompt_3 = ChatPromptTemplate.from_messages(
    [("system", system), ("human", "{question}")]
)

所谓的tool,原理可能(我猜)也是tool封装了以上的改prompt方法。

也可以先调LLM给出answer,再调一次LLM给出citation。缺点是调用了2次LLM。

二. structured output

1. LangChain支持一种叫做Pydantic的语法,描述output:

from typing import Optional
from langchain_core.pydantic_v1 import BaseModel, Field

class Person(BaseModel):
    """Information about a person."""

    # ^ Doc-string for the entity Person.
    # This doc-string is sent to the LLM as the description of the schema Person,
    # and it can help to improve extraction results.

    # Note that:
    # 1. Each field is an `optional` -- this allows the model to decline to extract it!
    # 2. Each field has a `description` -- this description is used by the LLM.
    # Having a good description can help improve extraction results.
    name: Optional[str] = Field(default=None, description="The name of the person")
    hair_color: Optional[str] = Field(
        default=None, description="The color of the peron's hair if known"
    )
    height_in_meters: Optional[str] = Field(
        default=None, description="Height measured in meters"
    )

其中,加了"Optional"的,有则输出,无则不输出。

runnable = prompt | llm.with_structured_output(schema=Person)

text = "Alan Smith is 6 feet tall and has blond hair."
runnable.invoke({"text": text})

注意:该llm必须是支持该Pydantic和with_structured_output的模型才行。

输出结果:

Person(name='Alan Smith', hair_color='blond', height_in_meters='1.8288')

2. 提升效果的经验

  • Set the model temperature to 0. (只拿最优解)
  • Improve the prompt. The prompt should be precise and to the point.
  • Document the schema: Make sure the schema is documented to provide more information to the LLM.
  • Provide reference examples! Diverse examples can help, including examples where nothing should be extracted. (Few shot例子!)
  • If you have a lot of examples, use a retriever to retrieve the most relevant examples. (Few shot例子多些更好;正例和负例都要覆盖到,负例是指抽取不到所需字段的情况)
  • Benchmark with the best available LLM/Chat Model (e.g., gpt-4, claude-3, etc) -- check with the model provider which one is the latest and greatest! (有的模型连结构化格式都经常输出得不对。。。最好专门用结构化输出来做训练,再用)
  • If the schema is very large, try breaking it into multiple smaller schemas, run separate extractions and merge the results. (一次输出的格式,不能太复杂;否则要拆分)
  • Make sure that the schema allows the model to REJECT extracting information. If it doesn't, the model will be forced to make up information! (提示模型,可以拒绝输出,不懂不要乱说)
  • Add verification/correction steps (ask an LLM to correct or verify the results of the extraction). (用大模型或者代码或者人工来验证正确性,json load失败或不包含必要字段,则说明输出格式错误)

三. Chatbot

1. 有base model和chat model,一定要选用专门为chat做过训练的chat model!

2. 两处query改写

带知识库检索的,要注意query改写,将类似"那是什么”中的"那"这种代词给替换掉,再去检索。

带memory的,也要query改写。

3. 精简memory的目的:A. 大模型context长度有限;B.删去对话历史中的无关内容,让大模型更聚焦在有用信息上。

memory总结用的prompt:

Distill the above chat messages into a single summary message. Include as many specific details as you can

4. 知识检索,要记得加上“不懂别乱说”:

If the context doesn't contain any relevant information to the question, don't make something up and just say "I don't know"

四. Tools&Agent

1. Agent:大模型来决定,这一步用什么tool(or 直接输出最终结果)以及入参;每一步都把上一步的输出和tool的输出作为历史信息。

2. LangChain支持自定义tool:

from langchain_core.tools import tool


@tool
def multiply(first_int: int, second_int: int) -> int:
    """Multiply two integers together."""
    return first_int * second_int

注释很有用,告诉大模型该tool是干什么用的。

3. tool调用失败后的策略:

A. 给一个兜底LLM(GPT4等能力更强的模型),第一个模型失败后,调兜底模型再试。

B. 把tool入参和报错信息,放到prompt里,再调用一次(大模型很听话)。

"The last tool call raised an exception. Try calling the tool again with corrected arguments. Do not repeat mistakes."

五. query & analysis

1. 如果知识库是结构化/半结构化数据,可以把query输入大模型得到更合适的搜索query,例如{"query":"XXX", "publish_year":"2024"}

2. 一个复杂query,输入LLM,得到若干简单query;使用简单query查询知识库得到结果,合在一起,回答复杂query

帮助LLM理解如何去分解得到简单query? 答:给几个few-shot-examples;

3. "需要搜索则输出query,不需要搜索则直接输出回答"

4. 多个知识库:根据生成的query里的“库”字段,只查询相应的库;没必要所有库都查询;

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/647665.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【Linux】Linux的基本指令_2

文章目录 二、基本指令8. man9. nano 和 cat10. cp11. mv12. echo 和 > 和 >> 和 <13. more 和 less14. head 和 tail 和 | 未完待续 二、基本指令 8. man Linux的命令有很多参数&#xff0c;我们不可能全记住&#xff0c;我们可以通过查看联机手册获取帮助。访问…

深入编程逻辑:从分支到循环的奥秘

新书上架~&#x1f447;全国包邮奥~ python实用小工具开发教程http://pythontoolsteach.com/3 欢迎关注我&#x1f446;&#xff0c;收藏下次不迷路┗|&#xff40;O′|┛ 嗷~~ 目录 一、编程逻辑的基石&#xff1a;分支与循环 分支逻辑详解 代码案例&#xff1a;判断整数是…

Unity 资源 之 限时免费的Lowpoly农场动物,等你来领!

Unity资源 之 Lowpoly farm animals 农村动物 前言资源包内容领取兑换码 前言 Unity 资源商店为大家带来了一份特别的惊喜——限时免费的农场动物资源&#xff01;这是一个充满趣味和实用性的资源包。 资源包内容 在这个资源包中&#xff0c;你可以找到丰富多样的低地养殖动物…

685. 冗余连接 II

685. 冗余连接 II 问题描述 在本问题中&#xff0c;有根树指满足以下条件的 有向 图。该树只有一个根节点&#xff0c;所有其他节点都是该根节点的后继。该树除了根节点之外的每一个节点都有且只有一个父节点&#xff0c;而根节点没有父节点。 输入一个有向图&#xff0c;该…

mac 安装Node.js

文章目录 前言一、Node是什么&#xff1f;二、下载三、安装四、验证总结 前言 Node.js是一个开源、跨平台的JavaScript运行时环境&#xff0c;它允许开发者在服务器端运行JavaScript代码。Node.js是基于Chrome V8 JavaScript引擎构建的&#xff0c;它的设计目标是提供一种高效…

这样的直男程序员,活该你单身一万年!

#分享下相亲时遇到过哪些奇葩现象# 这样的直男程序员&#xff0c;活该你单身一万年&#xff01; 在丛丛脱单小程序上相亲&#xff0c;遇到一个程序员妹纸&#xff0c;于是有了如下的真实故事&#xff1a; 妹子说她是程序员来着&#xff0c;想着我也是程序员&#xff0c;就想交…

基于xilinx FPGA的 FFT IP使用例程说明文档(可动态配置FFT点数,可计算信号频率与幅度)

目录 1 概述2 IP examples功能3 IP 使用例程3.1 IP设置3.2 fft_demo端口3.3 例程框图3.4 仿真结果3.5 仿真验证得出的结论4 注意事项5例程位置 1 概述 本文用于讲解xilinx IP 的FFT ip examples的功能说明&#xff0c;方便使用者快速上手。 参考文档&#xff1a;《PG109》 2 …

MySQL大表删除方案

1.问题 在生产环境中&#xff0c;执行大表删除操作时&#xff0c;很容易因为占用了大量io资源导致其他事务被阻塞&#xff0c;最终事务不断堆积导致MySQL挂掉。 2.drop命令 drop命令&#xff0c;MySQL主要干了两件事&#xff1a; 清除buffer pool缓冲&#xff08;内存&…

Java控制台实现斗地主的洗牌和发牌功能

一、题目要求 有3个玩家&#xff1a;A&#xff0c;B&#xff0c;C。底牌有三张牌&#xff0c;每个人共17张牌&#xff0c;共&#xff08;17*3354&#xff09;张牌&#xff0c;实现洗牌与发牌&#xff0c;只在控制没有实现UI可视化。 二、思路 1、用List集合存储所有的扑克牌。…

表查询基础【mysql】【表内容 增,删,改,查询】

博客主页&#xff1a;花果山~程序猿-CSDN博客 文章分栏&#xff1a;Linux_花果山~程序猿的博客-CSDN博客MySQL之旅_花果山~程序猿的博客-CSDN博客Linux_花果山~程序猿的博客-CSDN博客 关注我一起学习&#xff0c;一起进步&#xff0c;一起探索编程的无限可能吧&#xff01;让我…

MTK下载AP

只升级选Firemare Upgrade &#xff0c;点下载后&#xff0c;关机下插入USB

多线程案例(线程池)

White graces&#xff1a;个人主页 &#x1f649;专栏推荐:Java入门知识&#x1f649; &#x1f649; 内容推荐:<计算坤是如何工作的>&#x1f649; &#x1f439;今日诗词:百年兴衰皆由人, 不由天&#x1f439; ⛳️点赞 ☀️收藏⭐️关注&#x1f4ac;卑微小博主&…

Android11热点启动和关闭

Android官方关于Wi-Fi Hotspot (Soft AP) 的文章&#xff1a;https://source.android.com/docs/core/connect/wifi-softap?hlzh-cn 在 Android 11 的WifiManager类中有一套系统 API 可以控制热点的开和关&#xff0c;代码如下&#xff1a; 开启热点&#xff1a; // SoftApC…

计算机设计大赛

目录 1.1需求分析 2.1概要设计 3.1软件界面设计&#xff1a; 4.1代码开源 1.1需求分析 1.1 产品开发本说明&#xff1a; 在如今每人都会扔出许多垃圾&#xff0c;在一些地方大部分垃圾能得到卫生填埋、焚烧等无害化处理&#xff0c;而更多的垃圾则是简单的掩埋&#xff…

3D牙科网格分割使用基于语义的特征学习与图变换器

文章目录 3D Dental Mesh Segmentation Using Semantics-Based Feature Learning with Graph-Transformer摘要方法实验结果 3D Dental Mesh Segmentation Using Semantics-Based Feature Learning with Graph-Transformer 摘要 本文提出了一种新颖的基于语义的牙科网格分割方…

计算机毕业设计 | SSM汽车租赁系统(附源码)

1&#xff0c; 概述 1.1 课题背景 随着社会的快速发展&#xff0c;计算机的影响是全面且深入的。用户生活水平的不断提高&#xff0c;日常生活中用户对汽车租赁系统方面的要求也在不断提高&#xff0c;需要汽车租赁系统查询的人数更是不断增加&#xff0c;使得汽车租赁系统的…

rockylinux 利用nexus 搭建私服yum仓库

简单说下为啥弄这个私服&#xff0c;因为自己要学习一些东西&#xff0c;比如新版的k8s等&#xff0c;其中会涉及到一些yum的安装&#xff0c;为了防止因网络问题导致yum安装失败&#xff0c;和重复下载&#xff0c;所以弄个私服&#xff0c;当然也有为了意外保障的想法&#x…

树形DP-AcWing 285. 没有上司的舞会-XMUOJ提瓦特庆典策划

题目 思路 话不多说&#xff0c;直接上代码 代码 /* AcWing 285. 没有上司的舞会-XMUOJ提瓦特庆典策划 --JinlongW-2024/05/26 */ #include <bits/stdc.h> using namespace std; const int N7000; int st[N];//标记是否有父亲结点 int happy[N]; int dp[N][2]; vect…

【AHK V2】设计模式之命令模式

目录 情景剧场什么是命令模式优缺点优点缺点 使用命令模式的步骤命令模式代码示例合理使用AI工具自动生成代码 情景剧场 我们来设想一个场景&#xff1a; 你进入一家餐馆&#xff0c;餐馆只有老板一个人&#xff08;老板即厨师&#xff09;。 “老板&#xff0c;一份小炒肉&am…

HCIP的学习(22)

BGP优化 [r1-bgp]peer 12.0.0.2 default-route-advertise ---BGP下放缺省路由&#xff0c;无论本地的路由表中是否存在缺省路由&#xff0c;都会向对等体下发一条下一跳为本地的缺省路由&#xff0c;从而减少网络中路由数量&#xff0c;节省对等体的设备资源 BGP协议优先级 缺…