Xử lí lỗi (tiếp tục)
Chuyển đổi các ngoại lệ thành text làm dòng làm việc của bạn có thể tiếp tục thực thi trong khi cung
cấp cac LLMs cuối dòng với bối cảnh có giá trị về cái gì bị sai và các đường khôi phục tiềm năng.
Sau đây là một ví dụ đơn giản về làm cách nào bạn có thể ghi lại ngoại lệ nhưng vẫn tiếp tục thực thi
dòng làm việc của bạn bằng cách gắn với hành vi mặc định:
import logging
logger = logging.getLogger(__name__)
llms = {“fake”: fake_llm,
“Google”: llm}
def analyze_job_description(state, config: RunnableConfig):try:
llm = config[“configurable”].get(“model_provider”, “Google”)
llm = llms[model_provider]
analyze_chain = llm | parser
prompt = prompt_template_enum.format(job_description=job_description)
result = analyze_chain.invoke(prompt)
return {“is_suitable”: result}except Exception as e:
logger.error(f”Exception {e} occurred while executing analyze_job_
description”)
return {“is_suitable”: False}
Để test xử lí lỗi của chúng ta, chúng ta cần mô phỏng các thất bại LLM. LangChain có một vài classes
FakeChatModel cái giúp bạn test xích của bạn:
+ GenericFakeChatModel trả về các thông điệp dựa trên một lặp được cung cấp.
+ FakeChatModel luôn trả về một “fake_response” string.
+ FakeListChatModel lấy một list các thông điệp và trả về chúng từng cái một trên mỗi khởi động.
Hãy tạo một LLM giả cái thất bại thời gian mỗi giây:
from langchain_core.language_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
class MessagesIterator:def __init__(self):
self._count = 0
def __iter__(self):
return self
def __next__(self):
self._count += 1
if self._count % 2 == 1:raise ValueError(“Something went wrong”)
return AIMessage(content=”False”)
fake_llm = GenericFakeChatModel(messages=MessagesIterator())
