Why is the on_retry
method of my callback not called?
#24518
Replies: 3 comments 6 replies
-
@PepijnBoers Hello! I'm here to assist you with any bugs, questions, or contributions you have. Let's take a look at the issue you've encountered. The
Here is a revised version of your code with some adjustments to ensure the from langchain_core.callbacks import BaseCallbackHandler
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain_core.runnables.retry import RunnableRetry
from langchain_core.llms import LLM
from tenacity import retry_if_exception_type, stop_after_attempt
class MyCustomHandler(BaseCallbackHandler):
def on_llm_new_token(self, token: str, **kwargs) -> None:
print(f"My custom handler, token: {token}")
def on_retry(self, *args, **kwargs):
print("on_retry")
def on_llm_start(self, *args, **kwargs):
print("on_llm_start")
class SimulatedRetryableError(Exception):
pass
class FailingModel(LLM):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def _call(self, *args, **kwargs):
raise SimulatedRetryableError("Simulated failure")
return super().invoke(*args, **kwargs)
def _llm_type(self, *args, **kwargs):
return "custom"
prompt = ChatPromptTemplate.from_messages(["Tell me a joke about {animal}"])
model = FailingModel(n=1, callbacks=[MyCustomHandler()])
chain = prompt | model
runnable_with_retries = RunnableRetry(
bound=chain,
config={"callbacks": [MyCustomHandler()]},
max_attempt_number=5,
retry_exception_types=(SimulatedRetryableError,), # Ensure the correct exception type
wait_exponential_jitter=True
)
response = runnable_with_retries.invoke({"animal": "bears"}) Make sure that the |
Beta Was this translation helpful? Give feedback.
-
Could you check what happens in this case: response = runnable_with_retries.invoke({"animal": "bears"}, {'callbacks': [MyCustomHandler()]}) |
Beta Was this translation helpful? Give feedback.
-
@eyurtsev Any updates on this? If not, I would be helped tremendously by seeing a working example of the |
Beta Was this translation helpful? Give feedback.
-
Checked other resources
Commit to Help
Example Code
Description
I'm expecting to see an
on_retry
statement, but I do not manage to get it. When is theon_retry
method triggered?System Info
langchain==0.2.10
langchain-core==0.2.22
langchain-openai==0.1.17
langchain-text-splitters==0.2.2
MacOS 14.2.1
Python 3.9.6
Beta Was this translation helpful? Give feedback.
All reactions