【Langchain大语言模型开发教程】评估

🔗 LangChain for LLM Application Development - DeepLearning.AI

学习目标

1、Example generation

2、Manual evaluation and debug

3、LLM-assisted evaluation

4、LangChain evaluation platform

1、引包、加载环境变量;

python 复制代码
import os

from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file

from langchain.chains import RetrievalQA
from langchain_openai import ChatOpenAI
from langchain.document_loaders import CSVLoader
from langchain.indexes import VectorstoreIndexCreator
from langchain.vectorstores import DocArrayInMemorySearch

2、加载数据;

python 复制代码
file = 'OutdoorClothingCatalog_1000.csv'
loader = CSVLoader(file_path=file, encoding='utf-8')
data = loader.load()

3、创建向量数据库(内存警告⚠);

python 复制代码
model_name = "bge-large-en-v1.5"
embeddings = HuggingFaceEmbeddings(
    model_name=model_name,
)

db = DocArrayInMemorySearch.from_documents(data, embeddings)
retriever = db.as_retriever()

4、初始化一个LLM并创建一个RetrievalQ链;

python 复制代码
llm = ChatOpenAI(api_key=os.environ.get('ZHIPUAI_API_KEY'),
                         base_url=os.environ.get('ZHIPUAI_API_URL'),
                         model="glm-4",
                         temperature=0.98)

qa = RetrievalQA.from_chain_type(
    llm=llm, 
    chain_type="stuff", 
    retriever=retriever,
    verbose=True,
    chain_type_kwargs = {
        "document_separator": "<<<<>>>>>"
    }
)

Example generation

python 复制代码
from langchain.evaluation.qa import QAGenerateChain

example_gen_chain = QAGenerateChain.from_llm(llm)

new_examples = example_gen_chain.apply_and_parse(
    [{"doc": t} for t in data[:5]]
)

这里我们打印一下这个生成的example,发现是一个列表长下面这个样子;

python 复制代码
[{'qa_pairs': {'query': "What is the unique feature of the innersole in the Women's Campside Oxfords?", 'answer': 'The innersole has a vintage hunt, fish, and camping motif.'}}, {'qa_pairs': {'query': 'What is the name of the dog mat that is ruggedly constructed from recycled plastic materials, helping to keep dirt and water off the floors and plastic out of landfills?', 'answer': 'The name of the dog mat is Recycled Waterhog Dog Mat, Chevron Weave.'}}, {'qa_pairs': {'query': 'What is the name of the product described in the document that is suitable for Infant and Toddler Girls?', 'answer': "The product is called 'Infant and Toddler Girls' Coastal Chill Swimsuit, Two-Piece'."}}, {'qa_pairs': {'query': 'What is the primary material used in the construction of the Refresh Swimwear V-Neck Tankini, and what percentage of it is recycled?', 'answer': 'The primary material is nylon, with 82% of it being recycled nylon.'}}, {'qa_pairs': {'query': 'What is the material used for the EcoFlex 3L Storm Pants, according to the document?', 'answer': 'The EcoFlex 3L Storm Pants are made of 100% nylon, exclusive of trim.'}}]

所以这里我们需要进行一步提取;

python 复制代码
for example in new_examples:
    examples.append(example["qa_pairs"])

print(examples)

qa.invoke(examples[0]["query"])

Manual Evaluation

python 复制代码
import langchain
langchain.debug = True #开始debug模式,查看chain中的详细步骤

我们再次执行来查看chain中的细节;

LLM-assisted evaluation

那我们是不是可以使用语言模型来评估呢;

python 复制代码
langchain.debug = False #关闭debug模式

from langchain.evaluation.qa import QAEvalChain

让大语言模型来为我们每个example来生成答案;

python 复制代码
predictions = qa.apply(examples)

我们初始化一个评估链;

python 复制代码
eval_chain = QAEvalChain.from_llm(llm)

让大语言模型对实际答案和预测答案进行对比并给出一个评分;

python 复制代码
graded_outputs = eval_chain.evaluate(examples, predictions)

最后,我们可以打印一下看看结果;

python 复制代码
for i, eg in enumerate(examples):
    print(f"Example {i}:")
    print("Question: " + predictions[i]['query'])
    print("Real Answer: " + predictions[i]['answer'])
    print("Predicted Answer: " + predictions[i]['result'])
    print("Predicted Grade: " + graded_outputs[i]['results'])
    print()
相关推荐
梦想不只是梦与想7 分钟前
PyTorch、CPU、GPU、CUDA
人工智能·pytorch·python·深度学习·机器学习·cuda
数字融合9 分钟前
透明化视频孪生危化安全管控解决方案
人工智能·python·安全
冬奇Lab13 分钟前
一天一个开源项目(第253篇):dsh-superagent —— DeepSeek 开源的“主动式”编程智能体原型,核心原则是少占人的注意力
人工智能·开源·资讯
我真会写代码13 分钟前
LangChain 从0入门:模型、消息、Prompt、Tools、记忆、Agent与LangSmith实战
langchain·prompt
罗西的思考16 分钟前
【轻量化复刻大模型 / KIMI K3】KDA 模块交互式演示
人工智能·算法·机器学习
拓恒技术31 分钟前
从“可见光漏检”到“热异常锁定”:无人机河道排污口识别与溯源的技术链路
人工智能·视觉检测·无人机
2601_9689007743 分钟前
按量计费接口实战:从接入、预算到对账的完整链路
人工智能
七牛云行业应用1 小时前
MIT “权重空间编程”:GPT-6 Astra 修改 0.016% 的 Qwen 权重,MATH-500 从 7.9% 升至 48.1%
人工智能·gpt·ai
故七月1 小时前
AI 答案里的竞品共现:怎么看出赛道格局
大数据·人工智能
正在走向自律1 小时前
【3/5】人工智能训练师 三级/高级工 考证学习方向:从“独立执行”到“设计、归因与全链条负责”
人工智能·学习·人工智能训练师·注方案设计·数据质控负责人·模型评测与调优辅助·ai训练项目交付