[PYTHON/LANGCHAIN] OutputFixingParser 클래스 : 파싱 오류 발생시 재시도하기
■ OutputFixingParser 클래스를 사용해 파싱 오류 발생시 재시도하는 방법을 보여준다. ※ 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 |
from dotenv import load_dotenv from langchain_core.pydantic_v1 import BaseModel from langchain_core.pydantic_v1 import Field from langchain_core.output_parsers import PydanticOutputParser from langchain_core.prompts import PromptTemplate from langchain_openai import OpenAI from langchain.output_parsers import OutputFixingParser from langchain_core.runnables import RunnableParallel from langchain_core.runnables import RunnableLambda load_dotenv() class Action(BaseModel): action : str = Field(description = "action to take" ) action_input : str = Field(description = "input to the action") pydanticOutputParser = PydanticOutputParser(pydantic_object = Action) promptTemplate = PromptTemplate( template = "Answer the user query.\n{format_instructions}\n{query}\n", input_variables = ["query"], partial_variables = {"format_instructions": pydanticOutputParser.get_format_instructions()} ) openAI = OpenAI(temperature = 0) completionRunnableSequence = promptTemplate | openAI outputFixingParser = OutputFixingParser.from_llm(parser = pydanticOutputParser, llm = openAI) executeRunnableSequence = RunnableParallel(completion = completionRunnableSequence, prompt_value = promptTemplate) \ | RunnableLambda(lambda x : outputFixingParser.parse_with_prompt(**x)) action = executeRunnableSequence.invoke({"query" : "who is leo di caprios gf?"}) print(action) """ action='search' action_input='leo di caprios gf' """ |
▶