携带错误信息的重试

携带错误信息的重试

老师,如下是我整理的错误信息是如何被携带上的思路整理,请帮忙看看有没有理解错误。

同时发现,这个代码无法打印exception变量信息,打印inputs信息也只能看到他是个CustomToolException()类实例,是我打印方式的问题吗?

另外这个程序多执行几遍,有的时候能成功,有的时候还是会报错,如下第一次失败,第二次成功

https://img1.sycdn.imooc.com/climg/88bfde6809108c4619540923.jpg

https://img1.sycdn.imooc.com/climg/f4615f6809108d0e17991132.jpg

https://img1.sycdn.imooc.com/climg/b9ffba6809108d2317350349.jpg



https://img1.sycdn.imooc.com/climg/3aeda46809108d3917870431.jpg

正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

1回答
泽辉呀 2025-05-08 10:38:44

正常能运行成功过一次就没有太大的问题,因为哪怕提供了错误信息,LLM有时候也不一定每次都能正确处理(LLM的输出具有随机性),可以完整粘贴下代码,我帮你看下代码的运行流程有没有问题。

  • 提问者 曲别针010 #1

    完整代码如下:

    # !/user/bin/env python
    # coding: utf-8
    """
    @Time       : 2025/4/29 14:40
    @Auther     : clip@gmail.com
    @File       : 3.携带错误信息的重试.py
    """
    from typing import Any
    
    import dotenv
    from langchain_core.messages import AIMessage, ToolMessage, HumanMessage, ToolCall
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_core.runnables import RunnableConfig
    from langchain_core.tools import tool
    from langchain_openai import ChatOpenAI
    
    
    dotenv.load_dotenv()
    
    
    class CustomToolException(Exception):
        '''自定义的工具错误异常'''
    
        def __init__(self, tool_call: ToolCall, exception: Exception) -> None:
            super().__init__()
            self.tool_call = tool_call
            self.exception = exception
    
    
    @tool
    def complex_tool(int_arg: int, float_arg: float, dict_arg: dict) -> float:
        '''使用复杂工具进行复杂计算操作'''
        return int_arg + float_arg
    
    def tool_custom_exception(msg: AIMessage, config: RunnableConfig) ->  Any:
        try:
            return complex_tool.invoke(msg.tool_calls[0]['args'], config)
        except Exception as e:
            raise CustomToolException(msg.tool_calls[0], e)
    
    def exception_to_messages(inputs: dict) -> dict:
        # 1.从inputs中分离出异常信息
        print(inputs)
        exception = inputs.pop('exception')
        print(exception)
        print(exception.tool_call)
        # 2.根据异常信息组装占位消息列表
        messages = [
            AIMessage(content='', tool_calls=[exception.tool_call]),
            ToolMessage(tool_call_id=exception.tool_call['id'], content=str(exception.exception)),
            HumanMessage(content='最后一次工具调用引发了异常,请分析异常信息,使用更正的参数再次调用该工具')
        ]
        inputs['last_output'] = messages
        return inputs
    
    
    # 1.创建prompt,并预留占位符,用于存储错误输出信息
    prompt = ChatPromptTemplate.from_messages([
        ('human', '{query}'),
        ('placeholder', '{last_output}')
    ])
    
    # 2.创建大语言模型并绑定该工具
    llm = ChatOpenAI(model='gpt-4o', temperature=0)
    llm_with_tool = llm.bind_tools(tools=[complex_tool])
    
    # 3.创建链并执行工具
    chain = prompt | llm_with_tool | tool_custom_exception
    self_correcting_chain = chain.with_fallbacks(
        [exception_to_messages | chain], exception_key='exception'
    )
    
    # 3.调用链
    print(self_correcting_chain.invoke({'query': '使用复杂工具,对应的参数为5和12.3'}))


    2025-05-08 11:22:11
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
AI Agent 全栈开发工程师
  • 参与学习       500    人
  • 解答问题       404    个

全流程打造你自己的(Coze/Dify)低代码智能体开发平台;2025年入行正当时,企业急需,人才稀缺,竞争小;无论入行还是转行,首选口碑好课,门槛低、成长高

了解课程
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师