[PYTHON/LANGCHAIN] 도구 실행 오류시 재실행하기
■ 도구 실행 오류시 재실행하는 방법을 보여준다. ※ OPENAI_API_KEY 환경 변수 값은 .env 파일에 정의한다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
from dotenv import load_dotenv from langchain_core.tools import tool from langchain_core.messages import ToolCall from langchain_core.messages import AIMessage from langchain_core.runnables import RunnableConfig from langchain_core.runnables import Runnable from langchain_core.messages import ToolMessage from langchain_core.messages import HumanMessage from langchain_core.prompts import ChatPromptTemplate from langchain_openai import ChatOpenAI load_dotenv() @tool def complexTool(integerValue : int, floatValue : float, dictionaryValue : dict) -> int: """Do something complex with a complex tool.""" return integerValue * floatValue class CustomToolException(Exception): """Custom LangChain tool exception.""" def __init__(self, toolCall : ToolCall, exception : Exception) -> None: super().__init__() self.tool_call = toolCall self.exception = exception def complexToolWithCustomException(aiMessage : AIMessage, config : RunnableConfig) -> Runnable: try: return complexTool.invoke(aiMessage.tool_calls[0]["args"], config = config) except Exception as exception: raise CustomToolException(aiMessage.tool_calls[0], exception) def getInputDictionary(inputDictionary : dict) -> dict: exception = inputDictionary.pop("exception") messageList = [ AIMessage(content = "", tool_calls = [exception.tool_call]), ToolMessage(tool_call_id = exception.tool_call["id"], content = str(exception.exception)), HumanMessage(content = "The last tool call raised an exception. Try calling the tool again with corrected arguments. Do not repeat mistakes.") ] inputDictionary["last_output"] = messageList return inputDictionary # 우리는 프롬프트에 last_output MessagesPlaceholder를 추가한다. # 이 메시지는 전달되지 않으면 프롬프트에 전혀 영향을 미치지 않지만 필요한 경우 임의의 메시지 목록을 프롬프트에 삽입할 수 있는 옵션을 제공한다. # 이를 재시도 시 사용하여 오류 메시지를 삽입한다. chatPromptTemplate = ChatPromptTemplate.from_messages( [ ("human" , "{input}" ), ("placeholder", "{last_output}") ] ) chatOpenAI = ChatOpenAI(model="gpt-4o-mini") runnableBindable = chatOpenAI.bind_tools([complexTool]) runnableSequence = chatPromptTemplate | runnableBindable | complexToolWithCustomException selfCorrectingRunnableSequence = runnableSequence.with_fallbacks([getInputDictionary | runnableSequence], exception_key = "exception") responseValue = selfCorrectingRunnableSequence.invoke({"input" : "use complex tool. the args are 5, 2.1, empty dictionary. don't forget dictionaryValue"}) print(responseValue) |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
annotated-types==0.7.0 anyio==4.6.0 certifi==2024.8.30 charset-normalizer==3.3.2 colorama==0.4.6 distro==1.9.0 h11==0.14.0 httpcore==1.0.5 httpx==0.27.2 idna==3.10 jiter==0.5.0 jsonpatch==1.33 jsonpointer==3.0.0 langchain-core==0.3.5 langchain-openai==0.2.0 langsmith==0.1.128 openai==1.47.1 orjson==3.10.7 packaging==24.1 pydantic==2.9.2 pydantic_core==2.23.4 python-dotenv==1.0.1 PyYAML==6.0.2 regex==2024.9.11 requests==2.32.3 sniffio==1.3.1 tenacity==8.5.0 tiktoken==0.7.0 tqdm==4.66.5 typing_extensions==4.12.2 urllib3==2.2.3 |
※