微信扫码
与创始人交个朋友
我要投稿
LangChain 目前有两个语言的实现:Python
和 Node.js
。
项目代码结构:
由于 LangChain 更新频繁,如果遇到过时的用法或找不到包路径,可以在项目结构中查找最新版本的路径和用法。
这些核心组件相互协作,使得 LangChain 能够构建灵活、可扩展的语言应用程序。 |
以下是各个 LangChain 开源组件的简要介绍:
langchain-core
LangChain 核心库,包含基本的数据结构、工具和用于构建链式调用(Chains)的通用逻辑。它提供了 LLM 的抽象、向量数据库接口、内存管理、嵌入模型等组件,适用于构建复杂的语言模型应用。
langchain-community
由社区贡献的扩展库,提供对各种第三方服务和工具的集成支持,如 OpenAI、Qianfan、FAISS、Pinecone 等,使开发者能够轻松使用这些服务进行文档检索、向量存储和嵌入处理。
langchain
LangChain 框架的主包,整合了核心和社区扩展功能,提供丰富的工具链来构建与大语言模型(LLM)集成的应用。它支持从文本生成、问题回答到自定义工作流的各类应用场景。
langgraph
一个扩展 LangChain 的工具,专注于构建高度可控和自定义的智能代理。通过引入图结构,可以灵活管理不同任务和工作流之间的复杂依赖关系,使得创建可扩展、交互式的代理系统更加容易。
langserver
提供对 LangChain 服务化的支持,使得在云端运行和管理 LangChain 工作流成为可能。它为开发者提供 REST API,支持语言模型在服务环境中的自动扩展、部署和集成。
langsmith
开发者工具,专为调试和监控 LangChain 应用设计。它帮助开发者分析、记录和优化链条调用过程中的数据流,提供了对错误排查、性能监控和模型行为的详细洞察。
这些组件共同构建了一个强大的语言模型生态系统,方便开发者根据需求搭建自定义的 AI 应用。
conda create -n lang_chain python=3.10
conda activate lang_chain
pip install langchain
pip install langchain_community
pip install qianfan
import os
import platform
import subprocess
def load_env_from_bash_profile():
command = 'source ~/.bash_profile && env'
proc = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True, executable='/bin/bash')
for line in proc.stdout:
(key, _, value) = line.decode('utf-8').partition('=')
os.environ[key.strip()] = value.strip()
if platform.system() == 'Darwin':
# 解决os.getenv('QIANFAN_API_AK')返回为None问题
load_env_from_bash_profile()
ak = os.getenv('QIANFAN_API_AK')
sk = os.getenv('QIANFAN_API_SK')
print(f'ak: {ak}\nsk: {sk}')
os.environ['QIANFAN_AK'] = ak
os.environ['QIANFAN_SK'] = sk
注意:如果报错 raise errors.APIError(error_code, err_msg, req_id) qianfan.errors.APIError: api return error, req_id: code: 17, msg: Open api daily request limit reached 可能的原因: 未开通所调用服务的付费权限,或者账户已欠费,则需要充值即可!
LLMS 是 LangChain 与大语言模型交互的基础模块。你可以使用不同的 LLM 提供商(如 OpenAI、Hugging Face、Cohere 等)的模型。
import os
from langchain_community.llms import QianfanLLMEndpoint
from settings import QIANFAN_API_AK, QIANFAN_API_SK
os.environ['QIANFAN_AK'] = QIANFAN_API_AK
os.environ['QIANFAN_SK'] = QIANFAN_API_SK
def llms():
"""
预训练模型 LLMS
:return:
"""
# 实例化模型
llm = QianfanLLMEndpoint(model='ERNIE-4.0-8K-Preview')
res = llm.invoke("1+1=?")
print(res)
[INFO][2024-09-05 12:13:04.781] oauth.py:275 [t:8676167488]: trying to refresh token for ak `7PMgrX***`
[INFO][2024-09-05 12:13:05.573] oauth.py:302 [t:8676167488]: successfully refresh token
这个问题是基础的数学加法问题。
当我们进行简单的加法计算时,需要将两个数相加来求得结果。
对于 1 + 1 这个表达式:
1 加上 1 等于 2。
所以,1 + 1 = 2。
除了传统的 LLM
,LangChain 还支持聊天模型
。这些模型不仅可以处理单次输入,还能进行多轮对话,适合构建交互式聊天机器人。
from langchain_community.chat_models import QianfanChatEndpoint
from langchain_core.messages import HumanMessage
def chat_models():
"""
聊天模型(LLMS 的微调模型)
:return:
"""
# 实例化模型
chat = QianfanChatEndpoint(model='ERNIE-4.0-8K-Preview-0518')
messages = [HumanMessage(content='帮我介绍下诗仙李白的生平!')]
res = chat.invoke(messages)
print(res)
[INFO][2024-09-05 12:20:21.711] oauth.py:275 [t:8676167488]: trying to refresh token for ak `7PMgrX***`
[INFO][2024-09-05 12:20:22.046] oauth.py:302 [t:8676167488]: successfully refresh token
content='诗仙李白的生平介绍如下:\n\n一、基本信息与早年经历\n\n* 李白,字太白,号青莲居士,出生于蜀郡绵州昌隆县(今四川省绵阳市江油市青莲镇),也有说法认为他出生于西域碎叶。\n* 祖籍陇西成纪(今甘肃省秦安县),他是唐朝伟大的浪漫主义诗人,被誉为“诗仙”。\n* 李白是凉武昭王李暠的九世孙,为人爽朗大方,乐于交友,爱好饮酒作诗。\n\n二、文学成就与风格\n\n* 李白的乐府、歌行及绝句成就极高,歌行完全打破诗歌创作的一切固有格式,笔法多端,达到了任随性之而变幻莫测、摇曳多姿的神奇境界。其绝句自然明快,飘逸潇洒,能以简洁明快的语言表达出无尽的情思。\n* 在盛唐诗人中,李白是兼长五绝与七绝而且同臻极境的诗人。其诗作常被后人誉为“笔落惊风雨,诗成泣鬼神”。\n* 李白的诗雄奇飘逸,艺术成就极高,大多以描写山水和抒发内心的情感为主。他讴歌祖国山河与美丽的自然风光,风格雄奇奔放,俊逸清新,富有浪漫主义精神,达到了内容与艺术的完美统一。\n\n三、主要诗作与影响\n\n* 李白的代表作有《望庐山瀑布》《行路难》《蜀道难》《将进酒》《早发白帝城》等。\n* 李白的诗歌对后代产生了极为深远的影响,中唐的韩愈、孟郊、李贺,宋代的苏轼、陆游、辛弃疾,明清的高启、杨慎、龚自珍等著名诗人,都受到李白诗歌的启发和影响。\n\n四、其他方面\n\n* 除了文学,李白在书法和剑术方面也有很深的造诣。他的唯一传世书法真迹是《上阳台帖》,其剑术之高在唐朝位居第二,仅次于裴旻。\n* 李白从少年时起就常去寻找道观的道士谈论道经,后来与一位号为东岩子的隐者隐居于岷山,潜心学习。\n\n总的来说,李白是中国古代文学史上的巨星,他的诗作至今仍然被广泛传颂和研究。' additional_kwargs={'finish_reason': 'normal', 'request_id': 'as-0tws9yei08', 'object': 'chat.completion', 'search_info': []} response_metadata={'token_usage': {'prompt_tokens': 9, 'completion_tokens': 518, 'total_tokens': 527}, 'model_name': 'ERNIE-4.0-8K-Preview-0518', 'finish_reason': 'normal', 'id': 'as-0tws9yei08', 'object': 'chat.completion', 'created': 1725510058, 'result': '诗仙李白的生平介绍如下:\n\n一、基本信息与早年经历\n\n* 李白,字太白,号青莲居士,出生于蜀郡绵州昌隆县(今四川省绵阳市江油市青莲镇),也有说法认为他出生于西域碎叶。\n* 祖籍陇西成纪(今甘肃省秦安县),他是唐朝伟大的浪漫主义诗人,被誉为“诗仙”。\n* 李白是凉武昭王李暠的九世孙,为人爽朗大方,乐于交友,爱好饮酒作诗。\n\n二、文学成就与风格\n\n* 李白的乐府、歌行及绝句成就极高,歌行完全打破诗歌创作的一切固有格式,笔法多端,达到了任随性之而变幻莫测、摇曳多姿的神奇境界。其绝句自然明快,飘逸潇洒,能以简洁明快的语言表达出无尽的情思。\n* 在盛唐诗人中,李白是兼长五绝与七绝而且同臻极境的诗人。其诗作常被后人誉为“笔落惊风雨,诗成泣鬼神”。\n* 李白的诗雄奇飘逸,艺术成就极高,大多以描写山水和抒发内心的情感为主。他讴歌祖国山河与美丽的自然风光,风格雄奇奔放,俊逸清新,富有浪漫主义精神,达到了内容与艺术的完美统一。\n\n三、主要诗作与影响\n\n* 李白的代表作有《望庐山瀑布》《行路难》《蜀道难》《将进酒》《早发白帝城》等。\n* 李白的诗歌对后代产生了极为深远的影响,中唐的韩愈、孟郊、李贺,宋代的苏轼、陆游、辛弃疾,明清的高启、杨慎、龚自珍等著名诗人,都受到李白诗歌的启发和影响。\n\n四、其他方面\n\n* 除了文学,李白在书法和剑术方面也有很深的造诣。他的唯一传世书法真迹是《上阳台帖》,其剑术之高在唐朝位居第二,仅次于裴旻。\n* 李白从少年时起就常去寻找道观的道士谈论道经,后来与一位号为东岩子的隐者隐居于岷山,潜心学习。\n\n总的来说,李白是中国古代文学史上的巨星,他的诗作至今仍然被广泛传颂和研究。', 'is_truncated': False, 'need_clear_history': False, 'content_type': 'text', 'chat_id': '118000104525182086', 'is_safe': 1, 'usage': {'prompt_tokens': 9, 'completion_tokens': 518, 'total_tokens': 527}} id='run-5591cb8a-b6d8-4355-a45a-31ccd33f0d65-0' usage_metadata={'input_tokens': 9, 'output_tokens': 518, 'total_tokens': 527}
嵌入模型用于将文本转换为数值向量,适用于相似度计算、检索增强生成等任务。
from langchain_community.embeddings import QianfanEmbeddingsEndpoint
def embedding_models():
"""
向量模型
:return:
"""
# 实例化向量模型
embed = QianfanEmbeddingsEndpoint(model='Embedding-V1')
# 文本向量化
result_one = embed.embed_query(text='郑钦文退出瓜达拉哈拉赛')
print(f'result_one: {result_one}')
print(f'result_one size: {len(result_one)}')
print('***********************************')
result_batch = embed.embed_documents(
[
'台风摩羯来临前夜 海口现巨型闪电',
'外卖脱骨鸡被盗报警抓获1只小猫',
'女生离家3月暴瘦50斤父母满眼心疼'
]
)
print(f'result_batch: {result_batch}')
print(f'result_batch size: {len(result_batch)}')
print(f'result_batch 的向量纬度: {len(result_batch[0])}')
[INFO][2024-09-05 12:38:22.966] oauth.py:275 [t:8676167488]: trying to refresh token for ak `7PMgrX***`
[INFO][2024-09-05 12:38:23.272] oauth.py:302 [t:8676167488]: successfully refresh token
result_one: [-0.061145782470703125, 0.023861512541770935, -0.09996511787176132, 0.01227461639791727, 0.023608896881341934, -0.026105325669050217, -0.0329381562769413, -0.07904266566038132, 0.018362320959568024, 0.0194693636149168, 0.058596644550561905, -0.02881656028330326, 0.029189608991146088, 0.03286940976977348, -0.007360425777733326, 0.013249370269477367, 0.052207935601472855, 0.08645571023225784, 0.014012857340276241, -0.04514427110552788, -0.018283119425177574, -0.011612636037170887, -0.14034272730350494, -0.13559050858020782, -0.012343407608568668, 0.00891115702688694, -0.07282404601573944, -0.05236218497157097, -0.05027031898498535, -0.01724342070519924, -0.017314789816737175, 0.009451561607420444, -0.0180611964315176, -0.004783155396580696, -0.0009788970928639174, 0.05491626635193825, -0.01316547580063343, 0.0651666596531868, 0.010525609366595745, 0.07304934412240982, -0.0649542361497879, 0.013559294864535332, -0.06436653435230255, 0.006210618652403355, 0.021497363224625587, -0.05429530888795853, 0.028679298236966133, 0.0065652052871882915, -0.03086628019809723, 0.02248593606054783, -0.0650738850235939, 0.011616138741374016, -0.012589828111231327, -0.02901686541736126, -0.012489354237914085, -0.047519270330667496, 0.055055540055036545, -0.011426093056797981, 0.039180558174848557, -0.08844911307096481, 0.05337926745414734, -0.00424580741673708, 0.013129422441124916, -0.007047389633953571, 0.12116610258817673, -0.16935740411281586, -0.012754268012940884, 0.03491511195898056, -0.0014863788383081555, -0.02545318566262722, -0.056703485548496246, 0.02036210335791111, -0.000991546781733632, 0.08520791679620743, 0.08183754980564117, 0.052780844271183014, -0.014280140399932861, 0.010278027504682541, -0.010844850912690163, -0.013646398670971394, 0.013640185818076134, -0.03993672505021095, 0.08304055780172348, 0.0540512315928936, -0.01943030394613743, 0.09294834733009338, 0.10973719507455826, -0.028733542189002037, 0.007680305279791355, -0.02769552730023861, 0.03000280074775219, -0.03161681070923805, 0.10917199403047562, 0.0447961688041687, -0.044261734932661057, -0.01019282452762127, -0.002305119764059782, 0.02860315516591072, 0.016694357618689537, 0.011242195963859558, 0.07452917844057083, -0.011269165202975273, -0.02256951853632927, -0.009247341193258762, 0.014308636076748371, -0.04892760515213013, -0.029001299291849136, -0.05090386047959328, 0.0212065689265728, -0.0249153021723032, -0.07731495797634125, -0.03553071618080139, -0.01785898581147194, 0.009226812049746513, -0.03808782622218132, 0.01723061129450798, 0.0443652980029583, 0.001244660816155374, 0.06801939755678177, 0.03094625659286976, 0.11120275408029556, -0.026660801842808723, 0.05508621409535408, 0.044698458164930344, -0.06940074265003204, 0.08186043798923492, -0.019415805116295815, -0.14930427074432373, -0.09241731464862823, 0.049485236406326294, -0.03841128200292587, 0.006813810672610998, -0.02343638986349106, -0.01308618113398552, 0.09323510527610779, 0.007879714481532574, 0.021012363955378532, 0.013938465155661106, 0.08210518211126328, -0.045400653034448624, 0.008982597850263119, 0.042150434106588364, -0.043173227459192276, -0.001629128004424274, -0.08514057844877243, 0.12875023484230042, -0.025974417105317116, 0.07879181206226349, 0.027029704302549362, -0.041494280099868774, 0.019897863268852234, 0.04039379209280014, -0.14481674134731293, 0.0008188045467250049, -0.059386949986219406, -0.046806320548057556, 0.009762996807694435, -0.04030189290642738, -0.040240444242954254, 0.05765524134039879, 0.012650227174162865, 0.04292444884777069, -0.0481468141078949, 0.05842311307787895, 0.07199015468358994, -0.14018920063972473, 0.0658804178237915, 0.047015540301799774, 0.025959201157093048, 0.03927198424935341, -0.08175186812877655, 0.05332348868250847, 0.026608632877469063, -0.042681898921728134, -0.03419246897101402, 0.03856830671429634, 0.06865169107913971, 0.017560163512825966, 0.023226244375109673, 0.0034717232920229435, -0.0007976234192028642, -0.048287078738212585, -0.0030157258734107018, 0.09866933524608612, 0.11869645863771439, 0.04732683300971985, -0.02737743966281414, 0.004195947200059891, 0.04364129900932312, -0.028887631371617317, -0.04285794869065285, 0.10470705479383469, -0.0408879853785038, -0.051475800573825836, -0.05860661715269089, -0.05671560391783714, 0.0205586776137352, -0.1393624246120453, -0.02978053130209446, 0.06367355585098267, 0.04032975807785988, 0.06255712360143661, -0.05772097408771515, -0.0046120211482048035, 0.0257427841424942, 0.012898379936814308, 0.030742239207029343, -0.015375969000160694, 0.07528289407491684, 0.12036753445863724, -0.027847686782479286, -0.05023723095655441, -0.1057424396276474, 0.027614230290055275, -0.06196025013923645, -0.025320610031485558, 0.0805106833577156, -0.03505481779575348, 0.08508069813251495, -0.008360783569514751, -0.09345240890979767, -0.04518304392695427, 0.039716653525829315, -0.011702826246619225, -0.023840755224227905, -0.02058974653482437, 0.03274783864617348, -0.019623810425400734, 0.04653467237949371, -0.0657004714012146, -0.022832490503787994, -0.10877890884876251, -0.09515956044197083, -0.001181238447315991, -0.03510482981801033, -0.004416486714035273, -0.029066044837236404, 0.06301306933164597, 0.026675516739487648, -0.07738964259624481, -0.0303911492228508, -0.128959521651268, 0.04108332097530365, -0.024761633947491646, 0.10129551589488983, 0.015336169861257076, 0.12036990374326706, 0.02574784681200981, -0.10585396736860275, 0.0481877438724041, -0.044285569339990616, -0.015749359503388405, -0.004134128335863352, 0.04865095391869545, -0.019392646849155426, 0.18877345323562622, 0, 0, -0.12669737637043, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.12920789420604706, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0901355966925621, 0, 0, 0.1729459911584854, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.09247284382581711, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.12864942848682404, 0, 0, 0, 0, 0, 0, 0.2601807415485382, 0, 0, 0, 0, 0, 0, 0, -0.15358206629753113, 0, 0, 0, 0, 0, 0]
result_one 的向量纬度: 384
***********************************
result_batch: [[0.029245655983686447, 0.06558970361948013, -0.08048833906650543, -0.04351066052913666, 0.02007218264043331, -0.0338551364839077, -0.014646129682660103, 0.02951253391802311, 0.02428792603313923, -0.006925650406628847, 0.054223399609327316, 0.07157529145479202, -0.05407309904694557, -0.00656783627346158, -0.04187928885221481, 0.05663100630044937, -0.019664650782942772, 0.04049491882324219, -0.03689413517713547, 0.012582346796989441, 0.05698171257972717, -0.001331504201516509, -0.06157749891281128, -0.058927495032548904, 0.01881106197834015, 0.0541110523045063, 0.039338525384664536, 0.009223422966897488, 0.01767515204846859, 0.030851928517222404, -0.10759645700454712, -0.02536047250032425, -0.009306006133556366, -0.08082162588834763, 0.04433451220393181, 0.11520954966545105, 0.029206005856394768, 0.01787152700126171, 0.02189812809228897, -0.04850282892584801, -0.023129133507609367, 0.016689663752913475, -0.0002681038749869913, 0.040907807648181915, 0.040544554591178894, -0.0333779975771904, -0.04306155443191528, 0.06878796964883804, -0.09027636796236038, 0.04061465710401535, -0.04585908725857735, 0.024845091626048088, 0.014886226505041122, -0.015495391562581062, 0.08117575943470001, -0.06386829167604446, 0.009256614372134209, -0.04564271122217178, -0.03680528700351715, -0.02314605563879013, -0.021218957379460335, -0.06859201937913895, -0.08139422535896301, -0.03127914294600487, -0.00494861975312233, -0.003661378053948283, -0.11440610885620117, 0.018915267661213875, 0.03527176380157471, 0.048644840717315674, -0.054539330303668976, -0.05990486219525337, -0.014240620657801628, 0.0787230059504509, -0.035742081701755524, 0.04094111546874046, 0.009153478778898716, 0.10772714018821716, 0.012008252553641796, 0.07774685323238373, 0.017971264198422432, -0.02605035901069641, 0.048410091549158096, 0.04463448002934456, -0.04153643921017647, -0.06149369478225708, -0.08872105926275253, 0.006690768525004387, 0.021656394004821777, 0.08044034242630005, -0.01901768147945404, -0.0841435119509697, 0.08514054864645004, -0.022929800674319267, 0.02336837351322174, 0.04081713408231735, -0.01286094170063734, -0.047851257026195526, 0.01944408379495144, 0.03373757004737854, 0.04466848820447922, 0.04775812476873398, -0.05707050487399101, 0.02668684348464012, 0.09643639624118805, -0.030883319675922394, -0.06032019108533859, -0.11758832633495331, -0.037345100194215775, 0.0251945611089468, -0.12715937197208405, 0.029841352254152298, -0.009859773330390453, 0.0015538301086053252, -0.025385713204741478, 0.0631733313202858, -0.01037281472235918, -0.05557508394122124, 0.03795420005917549, 0.010615259408950806, 0.10160686075687408, 0.06069841608405113, -0.018754618242383003, 0.048313554376363754, -0.004078816156834364, 0.018519394099712372, -0.035663627088069916, 0.00952079612761736, -0.06633203476667404, 0.060060981661081314, -0.032537177205085754, -0.028637226670980453, -0.004893213044852018, 0.0131478700786829, 0.057202402502298355, -0.07348284870386124, 0.029566222801804543, 0.053562190383672714, -0.008756381459534168, 0.07506115734577179, 0.004884004592895508, 0.030525321140885353, 0.007399008143693209, 0.07655586302280426, -0.14239923655986786, 0.06669600307941437, 0.009519665502011776, 0.018047815188765526, -0.002290202770382166, -0.0968356505036354, 0.031001456081867218, 0.040406301617622375, -0.02560652792453766, -0.013441690243780613, 0.01740320399403572, -0.011018154211342335, -0.04025694355368614, -0.0226153451949358, -0.007163429167121649, 0.044650401920080185, 0.02955588325858116, 0.05497200787067413, -0.03216613456606865, -0.03508293256163597, 0.08922331780195236, -0.03712785616517067, -0.008959508500993252, 0.07411672919988632, 9.668959683040157e-05, -0.01436271145939827, -0.07724311947822571, 0.06441880762577057, 0.02160792052745819, -0.08840575069189072, 0.017562737688422203, 0.008395390585064888, 0.0911942645907402, -0.02592579834163189, -0.030209923163056374, 0.004067786503583193, -0.009466519579291344, 0.08604210615158081, 0.016485296189785004, 0.01332807820290327, 0.02672644704580307, 0.0514499694108963, -0.003258062293753028, -0.043918877840042114, -0.035855263471603394, -0.1322089582681656, -0.015607689507305622, 0.07230004668235779, 0.08630946278572083, 0.04604025185108185, 0.09176873415708542, -0.011060327291488647, -0.0006686719716526568, -0.10497952997684479, -0.028848066926002502, -0.0351075679063797, -0.05985501781105995, 0.007429723162204027, 0.024179216474294662, 0.060235727578401566, 0.00993523932993412, 0.07571476697921753, -0.02185540460050106, -0.06770613044500351, 0.08150644600391388, 0.01759752444922924, 0.09274228662252426, -0.02695164829492569, 0.02602461352944374, -0.020356474444270134, -0.06640097498893738, 0.022962570190429688, 0.0021915955003350973, -0.03332449868321419, 0.13491277396678925, -0.05148962512612343, -0.1163063645362854, -0.04960165172815323, 0.05661074072122574, 0.07622085511684418, 0.04454787075519562, -0.024224650114774704, 0.014553030021488667, 0.0865948349237442, 0.032096680253744125, -0.0213616956025362, -0.012874231673777103, -0.010764564387500286, 0.013416718691587448, -0.01673184707760811, -0.03829771280288696, -0.061452094465494156, 0.059714507311582565, -0.05892256274819374, -0.03333476185798645, 0.039367616176605225, -0.03749806433916092, -0.04354458302259445, 0.025858543813228607, -0.11736099421977997, 0.035872943699359894, -0.08908984065055847, 0.017148172482848167, -0.003803469007834792, -0.05368763953447342, -0.0288055669516325, 5.082497409603093e-06, 0.02275468409061432, -0.1258903443813324, -0.030655179172754288, -0.09579839557409286, 0.06303130090236664, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.2712875306606293, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.11520171910524368, -0.01875990442931652, -0.011763352900743484, 0, 0, 0, 0.2506221830844879, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.28317034244537354, 0, 0, 0, 0, 0, 0, 0, 0.042496632784605026, 0, -0.025690268725156784, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.2619134783744812, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.03187403827905655, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0.11237859725952148, 0.04861860349774361, -0.037613723427057266, 0.06039866432547569, 0.02703968994319439, -0.09964825212955475, -0.04751162603497505, 0.029802117496728897, 0.04628800228238106, 0.09309937059879303, 0.02748112939298153, 0.0451575368642807, 0.036439597606658936, 0.06767767667770386, -0.07525438815355301, -0.010093528777360916, -0.10585399717092514, 0.018630798906087875, 0.03943737968802452, -0.0270280409604311, 0.012311549857258797, -0.05268678441643715, -0.024965906515717506, -0.026482857763767242, -0.008151397109031677, -0.002142114331945777, 0.05123588815331459, 0.054243188351392746, 0.10970823466777802, 0.05001482367515564, -0.06357616931200027, 0.004486996680498123, 0.031074415892362595, -0.06864775717258453, -0.011213579215109348, 0.05860988423228264, 0.03955717012286186, 0.027893293648958206, 0.09015415608882904, 0.04233904182910919, 0.005969393532723188, -0.006584628019481897, 0.0614190399646759, -0.0013442139606922865, 0.000323534564813599, -0.006531541235744953, 0.05472048744559288, 0.011065613478422165, -0.026120953261852264, 0.050589241087436676, -0.05143167823553085, 0.020827747881412506, 0.06215802580118179, -0.04851164296269417, 0.07439663261175156, 0.010935680009424686, -0.09069500863552094, -0.028675861656665802, -0.026530716568231583, -0.026212824508547783, -0.11474236100912094, -0.047392308712005615, -0.07856929302215576, -0.0907345861196518, 0.14912065863609314, 0.00073950708610937, -0.027606695890426636, 0.08864963054656982, 0.04736553877592087, -0.09251098334789276, -0.08699624240398407, -0.008325239643454552, -0.11801367253065109, 0.050864558666944504, 0.02832675725221634, 0.07250573486089706, -0.034259241074323654, 0.05690464749932289, -0.009491224773228168, -0.05607457458972931, 0.0038351030088961124, -0.07914566993713379, 0.03849991783499718, 0.02390551194548607, -0.06643089652061462, -0.11977370083332062, -0.03094526007771492, 0.013981064781546593, -0.07074598968029022, 0.0635359063744545, -0.040199149399995804, 0.026612700894474983, 0.04410440847277641, -0.045757561922073364, 0.050664305686950684, -0.015857677906751633, 0.00010716287943068892, 0.028328122571110725, 0.03572307527065277, 0.02317582443356514, 0.0035218356642872095, 0.0196211040019989, 0.005977524910122156, -0.051303450018167496, 0.005626533646136522, -0.04476899281144142, -0.004751210100948811, -0.11106553673744202, -0.004640893079340458, -0.04027128219604492, -0.04585787281394005, -0.03198125585913658, -0.03077314794063568, 0.0024119659792631865, -0.0035174761433154345, 0.03931691125035286, -0.0065087140537798405, 0.03430952504277229, 0.01876833848655224, -0.11119016259908676, 0.08057165145874023, 0.06175975501537323, 0.03250160068273544, 0.03245925158262253, -0.01989855244755745, -0.09354832768440247, 0.021808335557579994, 0.014541300013661385, -0.07999175786972046, 0.15274274349212646, -0.07859646528959274, 0.004317606333643198, 0.04273398593068123, 0.014437444508075714, -0.041695717722177505, 0.045589931309223175, 0.06607167422771454, 0.028853079304099083, 0.008131169714033604, -0.016007645055651665, 0.0926845371723175, 0.046519018709659576, -0.005469870753586292, 0.04338991641998291, -0.0368768610060215, 0.014725831337273121, -0.05329522490501404, 0.02330865152180195, 0.03697780519723892, -0.10461176931858063, -0.020461052656173706, 0.005814286880195141, -0.037546705454587936, -0.011135002598166466, -0.06762347370386124, 0.00932338647544384, -0.02837125025689602, -0.06550286710262299, 0.003772991243749857, 0.01625196635723114, -0.03639095276594162, -0.024458665400743484, -0.12229292094707489, 0.002856349339708686, 0.05628524720668793, -0.04808959737420082, 0.08492103964090347, 0.07599000632762909, -0.009060713462531567, 0.053737033158540726, -0.08468573540449142, 0.08073724806308746, 0.03339379280805588, 0.00729743018746376, 0.032472383230924606, -0.09071934968233109, -0.0018345832359045744, 0.09156438708305359, 0.03870261088013649, -0.004789541941136122, -0.0628976970911026, 0.03591926023364067, -0.044937461614608765, 0.07730767875909805, 0.08173610270023346, 0.032510168850421906, -0.11720295995473862, -0.05504196509718895, 0.03305969387292862, -0.028758887201547623, -0.12425734847784042, 0.08242393285036087, 0.08350227773189545, -0.014061527326703072, -0.028810419142246246, 0.022767679765820503, -0.09259295463562012, -0.03899339586496353, -0.04694496840238571, 0.03125568851828575, -0.05229826271533966, -0.11582989990711212, 0.1138392761349678, 0.08648885786533356, 0.03539164364337921, 0.05339015647768974, 0.031002027913928032, 0.05737769603729248, 0.07410304248332977, 0.07362370938062668, 0.11435332149267197, -0.008148599416017532, 0.0035677594132721424, -0.017051350325345993, -0.009401632472872734, 0.026308294385671616, -0.03982293978333473, 0.032203759998083115, 0.016670774668455124, -0.022109678015112877, -0.03156069666147232, -0.09215695410966873, 0.03264531493186951, 0.056650955229997635, 0.09331784397363663, 0.03550655394792557, 0.06581344455480576, 0.04810374975204468, 0.0028254217468202114, -0.013030260801315308, -0.09041456878185272, -0.12304568290710449, 0.03897663205862045, 0.04356075078248978, -0.02478792704641819, -0.07482544332742691, -0.010633297264575958, -0.07047377526760101, 0.05851919576525688, 0.02582632377743721, 0.013422787189483643, -0.04334079474210739, -0.016268182545900345, -0.059182096272706985, -0.07789990305900574, -0.13341853022575378, 0.07426107674837112, -0.06384697556495667, -0.08607056736946106, -0.006968230474740267, 0.02644949220120907, 0.029979858547449112, -0.1192006915807724, 0.026721805334091187, 0.011549687944352627, 0.052630264312028885, 0, 0, 0, 0, -0.1685161143541336, -0.03600144386291504, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.17336703836917877, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.13832056522369385, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.17033667862415314, 0, -0.004350913688540459, 0, 0, 0, 0, -0.18632999062538147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.026328634470701218, 0, 0, 0, -0.10725714266300201, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.013199849054217339, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.09694530814886093, 0, 0], [0.15318617224693298, 0.012048143893480301, 0.060997374355793, -0.03248025104403496, -0.04544811695814133, -0.003551278728991747, -0.08415453135967255, 0.03300673887133598, -0.031614188104867935, -0.0007011581910774112, 0.04763876274228096, 0.062480293214321136, -0.013283523730933666, -0.010895144194364548, -0.005376795306801796, -0.00969754345715046, -0.04490916430950165, 0.012011950835585594, 0.050620440393686295, 0.0512918122112751, -0.021765172481536865, -0.06621148437261581, -0.02973072975873947, 0.08347739279270172, -0.03030291572213173, 0.0064037940464913845, 0.06907718628644943, 0.05948792025446892, 0.053828731179237366, 0.008490588515996933, 0.04344901815056801, 0.021381264552474022, -0.049303073436021805, -0.057470329105854034, -0.06423365324735641, -0.032659899443387985, -0.013746587559580803, 0.059947092086076736, -0.022454123944044113, 0.04526257887482643, -0.06618798524141312, 0.034933093935251236, 0.06773891299962997, 0.037840329110622406, 0.038373976945877075, -0.031180603429675102, 0.022928236052393913, -0.07407858967781067, -0.024439750239253044, 0.016328342258930206, -0.048422329127788544, 0.0048638139851391315, 0.0298647228628397, -0.018198072910308838, 0.05590683966875076, -0.039292726665735245, -0.07093042880296707, -0.10961951315402985, 0.021947067230939865, 0.04832296073436737, -0.06029282510280609, -0.05539312586188316, -0.011324615217745304, -0.08285854011774063, 0.06846195459365845, -0.10267366468906403, -0.12299831211566925, 0.12642668187618256, 0.0028263500425964594, -0.03375667706131935, -0.022074375301599503, 0.05123089253902435, -0.07047198712825775, -0.04187953472137451, 0.0522441565990448, -0.017144419252872467, -0.000842986861243844, 0.02954944036900997, 0.0008572863298468292, -0.013083661906421185, 0.06242526322603226, -0.05625432729721069, -0.03861014544963837, 0.04979068785905838, 0.004431063309311867, 0.015268760733306408, -0.07675893604755402, 0.014951162971556187, 0.08395378291606903, 0.03826533257961273, -0.00663897255435586, -0.09429685771465302, 0.16106882691383362, -0.03774842247366905, -0.011402402073144913, 0.060076214373111725, 0.03000781312584877, 0.03327798470854759, -0.074848972260952, 0.055900175124406815, -0.028340257704257965, 0.01600261777639389, -0.026284929364919662, 0.10443278402090073, -0.015089122578501701, 0.024275118485093117, 0.05678171291947365, -0.1455536037683487, -0.01030773762613535, -0.020783832296729088, -0.07515034824609756, 0.01248092483729124, -0.016148805618286133, -0.0901629775762558, -0.03132138028740883, 0.017282195389270782, -0.010015499778091908, -0.01810729317367077, 0.06034288555383682, 0.03239358961582184, 0.1271638125181198, 0.01998906210064888, -0.010832388885319233, 0.10338100045919418, -0.05655756592750549, 0.030042702332139015, -0.054028891026973724, -0.000721592630725354, -0.10889575630426407, 0.14088381826877594, -0.11793045699596405, -0.08320361375808716, 0.06184138357639313, 0.11253947764635086, 0.020291021093726158, 0.0339151956140995, -0.027203723788261414, -0.007681428920477629, 0.02081957459449768, -0.06661828607320786, -0.004550117999315262, 0.039198242127895355, -0.06726999580860138, 0.06550709158182144, -0.0214682724326849, 0.04889803007245064, -0.023701602593064308, 0.05686740577220917, 0.008659321814775467, -0.03722840175032616, 0.024795029312372208, -0.02182435803115368, -0.05772814154624939, -0.0257082749158144, -0.05164014920592308, -0.037859994918107986, -0.0475488044321537, 0.015510186553001404, 0.03600529208779335, -0.06733250617980957, -0.013050341978669167, -0.037977904081344604, 0.02330761030316353, 0.06888634711503983, 0.05834637209773064, -0.07464545220136642, -0.06880810111761093, 0.05223698914051056, 0.036288052797317505, 0.11195313930511475, 0.009352784603834152, 0.059806957840919495, 0.04852903634309769, -0.05616922304034233, 0.014839575625956059, 0.016761044040322304, 0.0657973662018776, 0.0773053839802742, 0.026292018592357635, -0.03248879313468933, 0.07984063774347305, 0.083088718354702, -0.10300363600254059, 0.040320802479982376, -0.004621823318302631, 0.07951744645833969, 0.013090482912957668, -0.012350297532975674, -0.05764230340719223, -0.10284608602523804, -0.07436130195856094, 0.04086039960384369, 0.1100720688700676, 0.09862113744020462, -0.008961549028754234, -0.036280516535043716, -0.02375003509223461, -0.11150955408811569, -0.10006433725357056, 0.121646448969841, -0.045186448842287064, -0.028742998838424683, 0.058264199644327164, 0.06966841220855713, 0.029326675459742546, -0.05213357135653496, 0.014226672239601612, -0.005923983175307512, 0.10288295149803162, 0.042083825916051865, 0.004057133570313454, -0.10490916669368744, -0.004548102617263794, -0.002317698672413826, -0.04332245886325836, 0.03135934844613075, 0.03436127305030823, 0.06820982694625854, 0.040867775678634644, -0.044050052762031555, -0.05942903459072113, 0.1211414784193039, 0.08352474123239517, 0.05390208959579468, 0.026312364265322685, 0.06423459947109222, -0.005292844958603382, 0.10671399533748627, 0.07304570078849792, -0.054201606661081314, -0.16842243075370789, -0.08752123266458511, -0.03281891345977783, 0.00809864979237318, -0.05722934752702713, -0.06422676891088486, 0.02131733112037182, -0.019025782123208046, -0.000134768764837645, -0.09761235862970352, -0.06996943801641464, -0.07638676464557648, -0.038919441401958466, 0.03488890081644058, 0.020871419459581375, -0.09783093631267548, -0.045008186250925064, 0.05757489055395126, -0.07009806483983994, 0.05562001094222069, -0.09444630891084671, 0.06616976112127304, -0.11463796347379684, 0.007514768745750189, -0.021906720474362373, 0.020799927413463593, 0, 0, 0, -0.14160025119781494, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.0370667539536953, 0, 0, 0, 0, 0, 0, 0.16696402430534363, 0, 0, 0, 0, -0.07133565843105316, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.034715812653303146, 0, 0, 0, 0, 0, 0, 0.07434548437595367, 0, -0.04296543449163437, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.03542681783437729, 0, -0.09617671370506287, 0, 0, 0, 0, 0, 0, 0, 0, 0.09324615448713303, 0, 0, 0, 0.13249388337135315, 0, 0, 0, 0, 0]]
result_batch size: 3
result_batch 的向量纬度: 384
在 LangChain 中,Prompts
组件用于为语言模型生成输入提示(prompts)。提示是引导语言模型生成期望结果的关键部分。LangChain 提供了多种构建和管理提示的方式,使得开发者可以创建高效、灵活的 prompts
。
Few-shot
提示是一种通过提供一些示例来引导语言模型更好地理解任务的方式。
from langchain_community.llms import QianfanLLMEndpoint
from langchain_core.prompts import PromptTemplate, FewShotPromptTemplate
def few_shot_prompt_demo():
"""
few_shot 用于在少量示例的基础上训练模型,使其能够更好地完成特定的任务
:return:
"""
# 示例
examples = [
{"Q": "狗属于哺乳动物", "A": "对"},
{"Q": "蝙蝠属于鸟类", "A": "错,蝙蝠属于哺乳类"},
{"Q": "蛇属于爬行动物", "A": "对"},
]
# 设置 example_prompt
example_template = """
问题:{Q}
答案:{A}\n
"""
# 实例化PromptTemplate
example_prompt = PromptTemplate(
input_variables=['Q', 'A'], # 包含模版中所有变量的名称
template=example_template # 表示提示模版的字符串,待填充的变量位置
)
# 实例化 few-shot-prompt
few_shot_prompt = FewShotPromptTemplate(
examples=examples, # 多个示例,一般是一个字典
example_prompt=example_prompt, # PromptTemplate 对象,为示例的格式
prefix='判断动物的种类?', # 示例之前要添加的文本
suffix='问题:{input}\\答案', # 示例之后要添加的文本
input_variables=["input"], # 所需要传递给模版的变量名
example_separator="\\n" # 用于分隔多个示例
)
# 实例化模型
llm = QianfanLLMEndpoint(model='Qianfan-Chinese-Llama-2-13B')
# 指定模型的输入
prompt_text = few_shot_prompt.format(input='小明属于鸟类')
print(f'prompt_text: {prompt_text}')
# 将 prompt_text 输入模型
result = llm.invoke(prompt_text)
print(f'result: {result}')
Zero-Shot
是指通过提供简短的提示,让语言模型在没有提供具体示例的情况下完成任务。这与 Few-Shot
不同,Few-Shot
通过提供若干示例来帮助模型理解任务,而 Zero-Shot
则完全依赖模型的预训练知识来推测用户意图并给出答案。
def zero_shot_prompt_demo():
"""
zero_shot 指在没有任何具体示例的情况下,让模型完成任务。
:return:
"""
# 定义模版
template = "明天我要去{city}旅游,请告诉我{city}有哪些旅游景点?"
prompt = PromptTemplate(
input_variables=['city'],
template=template
)
# 使用模版生成具体的prompt
city = '深圳'
prompt_text = prompt.format(city=city)
print(f'prompt_text: {prompt_text}')
# 实例化模型
llm = QianfanLLMEndpoint(model='Qianfan-Chinese-Llama-2-13B')
# 将 prompt 传入模型
result = llm.invoke(prompt_text)
print(f'result: {result}')
在 LangChain 中,Chains 是一种非常重要的概念,用于组合多个组件(如 PromptTemplate 和 LLM)来执行特定的任务。
def single_chain_old():
"""
单个chain
:return:
"""
# 定义模版
template = "(name) 开了一家人工智能公司,帮我取一个符合公司气质的名字!"
prompt = PromptTemplate(
input_variables=["name"], # 包含模版中所有变量名的名称
template=template # 表示提示模版字符串,待填充的变量位置
)
print(prompt)
# 实例化模型
llm = QianfanLLMEndpoint(model='Qianfan-Chinese-Llama-2-13B')
# 构造 Chain,将大模型与prompt组合在一起
# chain = LLMChain(llm=llm, prompt=prompt)
chain = LLMChain(llm=llm, prompt=prompt)
# 执行 chain
result = chain.invoke({"name": "李白"})
print(f"result: {result}")
LangChainDeprecationWarning: The class
LLMChain
was deprecated in LangChain 0.1.17 and will be removed in 1.0. Use RunnableSequence, e.g.,prompt | llm
instead.
def single_chain():
# 定义模版
template = "{name} 开了一家人工智能公司,帮我取一个符合公司气质的名字!"
prompt = PromptTemplate(
input_variables=["name"], # 包含模版中所有变量名的名称
template=template # 表示提示模版字符串,待填充的变量位置
)
print(prompt) # 输出提示模版
# 实例化模型
llm = QianfanLLMEndpoint(model='Qianfan-Chinese-Llama-2-13B')
# 构造 Chain,将大模型与prompt组合在一起
chain = prompt | llm # 使用 RunnableSequence
# 执行 chain
result = chain.invoke({"name": "李白"}) # 输入参数为 {"name": "李白"}
print(f"result: {result}") # 输出结果
# 调用函数
llm_chain()
def composite_chains()
# 定义模版
template = "{name} 开了一个早餐点,帮我取一个吸引人点名字!"
prompt = PromptTemplate(
input_variables=["name"], # 确保使用大括号{}包裹变量名
template=template # 表示提示模版字符串,待填充的变量位置
)
# 实例化模型
llm = QianfanLLMEndpoint(model='Qianfan-Chinese-Llama-2-13B')
# 构造 chain:第一条链
first_chain = prompt | llm # 使用 RunnableSequence
# 创建第二条链
# 定义模版
second_template = "{name} 开店赚钱了,然后又开了一个公司,帮我取一个吸引人的名字!"
second_prompt = PromptTemplate(
input_variables=["name"],
template=second_template # 表示提示模版字符串,待填充的变量位置
)
second_chain = second_prompt | llm # 使用 RunnableSequence
# 融合两条chain:使用 RunnableSequence
overall_chain = first_chain | second_chain # 将两条链组合在一起
# 执行 chain
result = overall_chain.invoke({"name": "王安石"}) # 输入参数为 {"name": "王安石"}
print(f"result: {result}") # 输出结果
# 调用函数
simple_sequential_chain()
在 LangChain 中,Agents 是一种高级抽象,用于构建复杂的任务流程。它们可以帮助你组合多个模型和工具,实现自动化的任务处理。下面是一些关于 LangChain 中 Agents 的基本概念和示例。
基本概念
Agents:代理是一种能够自动执行任务的组件,它可以调用多个工具和模型来完成复杂任务。
Tools:工具是代理可以调用的具体功能,例如查询数据库、执行网络请求等。
Chains:链是多个组件(如 PromptTemplate 和 LLM)的组合,用于执行特定任务。
RunnableSequence:用于组合多个组件,形成一个可执行的序列。
- 安装维基百科:pip install wikipedia
- 提高数值表达式的计算速度:pip install numexpr
def qianfan_agent():
# 实例化大模型
llm = QianfanLLMEndpoint(model='Qianfan-Chinese-Llama-2-13B')
# 工具加载函数:利用工具来增强模型
tools = load_tools(
tool_names=['llm-math', 'wikipedia'],
llm=llm
)
# 初始化智能体
agent = initialize_agent(
tools=tools,
llm=llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True,
handle_parsing_errors=True
)
prompt_template = "商朝是什么时候建立的?开国皇帝是谁?推理过程显示中文,结果显示中文"
prompt = PromptTemplate.from_template(prompt_template)
print(f'prompt: {prompt}')
res = agent.run(prompt)
print(f'res: {res}')
在LangChain框架中,Memory组件是用来管理智能体(Agent)与其环境之间的交互历史的。这个组件允许智能体记住之前的对话或操作,以便在未来的交互中做出更明智的决策。这在构建具有上下文感知能力的应用程序时特别有用,例如聊天机器人或虚拟助手。
LangChain Memory组件的关键特性:
def add_msg_to_history() -> None:
"""
添加消息到聊天历史记录
该函数实例化一个 `ChatMessageHistory` 对象,并向其中添加用户消息和 AI 消息。
最后打印出当前的消息历史记录,并将其转换为字典形式,再还原为消息对象。
:return: 无返回值
"""
# 实例化 ChatMessageHistory 对象
history = ChatMessageHistory()
# 向历史记录中添加用户消息
history.add_user_message("你在哪里?")
# 向历史记录中添加 AI 消息
history.add_ai_message("我在图书馆!")
# 打印当前的消息历史记录
print(history.messages)
# 将消息历史记录转换为字典形式
dicts = messages_to_dict(history.messages)
# 从字典形式还原消息历史记录
new_messages = messages_from_dict(dicts)
# 打印还原后的消息历史记录
print(new_messages)
# 用于存储会话历史的字典
store = {}
def get_session_history(session_id: str) -> InMemoryChatMessageHistory:
"""
获取会话历史
:param session_id: 会话 ID
:return: 会话历史实例
"""
if session_id not in store:
store[session_id] = InMemoryChatMessageHistory()
return store[session_id]
def store_qa_memory() -> None:
"""
存储问答对并进行连续对话
该函数使用 QianfanChatEndpoint 创建一个语言模型,并使用 RunnableWithMessageHistory 进行连续对话。
最后打印出每次对话的结果。
"""
# 初始化语言模型
llm = QianfanChatEndpoint(model="ERNIE-4.0-8K-Preview-0518")
# 创建 RunnableWithMessageHistory 对象,并传递语言模型和 get_session_history 函数
chain = RunnableWithMessageHistory(llm, get_session_history)
# 进行第一次预测
result1 = chain.invoke(
"老王有4个女朋友",
config={"configurable": {"session_id": "1"}}
) # session_id 确定线程
print(f"result1: {result1}")
# 进行第二次预测
result2 = chain.invoke(
"老李有6个女朋友",
config={"configurable": {"session_id": "1"}}
)
print(f"result2: {result2}")
# 进行第三次预测
result3 = chain.invoke(
"老王和老李一共有多少个女朋友?",
config={"configurable": {"session_id": "1"}}
)
print(f"result3: {result3}")
LangChain 的 Indexes 组件主要用于构建和管理索引,以便更高效地处理和检索数据。这些索引通常用于文档检索、知识库查询等场景。下面详细介绍 Indexes 组件的主要功能和使用方法。
安装文档加载器的包:
pip install -U langchain-unstructured
在 LangChain 中,VectorStore
是一种用于存储和检索向量化文档的组件,它可以用于执行相似性搜索。在使用自然语言处理任务时,将文本数据转换为向量(通常通过嵌入模型生成)后,我们可以使用 VectorStore
存储这些向量,并通过最近邻搜索或其他方式查询与查询向量最相似的文档。
VectorStore
组件在构建像语义搜索、推荐系统、聊天机器人等应用中非常有用。LangChain 提供了多种 VectorStore
的集成,支持不同的后端和存储方案,如 Pinecone、FAISS、Weaviate、Chroma 等。
VectorStore
的主要功能:
VectorStore
实现允许更新或删除存储的向量。常见的 VectorStore
实现
以下是 LangChain 支持的一些常见向量存储后端:
FAISS:
Pinecone:
Chroma:
Weaviate:
要安装 Chroma 向量数据库,可以通过 Python 的包管理器 pip
进行安装。以下是安装步骤:
安装额外包
通过 pip 安装:
使用以下命令安装 chromadb
包,这是 Chroma 向量数据库的官方 Python 客户端:
pip install chromadb
# 使用的是 CPU 环境,并且不需要 GPU 加速
pip install faiss-cpu
# 需要使用 GPU 加速
pip install faiss-gpu
安装带有额外依赖的版本(可选): 如果需要一些额外的功能或特性(如使用 SQLite 或其他后端),可以安装带有特定依赖的版本:
pip install chromadb[all]
验证安装:
安装完成后,可以通过导入 chromadb
来确认安装成功:
import chromadb
import faiss
如果没有错误提示,说明安装成功。
文档加载器
def load_text_file(file_path: str):
"""
文档加载器
:param file_path: 文件路径
:return: 文本列表
"""
loader = TextLoader(file_path=file_path, encoding="utf-8")
docs = loader.load()
print(f'docs:{docs}')
print(len(docs))
print(docs[0].page_content[:10])
def text_splitter_docs():
"""
使用 CharacterTextSplitter 将文档切分成较小的文本块。
1. 初始化 CharacterTextSplitter 对象,指定切分参数。
2. 将字符串列表转换为 Document 对象列表。
3. 使用 CharacterTextSplitter 对 Document 对象列表进行切分。
4. 输出切分后的结果。
:return: 无返回值
"""
# 初始化 CharacterTextSplitter 对象
text_splitter = CharacterTextSplitter(
separator='', # 分隔文本的字符或者字符串(这里设置为空字符串,表示不使用分隔符)
chunk_size=5, # 每个文本块的最大长度
chunk_overlap=2 # 文本块之间的重叠字符串长度
)
# 定义文档字符串列表
docs = [
"韩国未来环境可能不再利于白菜生长",
"央视发声明回应不播国足比赛",
"中国高铁1公里耗1万度电?官方回应",
]
# 将字符串列表转换为 Document 对象列表
documents = [Document(page_content=doc) for doc in docs]
# 使用 CharacterTextSplitter 对 Document 对象列表进行切分
results = text_splitter.split_documents(documents)
# results = text_splitter.split_text(','.join(docs))
# 输出切分后的结果
print(f'results:{results}')
向量数据库
def vector_stores(file_path: str):
"""
读取文件内容,切分文档,将切分后的文档向量化并保存到 Chroma 向量数据库中,
并执行一次相似性搜索。
:param file_path: 文件路径
:return: 无返回值
"""
# 读取文件内容
with open(file_path, encoding="utf-8") as f:
pku_text = f.read()
# 切分文档
text_splitter = CharacterTextSplitter(
separator='', # 分隔文本的字符或者字符串(这里设置为空字符串,表示不使用分隔符)
chunk_size=100, # 每个文本块的最大长度
chunk_overlap=5 # 文本块之间的重叠字符串长度
)
texts = text_splitter.split_text(pku_text)
print(f'texts:{len(texts)}') # 输出切分后的文本块数量
# 将切分后的文档向量化保存
embed = QianfanEmbeddingsEndpoint() # 初始化嵌入模型
# 创建 Chroma 向量存储,并将切分后的文本块向量化保存
doc_search = Chroma.from_texts(texts, embed)
# 查询
query = "中国高铁1公里耗1万度电?这种说法正确吗" # 设置查询文本
docs = doc_search.similarity_search(query) # 在向量存储中搜索与查询文本最相似的文档
print(f'docs:{docs}') # 输出搜索结果
print(len(docs)) # 输出搜索结果的数量
文档检索器
def retriever_faiss(file_path: str):
"""
读取文件内容,切分文档,将切分后的文档向量化并保存到 FAISS 向量数据库中,
并执行一次相似性搜索。
:param file_path: 文件路径
:return: 无返回值
"""
# 加载文件内容
loader = TextLoader(file_path=file_path, encoding="utf-8")
documents = loader.load()
# 使用 TokenTextSplitter 依据 tokens 数量切分文档
text_splitter = TokenTextSplitter(
chunk_size=50, # 减少每个文本块的 token 长度
chunk_overlap=10 # tokens 重叠部分
)
# 将文档切分为较小的文本块
docs = text_splitter.split_documents(documents)
# 初始化嵌入模型
embed = QianfanEmbeddingsEndpoint()
# 创建 FAISS 向量存储,并将切分后的文本块向量化保存
db = FAISS.from_documents(docs, embed)
# 创建检索器
retriever = db.as_retriever(search_kwargs={"k": 1})
# 执行相似性搜索
query = "中国高铁1公里耗1万度电?这种说法正确吗"
# results = retriever.get_relevant_documents(query)
results = retriever.invoke(query)
print(f'results:{results}')
53AI,企业落地应用大模型首选服务商
产品:大模型应用平台+智能体定制开发+落地咨询服务
承诺:先做场景POC验证,看到效果再签署服务协议。零风险落地应用大模型,已交付160+中大型企业
2024-11-25
AI Agents 现状报告,未来可期 or 强弩之末?
2024-11-13
只需8步,手把手教你用LangGraph创建AI智能体
2024-11-13
使用 LangChain 建立一个会话式的 RAG Agent 系统
2024-11-12
一文深度了解Agent智能体以及认知架构
2024-11-12
使用LangChain建立检索增强生成(RAG)系统
2024-11-11
Qwen-Agent 核心点说明
2024-11-11
吴恩达分享五个AI趋势,重点谈了多AI代理的美好前景
2024-11-11
使用 LangChain 构建一个 Agent(智能体/代理)
2024-08-18
2024-04-08
2024-06-03
2024-04-08
2024-04-17
2024-06-24
2024-04-12
2024-04-10
2024-07-01
2024-04-11
2024-11-25
2024-10-30
2024-10-11
2024-08-18
2024-08-16
2024-08-04
2024-07-29
2024-07-28