mirror of
https://github.com/langchain-ai/langchain.git
synced 2026-10-09 11:25:21 +03:00
Fix spelling errors in the text: 'Therefore' and 'Retrying I want to stress that your feedback is invaluable to us and is genuinely cherished. With gratitude, @baskaryan @hwchase17
13 KiB
13 KiB
In [18]:
from langchain.chat_models import ChatOpenAI, ChatAnthropicIn [21]:
from unittest.mock import patch
from openai.error import RateLimitErrorIn [24]:
# Note that we set max_retries = 0 to avoid retrying on RateLimits, etc
openai_llm = ChatOpenAI(max_retries=0)
anthropic_llm = ChatAnthropic()
llm = openai_llm.with_fallbacks([anthropic_llm])In [27]:
# Let's use just the OpenAI LLm first, to show that we run into an error
with patch('openai.ChatCompletion.create', side_effect=RateLimitError()):
try:
print(openai_llm.invoke("Why did the chicken cross the road?"))
except:
print("Hit error")Hit error
In [28]:
# Now let's try with fallbacks to Anthropic
with patch('openai.ChatCompletion.create', side_effect=RateLimitError()):
try:
print(llm.invoke("Why did the the chicken cross the road?"))
except:
print("Hit error")content=' I don\'t actually know why the chicken crossed the road, but here are some possible humorous answers:\n\n- To get to the other side!\n\n- It was too chicken to just stand there. \n\n- It wanted a change of scenery.\n\n- It wanted to show the possum it could be done.\n\n- It was on its way to a poultry farmers\' convention.\n\nThe joke plays on the double meaning of "the other side" - literally crossing the road to the other side, or the "other side" meaning the afterlife. So it\'s an anti-joke, with a silly or unexpected pun as the answer.' additional_kwargs={} example=False
In [29]:
from langchain.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages(
[
("system", "You're a nice assistant who always includes a compliment in your response"),
("human", "Why did the {animal} cross the road"),
]
)
chain = prompt | llm
with patch('openai.ChatCompletion.create', side_effect=RateLimitError()):
try:
print(chain.invoke({"animal": "kangaroo"}))
except:
print("Hit error")content=" I don't actually know why the kangaroo crossed the road, but I can take a guess! Here are some possible reasons:\n\n- To get to the other side (the classic joke answer!)\n\n- It was trying to find some food or water \n\n- It was trying to find a mate during mating season\n\n- It was fleeing from a predator or perceived threat\n\n- It was disoriented and crossed accidentally \n\n- It was following a herd of other kangaroos who were crossing\n\n- It wanted a change of scenery or environment \n\n- It was trying to reach a new habitat or territory\n\nThe real reason is unknown without more context, but hopefully one of those potential explanations does the joke justice! Let me know if you have any other animal jokes I can try to decipher." additional_kwargs={} example=False
In [30]:
# First let's create a chain with a ChatModel
# We add in a string output parser here so the outputs between the two are the same type
from langchain.schema.output_parser import StrOutputParser
chat_prompt = ChatPromptTemplate.from_messages(
[
("system", "You're a nice assistant who always includes a compliment in your response"),
("human", "Why did the {animal} cross the road"),
]
)
# Here we're going to use a bad model name to easily create a chain that will error
chat_model = ChatOpenAI(model_name="gpt-fake")
bad_chain = chat_prompt | chat_model | StrOutputParser()In [31]:
# Now lets create a chain with the normal OpenAI model
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
prompt_template = """Instructions: You should always include a compliment in your response.
Question: Why did the {animal} cross the road?"""
prompt = PromptTemplate.from_template(prompt_template)
llm = OpenAI()
good_chain = prompt | llmIn [32]:
# We can now create a final chain which combines the two
chain = bad_chain.with_fallbacks([good_chain])
chain.invoke({"animal": "turtle"})Out [32]:
'\n\nAnswer: The turtle crossed the road to get to the other side, and I have to say he had some impressive determination.'
In [34]:
short_llm = ChatOpenAI()
long_llm = ChatOpenAI(model="gpt-3.5-turbo-16k")
llm = short_llm.with_fallbacks([long_llm])In [38]:
inputs = "What is the next number: " + ", ".join(["one", "two"] * 3000)In [40]:
try:
print(short_llm.invoke(inputs))
except Exception as e:
print(e)This model's maximum context length is 4097 tokens. However, your messages resulted in 12012 tokens. Please reduce the length of the messages.
In [41]:
try:
print(llm.invoke(inputs))
except Exception as e:
print(e)content='The next number in the sequence is two.' additional_kwargs={} example=False
In [42]:
from langchain.output_parsers import DatetimeOutputParserIn [67]:
prompt = ChatPromptTemplate.from_template(
"what time was {event} (in %Y-%m-%dT%H:%M:%S.%fZ format - only return this value)"
)In [75]:
# In this case we are going to do the fallbacks on the LLM + output parser level
# Because the error will get raised in the OutputParser
openai_35 = ChatOpenAI() | DatetimeOutputParser()
openai_4 = ChatOpenAI(model="gpt-4")| DatetimeOutputParser()In [77]:
only_35 = prompt | openai_35
fallback_4 = prompt | openai_35.with_fallbacks([openai_4])In [80]:
try:
print(only_35.invoke({"event": "the superbowl in 1994"}))
except Exception as e:
print(f"Error: {e}")Error: Could not parse datetime string: The Super Bowl in 1994 took place on January 30th at 3:30 PM local time. Converting this to the specified format (%Y-%m-%dT%H:%M:%S.%fZ) results in: 1994-01-30T15:30:00.000Z
In [81]:
try:
print(fallback_4.invoke({"event": "the superbowl in 1994"}))
except Exception as e:
print(f"Error: {e}")1994-01-30 15:30:00
In [ ]: