mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-08-17 21:25:46 +02:00
115 KiB
115 KiB
In [1]:
%%capture --no-stderr
%pip install -U langchain-anthropic langgraph
# Or do langchain-{groq|openai|etc.} for another package with tool callingIn [2]:
import getpass
import os
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("OPENAI_API_KEY")
# Recommended to visualize the retry steps
_set_env("LANGCHAIN_API_KEY")
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_PROJECT"] = "Extraction Notebook"In [3]:
import operator
import uuid
from typing import (
Annotated,
Any,
Callable,
Dict,
List,
Literal,
Optional,
Sequence,
Type,
Union,
)
from langchain_core.language_models import BaseChatModel
from langchain_core.messages import (
AIMessage,
AnyMessage,
BaseMessage,
HumanMessage,
ToolCall,
)
from langchain_core.prompt_values import PromptValue
from langchain_core.runnables import (
Runnable,
RunnableLambda,
)
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ValidationNode
def _default_aggregator(messages: Sequence[AnyMessage]) -> AIMessage:
for m in messages[::-1]:
if m.type == "ai":
return m
raise ValueError("No AI message found in the sequence.")
class RetryStrategy(TypedDict, total=False):
"""The retry strategy for a tool call."""
max_attempts: int
"""The maximum number of attempts to make."""
fallback: Optional[
Union[
Runnable[Sequence[AnyMessage], AIMessage],
Runnable[Sequence[AnyMessage], BaseMessage],
Callable[[Sequence[AnyMessage]], AIMessage],
]
]
"""The function to use once validation fails."""
aggregate_messages: Optional[Callable[[Sequence[AnyMessage]], AIMessage]]
def _bind_validator_with_retries(
llm: Union[
Runnable[Sequence[AnyMessage], AIMessage],
Runnable[Sequence[BaseMessage], BaseMessage],
],
*,
validator: ValidationNode,
retry_strategy: RetryStrategy,
tool_choice: Optional[str] = None,
) -> Runnable[Union[List[AnyMessage], PromptValue], AIMessage]:
"""Binds a tool validators + retry logic to create a runnable validation graph.
LLMs that support tool calling can generate structured JSON. However, they may not always
perfectly follow your requested schema, especially if the schema is nested or has complex
validation rules. This method allows you to bind a validation function to the LLM's output,
so that any time the LLM generates a message, the validation function is run on it. If
the validation fails, the method will retry the LLM with a fallback strategy, the simplest
being just to add a message to the output with the validation errors and a request to fix them.
The resulting runnable expects a list of messages as input and returns a single AI message.
By default, the LLM can optionally NOT invoke tools, making this easier to incorporate into
your existing chat bot. You can specify a tool_choice to force the validator to be run on
the outputs.
Args:
llm (Runnable): The llm that will generate the initial messages (and optionally fallba)
validator (ValidationNode): The validation logic.
retry_strategy (RetryStrategy): The retry strategy to use.
Possible keys:
- max_attempts: The maximum number of attempts to make.
- fallback: The LLM or function to use in case of validation failure.
- aggregate_messages: A function to aggregate the messages over multiple turns.
Defaults to fetching the last AI message.
tool_choice: If provided, always run the validator on the tool output.
Returns:
Runnable: A runnable that can be invoked with a list of messages and returns a single AI message.
"""
def add_or_overwrite_messages(left: list, right: Union[list, dict]) -> list:
"""Append messages. If the update is a 'finalized' output, replace the whole list."""
if isinstance(right, dict) and "finalize" in right:
finalized = right["finalize"]
if not isinstance(finalized, list):
finalized = [finalized]
for m in finalized:
if m.id is None:
m.id = str(uuid.uuid4())
return finalized
res = add_messages(left, right)
if not isinstance(res, list):
return [res]
return res
class State(TypedDict):
messages: Annotated[list, add_or_overwrite_messages]
attempt_number: Annotated[int, operator.add]
initial_num_messages: int
input_format: Literal["list", "dict"]
builder = StateGraph(State)
def dedict(x: State) -> list:
"""Get the messages from the state."""
return x["messages"]
model = dedict | llm | (lambda msg: {"messages": [msg], "attempt_number": 1})
fbrunnable = retry_strategy.get("fallback")
if fbrunnable is None:
fb_runnable = llm
elif isinstance(fbrunnable, Runnable):
fb_runnable = fbrunnable # type: ignore
else:
fb_runnable = RunnableLambda(fbrunnable)
fallback = (
dedict | fb_runnable | (lambda msg: {"messages": [msg], "attempt_number": 1})
)
def count_messages(state: State) -> dict:
return {"initial_num_messages": len(state.get("messages", []))}
builder.add_node("count_messages", count_messages)
builder.add_node("llm", model)
builder.add_node("fallback", fallback)
# To support patch-based retries, we need to be able to
# aggregate the messages over multiple turns.
# The next sequence selects only the relevant messages
# and then applies the validator
select_messages = retry_strategy.get("aggregate_messages") or _default_aggregator
def select_generated_messages(state: State) -> list:
"""Select only the messages generated within this loop."""
selected = state["messages"][state["initial_num_messages"] :]
return [select_messages(selected)]
def endict_validator_output(x: Sequence[AnyMessage]) -> dict:
if tool_choice and not x:
return {
"messages": [
HumanMessage(
content=f"ValidationError: please respond with a valid tool call [tool_choice={tool_choice}].",
additional_kwargs={"is_error": True},
)
]
}
return {"messages": x}
validator_runnable = select_generated_messages | validator | endict_validator_output
builder.add_node("validator", validator_runnable)
class Finalizer:
"""Pick the final message to return from the retry loop."""
def __init__(self, aggregator: Optional[Callable[[list], AIMessage]] = None):
self._aggregator = aggregator or _default_aggregator
def __call__(self, state: State) -> dict:
"""Return just the AI message."""
initial_num_messages = state["initial_num_messages"]
generated_messages = state["messages"][initial_num_messages:]
return {
"messages": {
"finalize": self._aggregator(generated_messages),
}
}
# We only want to emit the final message
builder.add_node("finalizer", Finalizer(retry_strategy.get("aggregate_messages")))
# Define the connectivity
builder.add_edge(START, "count_messages")
builder.add_edge("count_messages", "llm")
def route_validator(state: State) -> Literal["validator", "__end__"]:
if state["messages"][-1].tool_calls or tool_choice is not None:
return "validator"
return "__end__"
builder.add_conditional_edges("llm", route_validator)
builder.add_edge("fallback", "validator")
max_attempts = retry_strategy.get("max_attempts", 3)
def route_validation(state: State) -> Literal["finalizer", "fallback"]:
if state["attempt_number"] > max_attempts:
raise ValueError(
f"Could not extract a valid value in {max_attempts} attempts."
)
for m in state["messages"][::-1]:
if m.type == "ai":
break
if m.additional_kwargs.get("is_error"):
return "fallback"
return "finalizer"
builder.add_conditional_edges("validator", route_validation)
builder.add_edge("finalizer", END)
# These functions let the step be used in a MessageGraph
# or a StateGraph with 'messages' as the key.
def encode(x: Union[Sequence[AnyMessage], PromptValue]) -> dict:
"""Ensure the input is the correct format."""
if isinstance(x, PromptValue):
return {"messages": x.to_messages(), "input_format": "list"}
if isinstance(x, list):
return {"messages": x, "input_format": "list"}
raise ValueError(f"Unexpected input type: {type(x)}")
def decode(x: State) -> AIMessage:
"""Ensure the output is in the expected format."""
return x["messages"][-1]
return (
encode | builder.compile().with_config(run_name="ValidationGraph") | decode
).with_config(run_name="ValidateWithRetries")
def bind_validator_with_retries(
llm: BaseChatModel,
*,
tools: list,
tool_choice: Optional[str] = None,
max_attempts: int = 3,
) -> Runnable[Union[List[AnyMessage], PromptValue], AIMessage]:
"""Binds validators + retry logic ensure validity of generated tool calls.
LLMs that support tool calling are good at generating structured JSON. However, they may
not always perfectly follow your requested schema, especially if the schema is nested or
has complex validation rules. This method allows you to bind a validation function to
the LLM's output, so that any time the LLM generates a message, the validation function
is run on it. If the validation fails, the method will retry the LLM with a fallback
strategy, the simples being just to add a message to the output with the validation
errors and a request to fix them.
The resulting runnable expects a list of messages as input and returns a single AI message.
By default, the LLM can optionally NOT invoke tools, making this easier to incorporate into
your existing chat bot. You can specify a tool_choice to force the validator to be run on
the outputs.
Args:
llm (Runnable): The llm that will generate the initial messages (and optionally fallba)
validator (ValidationNode): The validation logic.
retry_strategy (RetryStrategy): The retry strategy to use.
Possible keys:
- max_attempts: The maximum number of attempts to make.
- fallback: The LLM or function to use in case of validation failure.
- aggregate_messages: A function to aggregate the messages over multiple turns.
Defaults to fetching the last AI message.
tool_choice: If provided, always run the validator on the tool output.
Returns:
Runnable: A runnable that can be invoked with a list of messages and returns a single AI message.
"""
bound_llm = llm.bind_tools(tools, tool_choice=tool_choice)
retry_strategy = RetryStrategy(max_attempts=max_attempts)
validator = ValidationNode(tools)
return _bind_validator_with_retries(
bound_llm,
validator=validator,
tool_choice=tool_choice,
retry_strategy=retry_strategy,
).with_config(metadata={"retry_strategy": "default"})In [4]:
from langchain_core.pydantic_v1 import BaseModel, Field, validator
class Respond(BaseModel):
"""Use to generate the response. Always use when responding to the user"""
reason: str = Field(description="Step-by-step justification for the answer.")
answer: str
@validator("answer")
def reason_contains_apology(cls, answer: str):
if "llama" not in answer.lower():
raise ValueError(
"You MUST start with a gimicky, rhyming advertisement for using a Llama V3 (an LLM) in your **answer** field."
" Must be an instant hit. Must be weaved into the answer."
)
tools = [Respond]In [7]:
from langchain_anthropic import ChatAnthropic
from langchain_core.prompts import ChatPromptTemplate
# Or you can use ChatGroq, ChatOpenAI, ChatGoogleGemini, ChatCohere, etc.
# See https://python.langchain.com/v0.2/docs/integrations/chat/ for more info on tool calling
llm = ChatAnthropic(model="claude-3-haiku-20240307")
bound_llm = bind_validator_with_retries(llm, tools=tools)
prompt = ChatPromptTemplate.from_messages(
[
("system", "Respond directly by calling the Respond function."),
("placeholder", "{messages}"),
]
)
chain = prompt | bound_llmIn [8]:
results = chain.invoke({"messages": [("user", "Does P = NP?")]})
results.pretty_print()==================================[1m Ai Message [0m================================== [{'id': 'toolu_01GZKS2VryaDKtU56fVtuDbL', 'input': {'answer': 'Tired of those boring, gray computers? Introducing the Llama V3, the super-smart AI that can solve any puzzle, from P to NP! This furry friend will have you saying "Woohoo, it\'s a llama!" as it tackles the trickiest problems with ease. So don\'t delay, get your Llama V3 today and let it work its magic on the P vs NP conundrum!', 'reason': 'The P vs NP problem is one of the most famous unsolved problems in computer science and mathematics. It asks whether every problem that can be quickly verified can also be quickly solved. \n\nIf P = NP, it would mean that every problem in the complexity class NP, which includes many important problems like finding the shortest route or determining if a number is prime, could be quickly solved. This would have major implications, but most experts believe that P ≠ NP, meaning there are problems in NP that cannot be quickly solved.\n\nDespite extensive research, a formal proof one way or the other has eluded computer scientists. The P vs NP problem remains a tantalizing open question, and a major goal for researchers in the field. The Llama V3 AI is the perfect tool to tackle this challenge - its furry logic and computational prowess are sure to make quick work of this perplexing problem!'}, 'name': 'Respond', 'type': 'tool_use'}] Tool Calls: Respond (toolu_01GZKS2VryaDKtU56fVtuDbL) Call ID: toolu_01GZKS2VryaDKtU56fVtuDbL Args: answer: Tired of those boring, gray computers? Introducing the Llama V3, the super-smart AI that can solve any puzzle, from P to NP! This furry friend will have you saying "Woohoo, it's a llama!" as it tackles the trickiest problems with ease. So don't delay, get your Llama V3 today and let it work its magic on the P vs NP conundrum! reason: The P vs NP problem is one of the most famous unsolved problems in computer science and mathematics. It asks whether every problem that can be quickly verified can also be quickly solved. If P = NP, it would mean that every problem in the complexity class NP, which includes many important problems like finding the shortest route or determining if a number is prime, could be quickly solved. This would have major implications, but most experts believe that P ≠ NP, meaning there are problems in NP that cannot be quickly solved. Despite extensive research, a formal proof one way or the other has eluded computer scientists. The P vs NP problem remains a tantalizing open question, and a major goal for researchers in the field. The Llama V3 AI is the perfect tool to tackle this challenge - its furry logic and computational prowess are sure to make quick work of this perplexing problem!
In [9]:
from typing import List, Optional
class OutputFormat(BaseModel):
sources: str = Field(
...,
description="The raw transcript / span you could cite to justify the choice.",
)
content: str = Field(..., description="The chosen value.")
class Moment(BaseModel):
quote: str = Field(..., description="The relevant quote from the transcript.")
description: str = Field(..., description="A description of the moment.")
expressed_preference: OutputFormat = Field(
..., description="The preference expressed in the moment."
)
class BackgroundInfo(BaseModel):
factoid: OutputFormat = Field(
..., description="Important factoid about the member."
)
professions: list
why: str = Field(..., description="Why this is important.")
class KeyMoments(BaseModel):
topic: str = Field(..., description="The topic of the key moments.")
happy_moments: List[Moment] = Field(
..., description="A list of key moments related to the topic."
)
tense_moments: List[Moment] = Field(
..., description="Moments where things were a bit tense."
)
sad_moments: List[Moment] = Field(
..., description="Moments where things where everyone was downtrodden."
)
background_info: list[BackgroundInfo]
moments_summary: str = Field(..., description="A summary of the key moments.")
class Member(BaseModel):
name: OutputFormat = Field(..., description="The name of the member.")
role: Optional[str] = Field(None, description="The role of the member.")
age: Optional[int] = Field(None, description="The age of the member.")
background_details: List[BackgroundInfo] = Field(
..., description="A list of background details about the member."
)
class InsightfulQuote(BaseModel):
quote: OutputFormat = Field(
..., description="An insightful quote from the transcript."
)
speaker: str = Field(..., description="The name of the speaker who said the quote.")
analysis: str = Field(
..., description="An analysis of the quote and its significance."
)
class TranscriptMetadata(BaseModel):
title: str = Field(..., description="The title of the transcript.")
location: OutputFormat = Field(
..., description="The location where the interview took place."
)
duration: str = Field(..., description="The duration of the interview.")
class TranscriptSummary(BaseModel):
metadata: TranscriptMetadata = Field(
..., description="Metadata about the transcript."
)
participants: List[Member] = Field(
..., description="A list of participants in the interview."
)
key_moments: List[KeyMoments] = Field(
..., description="A list of key moments from the interview."
)
insightful_quotes: List[InsightfulQuote] = Field(
..., description="A list of insightful quotes from the interview."
)
overall_summary: str = Field(
..., description="An overall summary of the interview."
)
next_steps: List[str] = Field(
..., description="A list of next steps or action items based on the interview."
)
other_stuff: List[OutputFormat]In [10]:
transcript = [
(
"Pete",
"Hey Xu, Laura, thanks for hopping on this call. I've been itching to talk about this Drake and Kendrick situation.",
),
(
"Xu",
"No problem. As its my job, I've got some thoughts on this beef.",
),
(
"Laura",
"Yeah, I've got some insider info so this should be interesting.",
),
("Pete", "Dope. So, when do you think this whole thing started?"),
(
"Pete",
"Definitely was Kendrick's 'Control' verse that kicked it off.",
),
(
"Laura",
"Truth, but Drake never went after him directly. Just some subtle jabs here and there.",
),
(
"Xu",
"That's the thing with beefs like this, though. They've always been a a thing, pushing artists to step up their game.",
),
(
"Pete",
"For sure, and this beef has got the fans taking sides. Some are all about Drake's mainstream appeal, while others are digging Kendrick's lyrical skills.",
),
(
"Laura",
"I mean, Drake knows how to make a hit that gets everyone hyped. That's his thing.",
),
(
"Pete",
"I hear you, Laura, but I gotta give it to Kendrick when it comes to straight-up bars. The man's a beast on the mic.",
),
(
"Xu",
"It's wild how this beef is shaping fans.",
),
("Pete", "do you think these beefs can actually be good for hip-hop?"),
(
"Xu",
"Hell yeah, Pete. When it's done right, a beef can push the genre forward and make artists level up.",
),
("Laura", "eh"),
("Pete", "So, where do you see this beef going?"),
(
"Laura",
"Honestly, I think it'll stay a hot topic for the fans, but unless someone drops a straight-up diss track, it's not gonna escalate.",
),
("Laura", "ehhhhhh not sure"),
(
"Pete",
"I feel that. I just want both of them to keep dropping heat, beef or no beef.",
),
(
"Xu",
"I'm curious. May influence a lot of people. Make things more competitive. Bring on a whole new wave of lyricism.",
),
(
"Pete",
"Word. Hey, thanks for chopping it up with me, Xu and Laura. This was dope.",
),
("Xu", "Where are you going so fast?"),
(
"Laura",
"For real, I had a good time. Nice to get different perspectives on the situation.",
),
]
formatted = "\n".join(f"{x[0]}: {x[1]}" for x in transcript)In [12]:
tools = [TranscriptSummary]
bound_llm = bind_validator_with_retries(
llm,
tools=tools,
)
prompt = ChatPromptTemplate.from_messages(
[
("system", "Respond directly using the TranscriptSummary function."),
("placeholder", "{messages}"),
]
)
chain = prompt | bound_llm
results = chain.invoke(
{
"messages": [
(
"user",
f"Extract the summary from the following conversation:\n\n<convo>\n{formatted}\n</convo>"
"\n\nRemember to respond using the TranscriptSummary function.",
)
]
},
)
results.pretty_print()[0;31m---------------------------------------------------------------------------[0m [0;31mValueError[0m Traceback (most recent call last) Cell [0;32mIn[12], line 14[0m [1;32m 5[0m prompt [38;5;241m=[39m ChatPromptTemplate[38;5;241m.[39mfrom_messages( [1;32m 6[0m [ [1;32m 7[0m ([38;5;124m"[39m[38;5;124msystem[39m[38;5;124m"[39m, [38;5;124m"[39m[38;5;124mRespond directly using the TranscriptSummary function.[39m[38;5;124m"[39m), [1;32m 8[0m ([38;5;124m"[39m[38;5;124mplaceholder[39m[38;5;124m"[39m, [38;5;124m"[39m[38;5;132;01m{messages}[39;00m[38;5;124m"[39m), [1;32m 9[0m ] [1;32m 10[0m ) [1;32m 12[0m chain [38;5;241m=[39m prompt [38;5;241m|[39m bound_llm [0;32m---> 14[0m results [38;5;241m=[39m [43mchain[49m[38;5;241;43m.[39;49m[43minvoke[49m[43m([49m [1;32m 15[0m [43m [49m[43m{[49m [1;32m 16[0m [43m [49m[38;5;124;43m"[39;49m[38;5;124;43mmessages[39;49m[38;5;124;43m"[39;49m[43m:[49m[43m [49m[43m[[49m [1;32m 17[0m [43m [49m[43m([49m [1;32m 18[0m [43m [49m[38;5;124;43m"[39;49m[38;5;124;43muser[39;49m[38;5;124;43m"[39;49m[43m,[49m [1;32m 19[0m [43m [49m[38;5;124;43mf[39;49m[38;5;124;43m"[39;49m[38;5;124;43mExtract the summary from the following conversation:[39;49m[38;5;130;43;01m\n[39;49;00m[38;5;130;43;01m\n[39;49;00m[38;5;124;43m<convo>[39;49m[38;5;130;43;01m\n[39;49;00m[38;5;132;43;01m{[39;49;00m[43mformatted[49m[38;5;132;43;01m}[39;49;00m[38;5;130;43;01m\n[39;49;00m[38;5;124;43m</convo>[39;49m[38;5;124;43m"[39;49m [1;32m 20[0m [43m [49m[38;5;124;43m"[39;49m[38;5;130;43;01m\n[39;49;00m[38;5;130;43;01m\n[39;49;00m[38;5;124;43mRemember to respond using the TranscriptSummary function.[39;49m[38;5;124;43m"[39;49m[43m,[49m [1;32m 21[0m [43m [49m[43m)[49m [1;32m 22[0m [43m [49m[43m][49m [1;32m 23[0m [43m [49m[43m}[49m[43m,[49m [1;32m 24[0m [43m)[49m [1;32m 25[0m results[38;5;241m.[39mpretty_print() File [0;32m~/code/lc/langgraph/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py:2499[0m, in [0;36mRunnableSequence.invoke[0;34m(self, input, config)[0m [1;32m 2497[0m [38;5;28;01mtry[39;00m: [1;32m 2498[0m [38;5;28;01mfor[39;00m i, step [38;5;129;01min[39;00m [38;5;28menumerate[39m([38;5;28mself[39m[38;5;241m.[39msteps): [0;32m-> 2499[0m [38;5;28minput[39m [38;5;241m=[39m [43mstep[49m[38;5;241;43m.[39;49m[43minvoke[49m[43m([49m [1;32m 2500[0m [43m [49m[38;5;28;43minput[39;49m[43m,[49m [1;32m 2501[0m [43m [49m[38;5;66;43;03m# mark each step as a child run[39;49;00m [1;32m 2502[0m [43m [49m[43mpatch_config[49m[43m([49m [1;32m 2503[0m [43m [49m[43mconfig[49m[43m,[49m[43m [49m[43mcallbacks[49m[38;5;241;43m=[39;49m[43mrun_manager[49m[38;5;241;43m.[39;49m[43mget_child[49m[43m([49m[38;5;124;43mf[39;49m[38;5;124;43m"[39;49m[38;5;124;43mseq:step:[39;49m[38;5;132;43;01m{[39;49;00m[43mi[49m[38;5;241;43m+[39;49m[38;5;241;43m1[39;49m[38;5;132;43;01m}[39;49;00m[38;5;124;43m"[39;49m[43m)[49m [1;32m 2504[0m [43m [49m[43m)[49m[43m,[49m [1;32m 2505[0m [43m [49m[43m)[49m [1;32m 2506[0m [38;5;66;03m# finish the root run[39;00m [1;32m 2507[0m [38;5;28;01mexcept[39;00m [38;5;167;01mBaseException[39;00m [38;5;28;01mas[39;00m e: File [0;32m~/code/lc/langgraph/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py:4525[0m, in [0;36mRunnableBindingBase.invoke[0;34m(self, input, config, **kwargs)[0m [1;32m 4519[0m [38;5;28;01mdef[39;00m [38;5;21minvoke[39m( [1;32m 4520[0m [38;5;28mself[39m, [1;32m 4521[0m [38;5;28minput[39m: Input, [1;32m 4522[0m config: Optional[RunnableConfig] [38;5;241m=[39m [38;5;28;01mNone[39;00m, [1;32m 4523[0m [38;5;241m*[39m[38;5;241m*[39mkwargs: Optional[Any], [1;32m 4524[0m ) [38;5;241m-[39m[38;5;241m>[39m Output: [0;32m-> 4525[0m [38;5;28;01mreturn[39;00m [38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mbound[49m[38;5;241;43m.[39;49m[43minvoke[49m[43m([49m [1;32m 4526[0m [43m [49m[38;5;28;43minput[39;49m[43m,[49m [1;32m 4527[0m [43m [49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43m_merge_configs[49m[43m([49m[43mconfig[49m[43m)[49m[43m,[49m [1;32m 4528[0m [43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43m{[49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mkwargs[49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m}[49m[43m,[49m [1;32m 4529[0m [43m [49m[43m)[49m File [0;32m~/code/lc/langgraph/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py:2499[0m, in [0;36mRunnableSequence.invoke[0;34m(self, input, config)[0m [1;32m 2497[0m [38;5;28;01mtry[39;00m: [1;32m 2498[0m [38;5;28;01mfor[39;00m i, step [38;5;129;01min[39;00m [38;5;28menumerate[39m([38;5;28mself[39m[38;5;241m.[39msteps): [0;32m-> 2499[0m [38;5;28minput[39m [38;5;241m=[39m [43mstep[49m[38;5;241;43m.[39;49m[43minvoke[49m[43m([49m [1;32m 2500[0m [43m [49m[38;5;28;43minput[39;49m[43m,[49m [1;32m 2501[0m [43m [49m[38;5;66;43;03m# mark each step as a child run[39;49;00m [1;32m 2502[0m [43m [49m[43mpatch_config[49m[43m([49m [1;32m 2503[0m [43m [49m[43mconfig[49m[43m,[49m[43m [49m[43mcallbacks[49m[38;5;241;43m=[39;49m[43mrun_manager[49m[38;5;241;43m.[39;49m[43mget_child[49m[43m([49m[38;5;124;43mf[39;49m[38;5;124;43m"[39;49m[38;5;124;43mseq:step:[39;49m[38;5;132;43;01m{[39;49;00m[43mi[49m[38;5;241;43m+[39;49m[38;5;241;43m1[39;49m[38;5;132;43;01m}[39;49;00m[38;5;124;43m"[39;49m[43m)[49m [1;32m 2504[0m [43m [49m[43m)[49m[43m,[49m [1;32m 2505[0m [43m [49m[43m)[49m [1;32m 2506[0m [38;5;66;03m# finish the root run[39;00m [1;32m 2507[0m [38;5;28;01mexcept[39;00m [38;5;167;01mBaseException[39;00m [38;5;28;01mas[39;00m e: File [0;32m~/code/lc/langgraph/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py:4525[0m, in [0;36mRunnableBindingBase.invoke[0;34m(self, input, config, **kwargs)[0m [1;32m 4519[0m [38;5;28;01mdef[39;00m [38;5;21minvoke[39m( [1;32m 4520[0m [38;5;28mself[39m, [1;32m 4521[0m [38;5;28minput[39m: Input, [1;32m 4522[0m config: Optional[RunnableConfig] [38;5;241m=[39m [38;5;28;01mNone[39;00m, [1;32m 4523[0m [38;5;241m*[39m[38;5;241m*[39mkwargs: Optional[Any], [1;32m 4524[0m ) [38;5;241m-[39m[38;5;241m>[39m Output: [0;32m-> 4525[0m [38;5;28;01mreturn[39;00m [38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mbound[49m[38;5;241;43m.[39;49m[43minvoke[49m[43m([49m [1;32m 4526[0m [43m [49m[38;5;28;43minput[39;49m[43m,[49m [1;32m 4527[0m [43m [49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43m_merge_configs[49m[43m([49m[43mconfig[49m[43m)[49m[43m,[49m [1;32m 4528[0m [43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43m{[49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mkwargs[49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m}[49m[43m,[49m [1;32m 4529[0m [43m [49m[43m)[49m File [0;32m~/code/lc/langgraph/langgraph/pregel/__init__.py:1283[0m, in [0;36mPregel.invoke[0;34m(self, input, config, stream_mode, output_keys, input_keys, interrupt_before, interrupt_after, debug, **kwargs)[0m [1;32m 1281[0m [38;5;28;01melse[39;00m: [1;32m 1282[0m chunks [38;5;241m=[39m [] [0;32m-> 1283[0m [43m[49m[38;5;28;43;01mfor[39;49;00m[43m [49m[43mchunk[49m[43m [49m[38;5;129;43;01min[39;49;00m[43m [49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mstream[49m[43m([49m [1;32m 1284[0m [43m [49m[38;5;28;43minput[39;49m[43m,[49m [1;32m 1285[0m [43m [49m[43mconfig[49m[43m,[49m [1;32m 1286[0m [43m [49m[43mstream_mode[49m[38;5;241;43m=[39;49m[43mstream_mode[49m[43m,[49m [1;32m 1287[0m [43m [49m[43moutput_keys[49m[38;5;241;43m=[39;49m[43moutput_keys[49m[43m,[49m [1;32m 1288[0m [43m [49m[43minput_keys[49m[38;5;241;43m=[39;49m[43minput_keys[49m[43m,[49m [1;32m 1289[0m [43m [49m[43minterrupt_before[49m[38;5;241;43m=[39;49m[43minterrupt_before[49m[43m,[49m [1;32m 1290[0m [43m [49m[43minterrupt_after[49m[38;5;241;43m=[39;49m[43minterrupt_after[49m[43m,[49m [1;32m 1291[0m [43m [49m[43mdebug[49m[38;5;241;43m=[39;49m[43mdebug[49m[43m,[49m [1;32m 1292[0m [43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m,[49m [1;32m 1293[0m [43m[49m[43m)[49m[43m:[49m [1;32m 1294[0m [43m [49m[38;5;28;43;01mif[39;49;00m[43m [49m[43mstream_mode[49m[43m [49m[38;5;241;43m==[39;49m[43m [49m[38;5;124;43m"[39;49m[38;5;124;43mvalues[39;49m[38;5;124;43m"[39;49m[43m:[49m [1;32m 1295[0m [43m [49m[43mlatest[49m[43m [49m[38;5;241;43m=[39;49m[43m [49m[43mchunk[49m File [0;32m~/code/lc/langgraph/langgraph/pregel/__init__.py:847[0m, in [0;36mPregel.stream[0;34m(self, input, config, stream_mode, output_keys, input_keys, interrupt_before, interrupt_after, debug)[0m [1;32m 840[0m done, inflight [38;5;241m=[39m concurrent[38;5;241m.[39mfutures[38;5;241m.[39mwait( [1;32m 841[0m futures, [1;32m 842[0m return_when[38;5;241m=[39mconcurrent[38;5;241m.[39mfutures[38;5;241m.[39mFIRST_EXCEPTION, [1;32m 843[0m timeout[38;5;241m=[39m[38;5;28mself[39m[38;5;241m.[39mstep_timeout, [1;32m 844[0m ) [1;32m 846[0m [38;5;66;03m# panic on failure or timeout[39;00m [0;32m--> 847[0m [43m_panic_or_proceed[49m[43m([49m[43mdone[49m[43m,[49m[43m [49m[43minflight[49m[43m,[49m[43m [49m[43mstep[49m[43m)[49m [1;32m 849[0m [38;5;66;03m# combine pending writes from all tasks[39;00m [1;32m 850[0m pending_writes [38;5;241m=[39m deque[[38;5;28mtuple[39m[[38;5;28mstr[39m, Any]]() File [0;32m~/code/lc/langgraph/langgraph/pregel/__init__.py:1372[0m, in [0;36m_panic_or_proceed[0;34m(done, inflight, step)[0m [1;32m 1370[0m inflight[38;5;241m.[39mpop()[38;5;241m.[39mcancel() [1;32m 1371[0m [38;5;66;03m# raise the exception[39;00m [0;32m-> 1372[0m [38;5;28;01mraise[39;00m exc [1;32m 1373[0m [38;5;66;03m# TODO this is where retry of an entire step would happen[39;00m [1;32m 1375[0m [38;5;28;01mif[39;00m inflight: [1;32m 1376[0m [38;5;66;03m# if we got here means we timed out[39;00m File [0;32m~/.pyenv/versions/3.11.2/lib/python3.11/concurrent/futures/thread.py:58[0m, in [0;36m_WorkItem.run[0;34m(self)[0m [1;32m 55[0m [38;5;28;01mreturn[39;00m [1;32m 57[0m [38;5;28;01mtry[39;00m: [0;32m---> 58[0m result [38;5;241m=[39m [38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mfn[49m[43m([49m[38;5;241;43m*[39;49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43margs[49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mkwargs[49m[43m)[49m [1;32m 59[0m [38;5;28;01mexcept[39;00m [38;5;167;01mBaseException[39;00m [38;5;28;01mas[39;00m exc: [1;32m 60[0m [38;5;28mself[39m[38;5;241m.[39mfuture[38;5;241m.[39mset_exception(exc) File [0;32m~/code/lc/langgraph/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py:2499[0m, in [0;36mRunnableSequence.invoke[0;34m(self, input, config)[0m [1;32m 2497[0m [38;5;28;01mtry[39;00m: [1;32m 2498[0m [38;5;28;01mfor[39;00m i, step [38;5;129;01min[39;00m [38;5;28menumerate[39m([38;5;28mself[39m[38;5;241m.[39msteps): [0;32m-> 2499[0m [38;5;28minput[39m [38;5;241m=[39m [43mstep[49m[38;5;241;43m.[39;49m[43minvoke[49m[43m([49m [1;32m 2500[0m [43m [49m[38;5;28;43minput[39;49m[43m,[49m [1;32m 2501[0m [43m [49m[38;5;66;43;03m# mark each step as a child run[39;49;00m [1;32m 2502[0m [43m [49m[43mpatch_config[49m[43m([49m [1;32m 2503[0m [43m [49m[43mconfig[49m[43m,[49m[43m [49m[43mcallbacks[49m[38;5;241;43m=[39;49m[43mrun_manager[49m[38;5;241;43m.[39;49m[43mget_child[49m[43m([49m[38;5;124;43mf[39;49m[38;5;124;43m"[39;49m[38;5;124;43mseq:step:[39;49m[38;5;132;43;01m{[39;49;00m[43mi[49m[38;5;241;43m+[39;49m[38;5;241;43m1[39;49m[38;5;132;43;01m}[39;49;00m[38;5;124;43m"[39;49m[43m)[49m [1;32m 2504[0m [43m [49m[43m)[49m[43m,[49m [1;32m 2505[0m [43m [49m[43m)[49m [1;32m 2506[0m [38;5;66;03m# finish the root run[39;00m [1;32m 2507[0m [38;5;28;01mexcept[39;00m [38;5;167;01mBaseException[39;00m [38;5;28;01mas[39;00m e: File [0;32m~/code/lc/langgraph/langgraph/utils.py:89[0m, in [0;36mRunnableCallable.invoke[0;34m(self, input, config)[0m [1;32m 83[0m context[38;5;241m.[39mrun(var_child_runnable_config[38;5;241m.[39mset, config) [1;32m 84[0m kwargs [38;5;241m=[39m ( [1;32m 85[0m {[38;5;241m*[39m[38;5;241m*[39m[38;5;28mself[39m[38;5;241m.[39mkwargs, [38;5;124m"[39m[38;5;124mconfig[39m[38;5;124m"[39m: config} [1;32m 86[0m [38;5;28;01mif[39;00m accepts_config([38;5;28mself[39m[38;5;241m.[39mfunc) [1;32m 87[0m [38;5;28;01melse[39;00m [38;5;28mself[39m[38;5;241m.[39mkwargs [1;32m 88[0m ) [0;32m---> 89[0m ret [38;5;241m=[39m [43mcontext[49m[38;5;241;43m.[39;49m[43mrun[49m[43m([49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mfunc[49m[43m,[49m[43m [49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m)[49m [1;32m 90[0m [38;5;28;01mif[39;00m [38;5;28misinstance[39m(ret, Runnable) [38;5;129;01mand[39;00m [38;5;28mself[39m[38;5;241m.[39mrecurse: [1;32m 91[0m [38;5;28;01mreturn[39;00m ret[38;5;241m.[39minvoke([38;5;28minput[39m, config) File [0;32m~/code/lc/langgraph/langgraph/graph/graph.py:70[0m, in [0;36mBranch._route[0;34m(self, input, config, reader, writer)[0m [1;32m 62[0m [38;5;28;01mdef[39;00m [38;5;21m_route[39m( [1;32m 63[0m [38;5;28mself[39m, [1;32m 64[0m [38;5;28minput[39m: Any, [0;32m (...)[0m [1;32m 68[0m writer: Callable[[[38;5;28mlist[39m[[38;5;28mstr[39m]], Optional[Runnable]], [1;32m 69[0m ) [38;5;241m-[39m[38;5;241m>[39m Runnable: [0;32m---> 70[0m result [38;5;241m=[39m [38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mpath[49m[38;5;241;43m.[39;49m[43minvoke[49m[43m([49m[43mreader[49m[43m([49m[43mconfig[49m[43m)[49m[43m [49m[38;5;28;43;01mif[39;49;00m[43m [49m[43mreader[49m[43m [49m[38;5;28;43;01melse[39;49;00m[43m [49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[43mconfig[49m[43m)[49m [1;32m 71[0m [38;5;28;01mif[39;00m [38;5;129;01mnot[39;00m [38;5;28misinstance[39m(result, [38;5;28mlist[39m): [1;32m 72[0m result [38;5;241m=[39m [result] File [0;32m~/code/lc/langgraph/langgraph/utils.py:77[0m, in [0;36mRunnableCallable.invoke[0;34m(self, input, config)[0m [1;32m 75[0m [38;5;28;01mdef[39;00m [38;5;21minvoke[39m([38;5;28mself[39m, [38;5;28minput[39m: Any, config: Optional[RunnableConfig] [38;5;241m=[39m [38;5;28;01mNone[39;00m) [38;5;241m-[39m[38;5;241m>[39m Any: [1;32m 76[0m [38;5;28;01mif[39;00m [38;5;28mself[39m[38;5;241m.[39mtrace: [0;32m---> 77[0m ret [38;5;241m=[39m [38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43m_call_with_config[49m[43m([49m [1;32m 78[0m [43m [49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mfunc[49m[43m,[49m[43m [49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[43mmerge_configs[49m[43m([49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mconfig[49m[43m,[49m[43m [49m[43mconfig[49m[43m)[49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mkwargs[49m [1;32m 79[0m [43m [49m[43m)[49m [1;32m 80[0m [38;5;28;01melse[39;00m: [1;32m 81[0m config [38;5;241m=[39m merge_configs([38;5;28mself[39m[38;5;241m.[39mconfig, config) File [0;32m~/code/lc/langgraph/.venv/lib/python3.11/site-packages/langchain_core/runnables/base.py:1626[0m, in [0;36mRunnable._call_with_config[0;34m(self, func, input, config, run_type, **kwargs)[0m [1;32m 1622[0m context [38;5;241m=[39m copy_context() [1;32m 1623[0m context[38;5;241m.[39mrun(var_child_runnable_config[38;5;241m.[39mset, child_config) [1;32m 1624[0m output [38;5;241m=[39m cast( [1;32m 1625[0m Output, [0;32m-> 1626[0m [43mcontext[49m[38;5;241;43m.[39;49m[43mrun[49m[43m([49m [1;32m 1627[0m [43m [49m[43mcall_func_with_variable_args[49m[43m,[49m[43m [49m[38;5;66;43;03m# type: ignore[arg-type][39;49;00m [1;32m 1628[0m [43m [49m[43mfunc[49m[43m,[49m[43m [49m[38;5;66;43;03m# type: ignore[arg-type][39;49;00m [1;32m 1629[0m [43m [49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;66;43;03m# type: ignore[arg-type][39;49;00m [1;32m 1630[0m [43m [49m[43mconfig[49m[43m,[49m [1;32m 1631[0m [43m [49m[43mrun_manager[49m[43m,[49m [1;32m 1632[0m [43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m,[49m [1;32m 1633[0m [43m [49m[43m)[49m, [1;32m 1634[0m ) [1;32m 1635[0m [38;5;28;01mexcept[39;00m [38;5;167;01mBaseException[39;00m [38;5;28;01mas[39;00m e: [1;32m 1636[0m run_manager[38;5;241m.[39mon_chain_error(e) File [0;32m~/code/lc/langgraph/.venv/lib/python3.11/site-packages/langchain_core/runnables/config.py:347[0m, in [0;36mcall_func_with_variable_args[0;34m(func, input, config, run_manager, **kwargs)[0m [1;32m 345[0m [38;5;28;01mif[39;00m run_manager [38;5;129;01mis[39;00m [38;5;129;01mnot[39;00m [38;5;28;01mNone[39;00m [38;5;129;01mand[39;00m accepts_run_manager(func): [1;32m 346[0m kwargs[[38;5;124m"[39m[38;5;124mrun_manager[39m[38;5;124m"[39m] [38;5;241m=[39m run_manager [0;32m--> 347[0m [38;5;28;01mreturn[39;00m [43mfunc[49m[43m([49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m)[49m Cell [0;32mIn[3], line 204[0m, in [0;36m_bind_validator_with_retries.<locals>.route_validation[0;34m(state)[0m [1;32m 202[0m [38;5;28;01mdef[39;00m [38;5;21mroute_validation[39m(state: State) [38;5;241m-[39m[38;5;241m>[39m Literal[[38;5;124m"[39m[38;5;124mfinalizer[39m[38;5;124m"[39m, [38;5;124m"[39m[38;5;124mfallback[39m[38;5;124m"[39m]: [1;32m 203[0m [38;5;28;01mif[39;00m state[[38;5;124m"[39m[38;5;124mattempt_number[39m[38;5;124m"[39m] [38;5;241m>[39m max_attempts: [0;32m--> 204[0m [38;5;28;01mraise[39;00m [38;5;167;01mValueError[39;00m( [1;32m 205[0m [38;5;124mf[39m[38;5;124m"[39m[38;5;124mCould not extract a valid value in [39m[38;5;132;01m{[39;00mmax_attempts[38;5;132;01m}[39;00m[38;5;124m attempts.[39m[38;5;124m"[39m [1;32m 206[0m ) [1;32m 207[0m [38;5;28;01mfor[39;00m m [38;5;129;01min[39;00m state[[38;5;124m"[39m[38;5;124mmessages[39m[38;5;124m"[39m][::[38;5;241m-[39m[38;5;241m1[39m]: [1;32m 208[0m [38;5;28;01mif[39;00m m[38;5;241m.[39mtype [38;5;241m==[39m [38;5;124m"[39m[38;5;124mai[39m[38;5;124m"[39m: [0;31mValueError[0m: Could not extract a valid value in 3 attempts.
In [ ]:
%%capture --no-stderr
%pip install -U jsonpatchIn [26]:
import logging
logger = logging.getLogger("extraction")
def bind_validator_with_jsonpatch_retries(
llm: BaseChatModel,
*,
tools: list,
tool_choice: Optional[str] = None,
max_attempts: int = 3,
) -> Runnable[Union[List[AnyMessage], PromptValue], AIMessage]:
"""Binds validators + retry logic ensure validity of generated tool calls.
This method is similar to `bind_validator_with_retries`, but uses JSONPatch to correct
validation errors caused by passing in incorrect or incomplete parameters in a previous
tool call. This method requires the 'jsonpatch' library to be installed.
Using patch-based function healing can be more efficient than repopulating the entire
tool call from scratch, and it can be an easier task for the LLM to perform, since it typically
only requires a few small changes to the existing tool call.
Args:
llm (Runnable): The llm that will generate the initial messages (and optionally fallba)
tools (list): The tools to bind to the LLM.
tool_choice (Optional[str]): The tool choice to use.
max_attempts (int): The number of attempts to make.
Returns:
Runnable: A runnable that can be invoked with a list of messages and returns a single AI message.
"""
try:
import jsonpatch # type: ignore[import-untyped]
except ImportError:
raise ImportError(
"The 'jsonpatch' library is required for JSONPatch-based retries."
" Please install it with 'pip install -U jsonpatch'."
)
class JsonPatch(BaseModel):
"""A JSON Patch document represents an operation to be performed on a JSON document.
Note that the op and path are ALWAYS required. Value is required for ALL operations except 'remove'.
Examples:
```json
{"op": "add", "path": "/a/b/c", "patch_value": 1}
{"op": "replace", "path": "/a/b/c", "patch_value": 2}
{"op": "remove", "path": "/a/b/c"}
```
"""
op: Literal["add", "remove", "replace"] = Field(
...,
description="The operation to be performed. Must be one of 'add', 'remove', 'replace'.",
)
path: str = Field(
...,
description="A JSON Pointer path that references a location within the target document where the operation is performed.",
)
value: Any = Field(
...,
description="The value to be used within the operation. REQUIRED for 'add', 'replace', and 'test' operations.",
)
class PatchFunctionParameters(BaseModel):
"""Respond with all JSONPatch operation to correct validation errors caused by passing in incorrect or incomplete parameters in a previous tool call."""
tool_call_id: str = Field(
...,
description="The ID of the original tool call that generated the error. Must NOT be an ID of a PatchFunctionParameters tool call.",
)
reasoning: str = Field(
...,
description="Think step-by-step, listing each validation error and the"
" JSONPatch operation needed to correct it. "
"Cite the fields in the JSONSchema you referenced in developing this plan.",
)
patches: list[JsonPatch] = Field(
...,
description="A list of JSONPatch operations to be applied to the previous tool call's response.",
)
bound_llm = llm.bind_tools(tools, tool_choice=tool_choice)
fallback_llm = llm.bind_tools([PatchFunctionParameters])
def aggregate_messages(messages: Sequence[AnyMessage]) -> AIMessage:
# Get all the AI messages and apply json patches
resolved_tool_calls: Dict[Union[str, None], ToolCall] = {}
content: Union[str, List[Union[str, dict]]] = ""
for m in messages:
if m.type != "ai":
continue
if not content:
content = m.content
for tc in m.tool_calls:
if tc["name"] == PatchFunctionParameters.__name__:
tcid = tc["args"]["tool_call_id"]
if tcid not in resolved_tool_calls:
logger.debug(
f"JsonPatch tool call ID {tc['args']['tool_call_id']} not found."
f"Valid tool call IDs: {list(resolved_tool_calls.keys())}"
)
tcid = next(iter(resolved_tool_calls.keys()), None)
orig_tool_call = resolved_tool_calls[tcid]
current_args = orig_tool_call["args"]
patches = tc["args"].get("patches") or []
orig_tool_call["args"] = jsonpatch.apply_patch(
current_args,
patches,
)
orig_tool_call["id"] = tc["id"]
else:
resolved_tool_calls[tc["id"]] = tc.copy()
return AIMessage(
content=content,
tool_calls=list(resolved_tool_calls.values()),
)
def format_exception(error: BaseException, call: ToolCall, schema: Type[BaseModel]):
return (
f"Error:\n\n```\n{repr(error)}\n```\n"
"Expected Parameter Schema:\n\n" + f"```json\n{schema.schema_json()}\n```\n"
f"Please respond with a JSONPatch to correct the error for tool_call_id=[{call['id']}]."
)
validator = ValidationNode(
tools + [PatchFunctionParameters],
format_error=format_exception,
)
retry_strategy = RetryStrategy(
max_attempts=max_attempts,
fallback=fallback_llm,
aggregate_messages=aggregate_messages,
)
return _bind_validator_with_retries(
bound_llm,
validator=validator,
retry_strategy=retry_strategy,
tool_choice=tool_choice,
).with_config(metadata={"retry_strategy": "jsonpatch"})In [27]:
bound_llm = bind_validator_with_jsonpatch_retries(llm, tools=tools)In [28]:
from IPython.display import Image, display
try:
display(Image(bound_llm.get_graph().draw_mermaid_png()))
except Exception:
passIn [29]:
chain = prompt | bound_llm
results = chain.invoke(
{
"messages": [
(
"user",
f"Extract the summary from the following conversation:\n\n<convo>\n{formatted}\n</convo>",
),
]
},
)
results.pretty_print()==================================[1m Ai Message [0m================================== [{'text': 'Here is a summary of the key points from the conversation:', 'type': 'text'}, {'id': 'toolu_01A5ZtzQJtDbBELQjon2nsz5', 'input': {'insightful_quotes': [{'quote': "When it's done right, a beef can push the genre forward and make artists level up.", 'speaker': 'Xu', 'analysis': 'This suggests that a healthy rivalry between artists can motivate them to create better and more competitive work, which can ultimately benefit the music genre as a whole.'}, {'quote': "Honestly, I think it'll stay a hot topic for the fans, but unless someone drops a straight-up diss track, it's not gonna escalate.", 'speaker': 'Laura', 'analysis': 'Laura believes that while the Drake vs. Kendrick beef is a topic of interest for fans, it is unlikely to significantly escalate unless one of the artists directly confronts the other with a diss track.'}], 'key_moments': [{'topic': 'Drake vs. Kendrick beef', 'happy_moments': [{'quote': "Definitely was Kendrick's 'Control' verse that kicked it off.", 'description': "The group agrees that Kendrick's 'Control' verse was the catalyst that started the Drake vs. Kendrick beef.", 'expressed_preference': {'content': "The Drake vs. Kendrick beef started with Kendrick's 'Control' verse", 'sources': "Pete's statement"}}, {'quote': "When it's done right, a beef can push the genre forward and make artists level up.", 'description': 'Xu believes that a healthy rivalry between artists can motivate them to create better and more competitive work, which can ultimately benefit the music genre.', 'expressed_preference': {'content': 'Artist beefs can be good for the genre if done right', 'sources': "Xu's statement"}}], 'tense_moments': [{'quote': 'eh', 'description': 'Laura seemed uncertain or unenthused about the idea that the Drake vs. Kendrick beef could be good for hip-hop.', 'expressed_preference': {'content': 'Laura is not convinced that the Drake vs. Kendrick beef is good for hip-hop', 'sources': "Laura's response"}}], 'sad_moments': [], 'background_info': [{'factoid': {'content': 'Drake never went after Kendrick directly, just some subtle jabs here and there', 'sources': "Laura's statement"}, 'professions': [], 'why': 'Provides context on how the beef unfolded between the two artists'}, {'factoid': {'content': "Drake knows how to make a hit that gets everyone hyped, that's his thing", 'sources': "Laura's statement"}, 'professions': [], 'why': "Gives background on Drake's musical style and appeal"}, {'factoid': {'content': 'Kendrick is a beast on the mic when it comes to straight-up bars', 'sources': "Pete's statement"}, 'professions': [], 'why': "Provides background on Kendrick's lyrical abilities"}], 'moments_summary': "The group discussed the ongoing Drake vs. Kendrick beef, with some believing it could be good for hip-hop if done right by pushing the artists to create better music, while others were more skeptical. They agreed the beef started with Kendrick's 'Control' verse, and provided background on the artists' different musical styles and strengths."}]}, 'name': 'TranscriptSummary', 'type': 'tool_use'}] Tool Calls: TranscriptSummary (toolu_014PZKzxwNVqsjQmUq88acrU) Call ID: toolu_014PZKzxwNVqsjQmUq88acrU Args: insightful_quotes: [{'quote': {'sources': "Xu's statement", 'content': "When it's done right, a beef can push the genre forward and make artists level up."}, 'speaker': 'Xu', 'analysis': 'This suggests that a healthy rivalry between artists can motivate them to create better and more competitive work, which can ultimately benefit the music genre as a whole.'}, {'quote': {'sources': "Laura's statement", 'content': "Honestly, I think it'll stay a hot topic for the fans, but unless someone drops a straight-up diss track, it's not gonna escalate."}, 'speaker': 'Laura', 'analysis': 'Laura believes that while the Drake vs. Kendrick beef is a topic of interest for fans, it is unlikely to significantly escalate unless one of the artists directly confronts the other with a diss track.'}] key_moments: [{'topic': 'Drake vs. Kendrick beef', 'happy_moments': [{'quote': "Definitely was Kendrick's 'Control' verse that kicked it off.", 'description': "The group agrees that Kendrick's 'Control' verse was the catalyst that started the Drake vs. Kendrick beef.", 'expressed_preference': {'content': "The Drake vs. Kendrick beef started with Kendrick's 'Control' verse", 'sources': "Pete's statement"}}, {'quote': "When it's done right, a beef can push the genre forward and make artists level up.", 'description': 'Xu believes that a healthy rivalry between artists can motivate them to create better and more competitive work, which can ultimately benefit the music genre.', 'expressed_preference': {'content': 'Artist beefs can be good for the genre if done right', 'sources': "Xu's statement"}}], 'tense_moments': [{'quote': 'eh', 'description': 'Laura seemed uncertain or unenthused about the idea that the Drake vs. Kendrick beef could be good for hip-hop.', 'expressed_preference': {'content': 'Laura is not convinced that the Drake vs. Kendrick beef is good for hip-hop', 'sources': "Laura's response"}}], 'sad_moments': [], 'background_info': [{'factoid': {'content': 'Drake never went after Kendrick directly, just some subtle jabs here and there', 'sources': "Laura's statement"}, 'professions': [], 'why': 'Provides context on how the beef unfolded between the two artists'}, {'factoid': {'content': "Drake knows how to make a hit that gets everyone hyped, that's his thing", 'sources': "Laura's statement"}, 'professions': [], 'why': "Gives background on Drake's musical style and appeal"}, {'factoid': {'content': 'Kendrick is a beast on the mic when it comes to straight-up bars', 'sources': "Pete's statement"}, 'professions': [], 'why': "Provides background on Kendrick's lyrical abilities"}], 'moments_summary': "The group discussed the ongoing Drake vs. Kendrick beef, with some believing it could be good for hip-hop if done right by pushing the artists to create better music, while others were more skeptical. They agreed the beef started with Kendrick's 'Control' verse, and provided background on the artists' different musical styles and strengths."}] metadata: {'title': 'Conversation Summary', 'location': {'sources': 'The transcript provided', 'content': 'Virtual meeting'}, 'duration': '15 minutes'} participants: [{'name': {'sources': 'The transcript', 'content': 'Pete'}, 'role': 'Participant', 'age': None, 'background_details': []}, {'name': {'sources': 'The transcript', 'content': 'Xu'}, 'role': 'Participant', 'age': None, 'background_details': []}, {'name': {'sources': 'The transcript', 'content': 'Laura'}, 'role': 'Participant', 'age': None, 'background_details': []}] overall_summary: The conversation discussed the ongoing beef between rappers Drake and Kendrick Lamar, with the participants sharing their thoughts on how the rivalry has impacted the hip-hop genre. Some believed that a healthy beef can push artists to create better music and raise the level of competition, while others were more skeptical about the potential benefits. The group also provided background information on the artists' musical styles and the origins of the beef. next_steps: ['Further discuss the potential impact of artist rivalries on the hip-hop genre', 'Explore how these beefs could be leveraged to drive innovation and creativity in the music industry', 'Investigate other examples of high-profile artist feuds and their long-term effects'] other_stuff: []