You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I added a very descriptive title to this question.
I searched the LangChain documentation with the integrated search.
I used the GitHub search to find a similar question and didn't find it.
Commit to Help
I commit to help with one of those options 👆
Example Code
importloggingfromdatetimeimportdatetime, date, timefromtypingimportOptionalfromlangchain_openai.chat_modelsimportChatOpenAIfromlangchain_core.promptsimportChatPromptTemplatefrompydanticimportBaseModel, Field, field_validator, model_validator, ValidationErrorclassMatchingResult(BaseModel):
"""Response from the LLM agent. Args: id: identifier matching the input string confidence: confidence score of the match reason: reason for the match """id: Optional[int] =Field(description="identifier matching the input string")
confidence: int=Field(description="confidence score of the match")
reason: str=Field(description="reason for the match")
@field_validator('id')defcheck_location_id(cls, value):
possible_values= [1, 2, 3]
ifvalueisnotNoneandvaluenotinpossible_values:
raiseValueError(f'id {value} is not a valid value')
returnvalueclassMatchingInput(BaseModel):
content: str=Field(description="input string")
options_map: dict[int, str] =Field(description="map of options for matching")
classMatcher:
def__init__(self):
self.llm= (ChatOpenAI(
model="gpt-4o-mini",
temperature=0,
request_timeout=60
).with_structured_output(MatchingResult)
.with_retry(
retry_if_exception_type=(ValidationError,),
stop_after_attempt=3,
))
self.prompt=ChatPromptTemplate.from_messages(
[
("system", "You are a helpful assistant"),
("user",
"You should match the input string:\n""{content}\n to the provided options map.""**HERE SOME RULES FOR MATCHING**\n""Map of options to select from IDs to names:\n""{options_map}\n"),
]
)
self.chain= (
(self.prompt|self.llm)
.with_types(input_type=MatchingInput, output_type=MatchingResult)
)
asyncdefmatch_location(self, content: str, locations: dict[int, str]) -> (LocationMatchingResult, str):
try:
result=awaitself.chain.ainvoke(LocationMatchingInput(content=content, locations_map=locations))
returnresult, NoneexceptValidationErrorase:
logging.error(f"Error matching from string {content}. Error(s): {e.errors()} ({type(e)})")
# Here I want to change to prompt and include the error message and repeat the requestreturnNone, e.json()
exceptExceptionase:
logging.error(f"Error while matching from string {content} to string: Error {e} ({type(e)})")
returnNone, str(e)
Description
Often model fails to return correct result and post validation of the result object can spot this issue. My question is what is the most clear way to react on a validation exception by including errors in the prompt and request LLM again assuming last validation error.
System Info
System Information
OS: Darwin
OS Version: Darwin Kernel Version 24.2.0: Fri Dec 6 19:02:41 PST 2024; root:xnu-11215.61.5~2/RELEASE_ARM64_T6030
Python Version: 3.12.7 (main, Oct 16 2024, 12:05:52) [Clang 16.0.0 (clang-1600.0.26.3)]
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Checked other resources
Commit to Help
Example Code
Description
Often model fails to return correct result and post validation of the result object can spot this issue. My question is what is the most clear way to react on a validation exception by including errors in the prompt and request LLM again assuming last validation error.
System Info
System Information
Package Information
Other Dependencies
Beta Was this translation helpful? Give feedback.
All reactions