diff --git a/docs/_scripts/copy_notebooks.py b/docs/_scripts/copy_notebooks.py index 2e3d9024a..021afcec3 100644 --- a/docs/_scripts/copy_notebooks.py +++ b/docs/_scripts/copy_notebooks.py @@ -27,6 +27,7 @@ _MANUAL = { "branching.ipynb", "dynamically-returning-directly.ipynb", "configuration.ipynb", + "extraction/retries.ipynb", ], "tutorials": [ "introduction.ipynb", diff --git a/docs/docs/how-tos/index.md b/docs/docs/how-tos/index.md index 656847abd..7e277c3de 100644 --- a/docs/docs/how-tos/index.md +++ b/docs/docs/how-tos/index.md @@ -30,4 +30,8 @@ The following examples are useful especially if you are used to LangChain's Agen ### Alternative ways to define State -- [Pydantic State](state-model.ipynb): Use a pydantic model as your state \ No newline at end of file +- [Pydantic State](state-model.ipynb): Use a pydantic model as your state + +### Structured Output + +- [Extraction with Re-prompting](./extraction/retries.ipynb): how to generate complex nested schemas using JSONPatch retries, for when function calling is insufficient, and regular reprompting still fails to generate valid results. \ No newline at end of file diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 61a383a14..6266ee28e 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -143,6 +143,8 @@ nav: - "Managing Agent Steps": how-tos/managing-agent-steps.ipynb - Alternative State Definitions: - "Pydantic State": how-tos/state-model.ipynb + - Structured Output: + - "Extraction with Re-prompting": how-tos/extraction/retries.ipynb - 'Conceptual Guides': - 'concepts/index.md' - Reference: diff --git a/examples/extraction/retries.ipynb b/examples/extraction/retries.ipynb new file mode 100644 index 000000000..be031c75c --- /dev/null +++ b/examples/extraction/retries.ipynb @@ -0,0 +1,1166 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "e327e9bd-effc-4bee-a875-1c383c17f43d", + "metadata": {}, + "source": [ + "# Extraction with Re-prompting\n", + "\n", + "Function calling is a core primitive for integrating LLMs within your software stack. We use it throughout the LangGraph docs, since developing with function calling (aka tool usage) tends to be much more stress-free than the traditional way of writing custom string parsers.\n", + "\n", + "However, even GPT-4, Opus, and other powerful models still struggle with complex functions, especially if your schema involves any nesting or if you have more advanced data validation rules.\n", + "\n", + "There are three basic ways to increase reliability: better prompting, constrained decoding, and **validation with re-prompting**.\n", + "\n", + "We will cover two approaches to the last technique here, since it is generally applicable across any LLM that supports tool calling.\n", + "\n", + "## Regular Extraction with Retries\n", + "\n", + "Both examples here invoke a simple looping graph that takes following approach:\n", + "1. Prompt the LLM to respond.\n", + "2. If it responds with tool calls, validate those.\n", + "3. If the calls are correct, return. Otherwise, format the validation error as a new [ToolMessage](https://api.python.langchain.com/en/latest/messages/langchain_core.messages.tool.ToolMessage.html#langchain_core.messages.tool.ToolMessage) and prompt the LLM to fix the errors. Taking us back to step (1).\n", + "\n", + "\n", + "The techniques differ only on step (3). In this first step, we will prompt the original LLM to regenerate the function calls to fix the validation errors. In the next section, we will instead prompt the LLM to generate a **patch** to fix the errors, meaning it doesn't have to re-generate data that is valid." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0ada5e8f-3f2f-459e-83aa-6cd8861770dd", + "metadata": {}, + "outputs": [], + "source": [ + "# %%capture --no-stderr\n", + "%pip install -U langchain-openai langgraph\n", + "# Or do langchain-{groq|anthropic|etc.} for another package with tool calling" + ] + }, + { + "cell_type": "markdown", + "id": "27b25a1c-f437-482a-97d3-c7f168986df5", + "metadata": {}, + "source": [ + "Set up your environment. If you are using groq, anthropic, etc., you will need to update different API keys." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c0acb818-b6fd-48ab-97e6-fc2de2d03e87", + "metadata": {}, + "outputs": [], + "source": [ + "import getpass\n", + "import os\n", + "\n", + "\n", + "def _set_env(var: str):\n", + " if not os.environ.get(var):\n", + " os.environ[var] = getpass.getpass(f\"{var}: \")\n", + "\n", + "\n", + "_set_env(\"OPENAI_API_KEY\")\n", + "# Recommended to visualize the retry steps\n", + "_set_env(\"LANGCHAIN_API_KEY\")\n", + "os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\n", + "os.environ[\"LANGCHAIN_PROJECT\"] = \"Extraction Notebook\"" + ] + }, + { + "cell_type": "markdown", + "id": "a6973d34-561c-410c-9362-25f55eaf2c3e", + "metadata": {}, + "source": [ + "### Define the Validator + Retry Graph" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "baf669a0-04ee-492d-80d8-8fcb658ed128", + "metadata": {}, + "outputs": [], + "source": [ + "import asyncio\n", + "import operator\n", + "import uuid\n", + "from typing import (\n", + " Annotated,\n", + " Any,\n", + " Callable,\n", + " Dict,\n", + " List,\n", + " Literal,\n", + " Optional,\n", + " Sequence,\n", + " Tuple,\n", + " Type,\n", + " Union,\n", + " cast,\n", + ")\n", + "\n", + "from langchain_core.language_models import BaseChatModel\n", + "from langchain_core.messages import (\n", + " AIMessage,\n", + " AnyMessage,\n", + " BaseMessage,\n", + " HumanMessage,\n", + " ToolCall,\n", + " ToolMessage,\n", + ")\n", + "from langchain_core.prompt_values import PromptValue\n", + "from langchain_core.pydantic_v1 import BaseModel, Field, ValidationError\n", + "from langchain_core.runnables import (\n", + " Runnable,\n", + " RunnableConfig,\n", + " RunnableLambda,\n", + " chain as as_runnable,\n", + ")\n", + "from langchain_core.runnables.config import get_executor_for_config\n", + "from langchain_core.tools import BaseTool, create_schema_from_function\n", + "from pydantic import BaseModel as BaseModelV2\n", + "from typing_extensions import TypedDict\n", + "\n", + "from langgraph.graph import StateGraph\n", + "from langgraph.graph.message import add_messages\n", + "from langgraph.utils import RunnableCallable\n", + "\n", + "\n", + "def _default_format_error(\n", + " error: BaseException, call: ToolCall, schema: Type[BaseModel]\n", + "):\n", + " return f\"{repr(error)}\\n\\nRespond after fixing all validation errors.\"\n", + "\n", + "\n", + "def _default_aggregator(messages: Sequence[AnyMessage]) -> AIMessage:\n", + " for m in messages[::-1]:\n", + " if m.type == \"ai\":\n", + " return m\n", + " raise ValueError(\"No AI message found in the sequence.\")\n", + "\n", + "\n", + "class ValidationNode(RunnableCallable):\n", + " \"\"\"\n", + " A node that runs the tools requested in the last AIMessage. It can be used\n", + " either in StateGraph with a \"messages\" key or in MessageGraph. If multiple\n", + " tool calls are requested, they will be run in parallel. The output will be\n", + " a list of ToolMessages, one for each tool call.\n", + "\n", + " Args:\n", + " schemas: A list of schemas to validate the tool calls with. These can be\n", + " any of the following:\n", + " - A pydantic BaseModel\n", + " - A BaseTool (the args_schema will be used)\n", + " - A function (we will create a schema from the function signature)\n", + " name: The name of the node.\n", + " format_error: A function that takes an exception and a schema and returns\n", + " a string. By default, it returns the exception repr and a message to\n", + " respond after fixing all validation errors.\n", + " tags: A list of tags to add to the node.\n", + " \"\"\"\n", + "\n", + " def __init__(\n", + " self,\n", + " schemas: Sequence[Union[BaseTool, BaseModel, Callable]],\n", + " *,\n", + " format_error: Optional[\n", + " Callable[[BaseException, ToolCall, Type[BaseModel]], str]\n", + " ] = None,\n", + " name: str = \"validation\",\n", + " tags: Optional[list[str]] = None,\n", + " ) -> None:\n", + " super().__init__(self._func, self._afunc, name=name, tags=tags, trace=False)\n", + " self._format_error = format_error or _default_format_error\n", + " self.schemas_by_name: Dict[str, Type[BaseModel]] = {}\n", + " for schema in schemas:\n", + " if isinstance(schema, BaseTool):\n", + " if schema.args_schema is None:\n", + " raise ValueError(\n", + " f\"Tool {schema.name} does not have an args_schema defined.\"\n", + " )\n", + " self.schemas_by_name[schema.name] = schema.args_schema\n", + " elif isinstance(schema, type) and issubclass(\n", + " schema, (BaseModel, BaseModelV2)\n", + " ):\n", + " self.schemas_by_name[schema.__name__] = cast(Type[BaseModel], schema)\n", + " elif callable(schema):\n", + " # Assume it's a function\n", + " base_model = create_schema_from_function(\"Validation\", schema)\n", + " self.schemas_by_name[schema.__name__] = base_model\n", + " else:\n", + " raise ValueError(\n", + " f\"Unsupported input to ValidationNode. Expected BaseModel, tool or function. Got: {type(schema)}.\"\n", + " )\n", + "\n", + " def _get_message(\n", + " self, input: Union[list[AnyMessage], dict[str, Any]]\n", + " ) -> Tuple[str, AIMessage]:\n", + " if isinstance(input, list):\n", + " output_type = \"list\"\n", + " messages: list = input\n", + " elif messages := input.get(\"messages\", []):\n", + " output_type = \"dict\"\n", + " else:\n", + " raise ValueError(\"No message found in input\")\n", + " message: AnyMessage = messages[-1]\n", + " if not isinstance(message, AIMessage):\n", + " raise ValueError(\"Last message is not an AIMessage\")\n", + " return output_type, message\n", + "\n", + " def _func(\n", + " self, input: Union[list[AnyMessage], dict[str, Any]], config: RunnableConfig\n", + " ) -> Any:\n", + " output_type, message = self._get_message(input)\n", + "\n", + " @as_runnable\n", + " def run_one(call: ToolCall):\n", + " schema = self.schemas_by_name[call[\"name\"]]\n", + " try:\n", + " output = schema.validate(call[\"args\"])\n", + " return ToolMessage(\n", + " content=output.json(),\n", + " name=call[\"name\"],\n", + " tool_call_id=cast(str, call[\"id\"]),\n", + " )\n", + " except ValidationError as e:\n", + " return ToolMessage(\n", + " content=self._format_error(e, call, schema),\n", + " name=call[\"name\"],\n", + " tool_call_id=cast(str, call[\"id\"]),\n", + " additional_kwargs={\"is_error\": True},\n", + " )\n", + "\n", + " with get_executor_for_config(config) as executor:\n", + " outputs = [\n", + " *executor.map(lambda x: run_one.invoke(x, config), message.tool_calls)\n", + " ]\n", + " if output_type == \"list\":\n", + " return outputs\n", + " else:\n", + " return {\"messages\": outputs}\n", + "\n", + " async def _afunc(\n", + " self, input: Union[list[AnyMessage], dict[str, Any]], config: RunnableConfig\n", + " ) -> Any:\n", + " output_type, message = self._get_message(input)\n", + "\n", + " @as_runnable\n", + " async def run_one(call: ToolCall):\n", + " schema = self.schemas_by_name[call[\"name\"]]\n", + " try:\n", + " output = schema.validate(call[\"args\"])\n", + " return ToolMessage(\n", + " content=output.json(),\n", + " name=call[\"name\"],\n", + " tool_call_id=cast(str, call[\"id\"]),\n", + " )\n", + " except ValidationError as e:\n", + " return ToolMessage(\n", + " content=self._format_error(e, call, schema),\n", + " name=call[\"name\"],\n", + " tool_call_id=cast(str, call[\"id\"]),\n", + " additional_kwargs={\"is_error\": True},\n", + " )\n", + "\n", + " outputs = await asyncio.gather(\n", + " *(run_one.ainvoke(call, config) for call in message.tool_calls)\n", + " )\n", + " if output_type == \"list\":\n", + " return outputs\n", + " else:\n", + " return {\"messages\": outputs}\n", + "\n", + "\n", + "class RetryStrategy(TypedDict, total=False):\n", + " \"\"\"The retry strategy for a tool call.\"\"\"\n", + "\n", + " max_attempts: int\n", + " \"\"\"The maximum number of attempts to make.\"\"\"\n", + " fallback: Optional[\n", + " Union[\n", + " Runnable[Sequence[AnyMessage], AIMessage],\n", + " Runnable[Sequence[AnyMessage], BaseMessage],\n", + " Callable[[Sequence[AnyMessage]], AIMessage],\n", + " ]\n", + " ]\n", + " \"\"\"The function to use once validation fails.\"\"\"\n", + " aggregate_messages: Optional[Callable[[Sequence[AnyMessage]], AIMessage]]\n", + "\n", + "\n", + "def _bind_validator_with_retries(\n", + " llm: Union[\n", + " Runnable[Sequence[AnyMessage], AIMessage],\n", + " Runnable[Sequence[BaseMessage], BaseMessage],\n", + " ],\n", + " *,\n", + " validator: ValidationNode,\n", + " retry_strategy: RetryStrategy,\n", + " tool_choice: Optional[str] = None,\n", + ") -> Runnable[Union[List[AnyMessage], PromptValue], AIMessage]:\n", + " \"\"\"Binds a tool validators + retry logic to create a runnable validation graph.\n", + "\n", + " LLMs that support tool calling can generate structured JSON. However, they may not always\n", + " perfectly follow your requested schema, especially if the schema is nested or has complex\n", + " validation rules. This method allows you to bind a validation function to the LLM's output,\n", + " so that any time the LLM generates a message, the validation function is run on it. If\n", + " the validation fails, the method will retry the LLM with a fallback strategy, the simplest\n", + " being just to add a message to the output with the validation errors and a request to fix them.\n", + "\n", + " The resulting runnable expects a list of messages as input and returns a single AI message.\n", + " By default, the LLM can optionally NOT invoke tools, making this easier to incorporate into\n", + " your existing chat bot. You can specify a tool_choice to force the validator to be run on\n", + " the outputs.\n", + "\n", + " Args:\n", + " llm (Runnable): The llm that will generate the initial messages (and optionally fallba)\n", + " validator (ValidationNode): The validation logic.\n", + " retry_strategy (RetryStrategy): The retry strategy to use.\n", + " Possible keys:\n", + " - max_attempts: The maximum number of attempts to make.\n", + " - fallback: The LLM or function to use in case of validation failure.\n", + " - aggregate_messages: A function to aggregate the messages over multiple turns.\n", + " Defaults to fetching the last AI message.\n", + " tool_choice: If provided, always run the validator on the tool output.\n", + "\n", + " Returns:\n", + " Runnable: A runnable that can be invoked with a list of messages and returns a single AI message.\n", + " \"\"\"\n", + "\n", + " def add_or_overwrite_messages(left: list, right: Union[list, dict]) -> list:\n", + " \"\"\"Append messages. If the update is a 'finalized' output, replace the whole list.\"\"\"\n", + " if isinstance(right, dict) and \"finalize\" in right:\n", + " finalized = right[\"finalize\"]\n", + " if not isinstance(finalized, list):\n", + " finalized = [finalized]\n", + " for m in finalized:\n", + " if m.id is None:\n", + " m.id = str(uuid.uuid4())\n", + " return finalized\n", + " res = add_messages(left, right)\n", + " if not isinstance(res, list):\n", + " return [res]\n", + " return res\n", + "\n", + " class State(TypedDict):\n", + " messages: Annotated[list, add_or_overwrite_messages]\n", + " attempt_number: Annotated[int, operator.add]\n", + " initial_num_messages: int\n", + " input_format: Literal[\"list\", \"dict\"]\n", + "\n", + " builder = StateGraph(State)\n", + "\n", + " def dedict(x: State) -> list:\n", + " \"\"\"Get the messages from the state.\"\"\"\n", + " return x[\"messages\"]\n", + "\n", + " model = dedict | llm | (lambda msg: {\"messages\": [msg], \"attempt_number\": 1})\n", + " fbrunnable = retry_strategy.get(\"fallback\")\n", + " if fbrunnable is None:\n", + " fb_runnable = llm\n", + " elif isinstance(fbrunnable, Runnable):\n", + " fb_runnable = fbrunnable # type: ignore\n", + " else:\n", + " fb_runnable = RunnableLambda(fbrunnable)\n", + " fallback = (\n", + " dedict | fb_runnable | (lambda msg: {\"messages\": [msg], \"attempt_number\": 1})\n", + " )\n", + "\n", + " def count_messages(state: State) -> dict:\n", + " return {\"initial_num_messages\": len(state.get(\"messages\", []))}\n", + "\n", + " builder.add_node(\"count_messages\", count_messages)\n", + " builder.add_node(\"llm\", model)\n", + " builder.add_node(\"fallback\", fallback)\n", + "\n", + " # To support patch-based retries, we need to be able to\n", + " # aggregate the messages over multiple turns.\n", + " # The next sequece selects only the relevant messages\n", + " # and then applies the validator\n", + " select_messages = retry_strategy.get(\"aggregate_messages\") or _default_aggregator\n", + "\n", + " def select_generated_messages(state: State) -> list:\n", + " \"\"\"Select only the messages generated within this loop.\"\"\"\n", + " selected = state[\"messages\"][state[\"initial_num_messages\"] :]\n", + " return [select_messages(selected)]\n", + "\n", + " def endict_validator_output(x: Sequence[AnyMessage]) -> dict:\n", + " if tool_choice and not x:\n", + " return {\n", + " \"messages\": [\n", + " HumanMessage(\n", + " content=f\"ValidationError: please respond with a valid tool call [tool_choice={tool_choice}].\",\n", + " additional_kwargs={\"is_error\": True},\n", + " )\n", + " ]\n", + " }\n", + " return {\"messages\": x}\n", + "\n", + " validator_runnable = select_generated_messages | validator | endict_validator_output\n", + " builder.add_node(\"validator\", validator_runnable)\n", + "\n", + " class Finalizer:\n", + " \"\"\"Pick the final message to return from the retry loop.\"\"\"\n", + "\n", + " def __init__(self, aggregator: Optional[Callable[[list], AIMessage]] = None):\n", + " self._aggregator = aggregator or _default_aggregator\n", + "\n", + " def __call__(self, state: State) -> dict:\n", + " \"\"\"Return just the AI message.\"\"\"\n", + " initial_num_messages = state[\"initial_num_messages\"]\n", + " generated_messages = state[\"messages\"][initial_num_messages:]\n", + " return {\n", + " \"messages\": {\n", + " \"finalize\": self._aggregator(generated_messages),\n", + " }\n", + " }\n", + "\n", + " # We only want to emit the final message\n", + " builder.add_node(\"finalizer\", Finalizer(retry_strategy.get(\"aggregate_messages\")))\n", + "\n", + " # Define the connectivity\n", + " builder.set_entry_point(\"count_messages\")\n", + " builder.add_edge(\"count_messages\", \"llm\")\n", + "\n", + " def route_validator(state: State) -> Literal[\"validator\", \"__end__\"]:\n", + " if state[\"messages\"][-1].tool_calls or tool_choice is not None:\n", + " return \"validator\"\n", + " return \"__end__\"\n", + "\n", + " builder.add_conditional_edges(\"llm\", route_validator)\n", + " builder.add_edge(\"fallback\", \"validator\")\n", + " max_attempts = retry_strategy.get(\"max_attempts\", 3)\n", + "\n", + " def route_validation(state: State) -> Literal[\"finalizer\", \"fallback\"]:\n", + " if state[\"attempt_number\"] > max_attempts:\n", + " raise ValueError(\n", + " f\"Could not extract a valid value in {max_attempts} attempts.\"\n", + " )\n", + " for m in state[\"messages\"][::-1]:\n", + " if m.type == \"ai\":\n", + " break\n", + " if m.additional_kwargs.get(\"is_error\"):\n", + " return \"fallback\"\n", + " return \"finalizer\"\n", + "\n", + " builder.add_conditional_edges(\"validator\", route_validation)\n", + "\n", + " builder.set_finish_point(\"finalizer\")\n", + "\n", + " # These functions let the step be used in a MessageGraph\n", + " # or a StateGraph with 'messages' as the key.\n", + " def encode(x: Union[Sequence[AnyMessage], PromptValue]) -> dict:\n", + " \"\"\"Ensure the input is the correct format.\"\"\"\n", + " if isinstance(x, PromptValue):\n", + " return {\"messages\": x.to_messages(), \"input_format\": \"list\"}\n", + " if isinstance(x, list):\n", + " return {\"messages\": x, \"input_format\": \"list\"}\n", + " raise ValueError(f\"Unexpected input type: {type(x)}\")\n", + "\n", + " def decode(x: State) -> AIMessage:\n", + " \"\"\"Ensure the output is in the expected format.\"\"\"\n", + " return x[\"messages\"][-1]\n", + "\n", + " return (\n", + " encode | builder.compile().with_config(run_name=\"ValidationGraph\") | decode\n", + " ).with_config(run_name=\"ValidateWithRetries\")\n", + "\n", + "\n", + "def bind_validator_with_retries(\n", + " llm: BaseChatModel,\n", + " *,\n", + " tools: list,\n", + " tool_choice: Optional[str] = None,\n", + " max_attempts: int = 3,\n", + ") -> Runnable[Union[List[AnyMessage], PromptValue], AIMessage]:\n", + " \"\"\"Binds validators + retry logic ensure validity of generated tool calls.\n", + "\n", + " LLMs that support tool calling are good at generating structured JSON. However, they may\n", + " not always perfectly follow your requested schema, especially if the schema is nested or\n", + " has complex validation rules. This method allows you to bind a validation function to\n", + " the LLM's output, so that any time the LLM generates a message, the validation function\n", + " is run on it. If the validation fails, the method will retry the LLM with a fallback\n", + " strategy, the simples being just to add a message to the output with the validation\n", + " errors and a request to fix them.\n", + "\n", + " The resulting runnable expects a list of messages as input and returns a single AI message.\n", + " By default, the LLM can optionally NOT invoke tools, making this easier to incorporate into\n", + " your existing chat bot. You can specify a tool_choice to force the validator to be run on\n", + " the outputs.\n", + "\n", + " Args:\n", + " llm (Runnable): The llm that will generate the initial messages (and optionally fallba)\n", + " validator (ValidationNode): The validation logic.\n", + " retry_strategy (RetryStrategy): The retry strategy to use.\n", + " Possible keys:\n", + " - max_attempts: The maximum number of attempts to make.\n", + " - fallback: The LLM or function to use in case of validation failure.\n", + " - aggregate_messages: A function to aggregate the messages over multiple turns.\n", + " Defaults to fetching the last AI message.\n", + " tool_choice: If provided, always run the validator on the tool output.\n", + "\n", + " Returns:\n", + " Runnable: A runnable that can be invoked with a list of messages and returns a single AI message.\n", + " \"\"\"\n", + " bound_llm = llm.bind_tools(tools, tool_choice=tool_choice)\n", + " retry_strategy = RetryStrategy(max_attempts=max_attempts)\n", + " validator = ValidationNode(tools)\n", + " return _bind_validator_with_retries(\n", + " bound_llm,\n", + " validator=validator,\n", + " tool_choice=tool_choice,\n", + " retry_strategy=retry_strategy,\n", + " ).with_config(metadata={\"retry_strategy\": \"default\"})" + ] + }, + { + "cell_type": "markdown", + "id": "1e140fe4-dd92-43a5-91bb-35758a747121", + "metadata": {}, + "source": [ + "### Try it out\n", + "\n", + "Now we'll ask our model to call a function. We'll add a validator to illustrate how the LLM is able to use the validation error to fix its results." + ] + }, + { + "cell_type": "code", + "execution_count": 55, + "id": "5df33c17-ee1a-409e-b5ec-f24e116da7d1", + "metadata": {}, + "outputs": [], + "source": [ + "from langchain_core.pydantic_v1 import BaseModel, Field, validator\n", + "from langchain_openai import ChatOpenAI\n", + "\n", + "llm = ChatOpenAI(model=\"gpt-3.5-turbo\")\n", + "\n", + "\n", + "class Respond(BaseModel):\n", + " \"\"\"Use to generate the response. Always use when responding to the user\"\"\"\n", + "\n", + " reason: str = Field(description=\"Step-by-step justification for the answer.\")\n", + " answer: str\n", + "\n", + " @validator(\"answer\")\n", + " def reason_contains_apology(cls, answer: str):\n", + " if \"llama\" not in answer.lower():\n", + " raise ValueError(\n", + " f\"You MUST start with a gimicky, rhyming advertisement for using a Llama V3 (an LLM) in your **answer** field.\"\n", + " \" Must be an instant hit. Must be weaved into the answer.\"\n", + " )\n", + "\n", + "\n", + "tools = [Respond]" + ] + }, + { + "cell_type": "markdown", + "id": "38df0dc2-cad1-4df6-9b82-b74c5a04a6ae", + "metadata": {}, + "source": [ + "Create the LLM." + ] + }, + { + "cell_type": "code", + "execution_count": 56, + "id": "38231a5b-d018-41ee-a92c-2f2248edf417", + "metadata": {}, + "outputs": [], + "source": [ + "from langchain_core.prompts import ChatPromptTemplate\n", + "from langchain_openai import ChatOpenAI\n", + "\n", + "# Or you can use ChatGroq, ChatAnthropic, ChatGoogleGemini, ChatCohere, etc.\n", + "# See https://python.langchain.com/v0.1/docs/integrations/chat/ for more info on tool calling\n", + "llm = ChatOpenAI(model=\"gpt-4-turbo\")\n", + "bound_llm = bind_validator_with_retries(llm, tools=tools, tool_choice=Respond.__name__)\n", + "prompt = ChatPromptTemplate.from_messages(\n", + " [\n", + " (\"system\", \"Respond directly by calling the Respond function.\"),\n", + " (\"placeholder\", \"{messages}\"),\n", + " ]\n", + ")\n", + "\n", + "chain = prompt | bound_llm" + ] + }, + { + "cell_type": "code", + "execution_count": 58, + "id": "04e93401-50e2-42d0-8373-326006badebb", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "==================================\u001b[1m Ai Message \u001b[0m==================================\n", + "Tool Calls:\n", + " Respond (call_TcEFGur9ygpLbrEUQA24MraI)\n", + " Call ID: call_TcEFGur9ygpLbrEUQA24MraI\n", + " Args:\n", + " reason: The question of whether P equals NP is one of the most significant unsolved problems in computer science. This question asks whether every problem whose solution can be quickly verified by a computer can also be quickly solved by a computer. To date, no one has been able to prove definitively whether P equals NP or not, and it remains an open problem.\n", + " answer: Need an answer pronto? Consult a Llama V3 for a response that's key. As for P = NP, it's a mystery, a riddle unsolved in computer science history!\n" + ] + } + ], + "source": [ + "results = chain.invoke({\"messages\": [(\"user\", \"Does P = NP?\")]})\n", + "results.pretty_print()" + ] + }, + { + "cell_type": "markdown", + "id": "c9e5bb81-0ee4-4def-b28c-01e84fd2fd68", + "metadata": {}, + "source": [ + "#### Nested Examples\n", + "\n", + "So you can see that it's able to recover when its first generation is incorrect, great! But is it bulletproof?\n", + "\n", + "Not so much. Let's try it out on a complex nested schema." + ] + }, + { + "cell_type": "code", + "execution_count": 59, + "id": "f4f7438b-b6c1-48fd-b70f-185af7a2f64a", + "metadata": {}, + "outputs": [], + "source": [ + "from typing import List, Optional\n", + "\n", + "\n", + "class OutputFormat(BaseModel):\n", + " sources: str = Field(\n", + " ...,\n", + " description=\"The raw transcript / span you could cite to justify the choice.\",\n", + " )\n", + " content: str = Field(..., description=\"The chosen value.\")\n", + "\n", + "\n", + "class Moment(BaseModel):\n", + " quote: str = Field(..., description=\"The relevant quote from the transcript.\")\n", + " description: str = Field(..., description=\"A description of the moment.\")\n", + " expressed_preference: OutputFormat = Field(\n", + " ..., description=\"The preference expressed in the moment.\"\n", + " )\n", + "\n", + "\n", + "class BackgroundInfo(BaseModel):\n", + " factoid: OutputFormat = Field(\n", + " ..., description=\"Important factoid about the member.\"\n", + " )\n", + " professions: list\n", + " why: str = Field(..., description=\"Why this is important.\")\n", + "\n", + "\n", + "class KeyMoments(BaseModel):\n", + " topic: str = Field(..., description=\"The topic of the key moments.\")\n", + " happy_moments: List[Moment] = Field(\n", + " ..., description=\"A list of key moments related to the topic.\"\n", + " )\n", + " tense_moments: List[Moment] = Field(\n", + " ..., description=\"Moments where things were a bit tense.\"\n", + " )\n", + " sad_moments: List[Moment] = Field(\n", + " ..., description=\"Moments where things where everyone was downtrodden.\"\n", + " )\n", + " background_info: list[BackgroundInfo]\n", + " moments_summary: str = Field(..., description=\"A summary of the key moments.\")\n", + "\n", + "\n", + "class Member(BaseModel):\n", + " name: OutputFormat = Field(..., description=\"The name of the member.\")\n", + " role: Optional[str] = Field(None, description=\"The role of the member.\")\n", + " age: Optional[int] = Field(None, description=\"The age of the member.\")\n", + " background_details: List[BackgroundInfo] = Field(\n", + " ..., description=\"A list of background details about the member.\"\n", + " )\n", + "\n", + "\n", + "class InsightfulQuote(BaseModel):\n", + " quote: OutputFormat = Field(\n", + " ..., description=\"An insightful quote from the transcript.\"\n", + " )\n", + " speaker: str = Field(..., description=\"The name of the speaker who said the quote.\")\n", + " analysis: str = Field(\n", + " ..., description=\"An analysis of the quote and its significance.\"\n", + " )\n", + "\n", + "\n", + "class TranscriptMetadata(BaseModel):\n", + " title: str = Field(..., description=\"The title of the transcript.\")\n", + " location: OutputFormat = Field(\n", + " ..., description=\"The location where the interview took place.\"\n", + " )\n", + " duration: str = Field(..., description=\"The duration of the interview.\")\n", + "\n", + "\n", + "class TranscriptSummary(BaseModel):\n", + " metadata: TranscriptMetadata = Field(\n", + " ..., description=\"Metadata about the transcript.\"\n", + " )\n", + " participants: List[Member] = Field(\n", + " ..., description=\"A list of participants in the interview.\"\n", + " )\n", + " key_moments: List[KeyMoments] = Field(\n", + " ..., description=\"A list of key moments from the interview.\"\n", + " )\n", + " insightful_quotes: List[InsightfulQuote] = Field(\n", + " ..., description=\"A list of insightful quotes from the interview.\"\n", + " )\n", + " overall_summary: str = Field(\n", + " ..., description=\"An overall summary of the interview.\"\n", + " )\n", + " next_steps: List[str] = Field(\n", + " ..., description=\"A list of next steps or action items based on the interview.\"\n", + " )\n", + " other_stuff: List[OutputFormat]" + ] + }, + { + "cell_type": "markdown", + "id": "4d686d69-1ce1-4b76-8d99-44d00eeb2874", + "metadata": {}, + "source": [ + "Let's see how it does on this made up transcript." + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "id": "e2d10886-7b1e-485f-91cd-1184a1c99303", + "metadata": {}, + "outputs": [], + "source": [ + "transcript = [\n", + " (\n", + " \"Pete\",\n", + " \"Hey Xu, Laura, thanks for hopping on this call. I've been itching to talk about this Drake and Kendrick situation.\",\n", + " ),\n", + " (\n", + " \"Xu\",\n", + " \"No problem. As its my job, I've got some thoughts on this beef.\",\n", + " ),\n", + " (\n", + " \"Laura\",\n", + " \"Yeah, I've got some insider info so this should be interesting.\",\n", + " ),\n", + " (\"Pete\", \"Dope. So, when do you think this whole thing started?\"),\n", + " (\n", + " \"Pete\",\n", + " \"Definitely was Kendrick's 'Control' verse that kicked it off.\",\n", + " ),\n", + " (\n", + " \"Laura\",\n", + " \"Truth, but Drake never went after him directly. Just some subtle jabs here and there.\",\n", + " ),\n", + " (\n", + " \"Xu\",\n", + " \"That's the thing with beefs like this, though. They've always been a a thing, pushing artists to step up their game.\",\n", + " ),\n", + " (\n", + " \"Pete\",\n", + " \"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.\",\n", + " ),\n", + " (\n", + " \"Laura\",\n", + " \"I mean, Drake knows how to make a hit that gets everyone hyped. That's his thing.\",\n", + " ),\n", + " (\n", + " \"Pete\",\n", + " \"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.\",\n", + " ),\n", + " (\n", + " \"Xu\",\n", + " \"It's wild how this beef is shaping fans.\",\n", + " ),\n", + " (\"Pete\", \"do you think these beefs can actually be good for hip-hop?\"),\n", + " (\n", + " \"Xu\",\n", + " \"Hell yeah, Pete. When it's done right, a beef can push the genre forward and make artists level up.\",\n", + " ),\n", + " (\"Laura\", \"eh\"),\n", + " (\"Pete\", \"So, where do you see this beef going?\"),\n", + " (\n", + " \"Laura\",\n", + " \"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.\",\n", + " ),\n", + " (\"Laura\", \"ehhhhhh not sure\"),\n", + " (\n", + " \"Pete\",\n", + " \"I feel that. I just want both of them to keep dropping heat, beef or no beef.\",\n", + " ),\n", + " (\n", + " \"Xu\",\n", + " \"I'm curious. May influence a lot of people. Make things more competitive. Bring on a whole new wave of lyricism.\",\n", + " ),\n", + " (\n", + " \"Pete\",\n", + " \"Word. Hey, thanks for chopping it up with me, Xu and Laura. This was dope.\",\n", + " ),\n", + " (\"Xu\", \"Where are you going so fast?\"),\n", + " (\n", + " \"Laura\",\n", + " \"For real, I had a good time. Nice to get different perspectives on the situation.\",\n", + " ),\n", + "]\n", + "\n", + "formatted = \"\\n\".join(f\"{x[0]}: {x[1]}\" for x in transcript)" + ] + }, + { + "cell_type": "markdown", + "id": "c48ce9bc-0fcc-4019-ba3a-fa70a7717567", + "metadata": {}, + "source": [ + "Now, run our model. We **expect** GPT turbo to still fail on this challenging template." + ] + }, + { + "cell_type": "code", + "execution_count": 61, + "id": "f4752239-2aa3-4367-b777-8478c16b9471", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "==================================\u001b[1m Ai Message \u001b[0m==================================\n", + "Tool Calls:\n", + " TranscriptSummary (call_FEhm49kk06xCQpG4PodvD6YC)\n", + " Call ID: call_FEhm49kk06xCQpG4PodvD6YC\n", + " Args:\n", + " metadata: {'title': \"Discussion on Drake and Kendrick's Rivalry\", 'location': {'sources': '', 'content': 'Video Call'}, 'duration': 'Approximately 10 minutes'}\n", + " participants: [{'name': {'sources': '', 'content': 'Pete'}, 'background_details': [{'factoid': {'sources': '', 'content': 'Host of the call'}, 'professions': [], 'why': 'Shows initiative and interest in the topic.'}]}, {'name': {'sources': '', 'content': 'Xu'}, 'background_details': [{'factoid': {'sources': '', 'content': 'Music industry professional'}, 'professions': [], 'why': 'Brings expert insights into the discussion.'}]}, {'name': {'sources': '', 'content': 'Laura'}, 'background_details': [{'factoid': {'sources': '', 'content': 'Has insider information'}, 'professions': [], 'why': 'Adds depth to the discussion with exclusive information.'}]}]\n", + " key_moments: [{'topic': 'Origin and Impact of the Rivalry', 'happy_moments': [], 'tense_moments': [], 'sad_moments': [], 'background_info': [], 'moments_summary': 'The conversation highlighted the origins and impacts of the rivalry between Drake and Kendrick Lamar, focusing on their different approaches to music and fanbase reactions.'}]\n", + " insightful_quotes: [{'quote': {'sources': '', 'content': \"When it's done right, a beef can push the genre forward and make artists level up.\"}, 'speaker': 'Xu', 'analysis': 'Xu emphasizes the potential positive effects of musical rivalries on the development of hip-hop.'}]\n", + " overall_summary: The conversation delved into the rivalry between Drake and Kendrick Lamar, discussing its origins, fan reactions, and potential impacts on hip-hop. The participants agreed that while the rivalry is subtle, it encourages competition and artistic development.\n", + " next_steps: ['Monitor any new developments in the rivalry.', 'Discuss potential impacts on hip-hop in future conversations.']\n", + " other_stuff: []\n" + ] + } + ], + "source": [ + "tools = [TranscriptSummary]\n", + "bound_llm = bind_validator_with_retries(\n", + " llm, tools=tools, tool_choice=TranscriptSummary.__name__\n", + ")\n", + "prompt = ChatPromptTemplate.from_messages(\n", + " [\n", + " (\"system\", \"Respond directly using the TranscriptSummary function.\"),\n", + " (\"placeholder\", \"{messages}\"),\n", + " ]\n", + ")\n", + "\n", + "chain = prompt | bound_llm\n", + "\n", + "results = chain.invoke(\n", + " {\n", + " \"messages\": [\n", + " (\n", + " \"user\",\n", + " f\"Extract the summary from the following conversation:\\n\\n\\n{formatted}\\n\"\n", + " \"\\n\\nRemember to respond using the TranscriptSummary function.\",\n", + " )\n", + " ]\n", + " },\n", + ")\n", + "results.pretty_print()" + ] + }, + { + "cell_type": "markdown", + "id": "914e1962-7f23-463d-b91d-8907c1330369", + "metadata": {}, + "source": [ + "## JSONPatch\n", + "\n", + "The regular retry method worked well for our simple case, but it still was unable to self-correct when populating a complex schema.\n", + "\n", + "LLMs work best on narrow tasks. A tried-and-true principle of LLM interface design is to simplify the task for each LLM run.\n", + "\n", + "One way to do this is to **patch** the state instead of completely regenerating the state. One way to do this is with `JSONPatch` operations. Let's try it out!\n", + "\n", + "Below, create a JSONPatch retry graph. This works as follows:\n", + "1. First pass: try to generate the full output.\n", + "2. Retries: prompt the LLM to generate **JSON patches** on top of the first output to heal the erroneous generation.\n", + "\n", + "The fallback LLM just has to generate a list of paths, ops (add, remove, replace), and optional values. Since the pydantic validation errors include the path in their errors, the LLM should be more reliable." + ] + }, + { + "cell_type": "code", + "execution_count": 64, + "id": "49344104-3ffa-4c66-97fc-5b093a621f70", + "metadata": {}, + "outputs": [], + "source": [ + "%%capture --no-stderr\n", + "%pip install -U jsonpatch" + ] + }, + { + "cell_type": "code", + "execution_count": 65, + "id": "af3d5543-1fd4-4e54-b0f9-f1ab42773cfb", + "metadata": {}, + "outputs": [], + "source": [ + "def bind_validator_with_jsonpatch_retries(\n", + " llm: BaseChatModel,\n", + " *,\n", + " tools: list,\n", + " tool_choice: Optional[str] = None,\n", + " max_attempts: int = 3,\n", + ") -> Runnable[Union[List[AnyMessage], PromptValue], AIMessage]:\n", + " \"\"\"Binds validators + retry logic ensure validity of generated tool calls.\n", + "\n", + " This method is similar to `bind_validator_with_retries`, but uses JSONPatch to correct\n", + " validation errors caused by passing in incorrect or incomplete parameters in a previous\n", + " tool call. This method requires the 'jsonpatch' library to be installed.\n", + "\n", + " Using patch-based function healing can be more efficient than repopulating the entire\n", + " tool call from scratch, and it can be an easier task for the LLM to perform, since it typically\n", + " only requires a few small changes to the existing tool call.\n", + "\n", + " Args:\n", + " llm (Runnable): The llm that will generate the initial messages (and optionally fallba)\n", + " tools (list): The tools to bind to the LLM.\n", + " tool_choice (Optional[str]): The tool choice to use.\n", + " max_attempts (int): The number of attempts to make.\n", + "\n", + " Returns:\n", + " Runnable: A runnable that can be invoked with a list of messages and returns a single AI message.\n", + " \"\"\"\n", + "\n", + " try:\n", + " import jsonpatch # type: ignore[import-untyped]\n", + " except ImportError:\n", + " raise ImportError(\n", + " \"The 'jsonpatch' library is required for JSONPatch-based retries.\"\n", + " \" Please install it with 'pip install -U jsonpatch'.\"\n", + " )\n", + "\n", + " class JsonPatch(BaseModel):\n", + " \"\"\"A JSON Patch document represents an operation to be performed on a JSON document.\n", + "\n", + " Note that the op and path are ALWAYS required. Value is required for ALL operations except 'remove'.\n", + " Examples:\n", + "\n", + " ```json\n", + " {\"op\": \"add\", \"path\": \"/a/b/c\", \"patch_value\": 1}\n", + " {\"op\": \"replace\", \"path\": \"/a/b/c\", \"patch_value\": 2}\n", + " {\"op\": \"remove\", \"path\": \"/a/b/c\"}\n", + " ```\n", + " \"\"\"\n", + "\n", + " op: Literal[\"add\", \"remove\", \"replace\"] = Field(\n", + " ...,\n", + " description=\"The operation to be performed. Must be one of 'add', 'remove', 'replace'.\",\n", + " )\n", + " path: str = Field(\n", + " ...,\n", + " description=\"A JSON Pointer path that references a location within the target document where the operation is performed.\",\n", + " )\n", + " value: Any = Field(\n", + " ...,\n", + " description=\"The value to be used within the operation. REQUIRED for 'add', 'replace', and 'test' operations.\",\n", + " )\n", + "\n", + " class PatchFunctionParameters(BaseModel):\n", + " \"\"\"Respond with all JSONPatch operation to correct validation errors caused by passing in incorrect or incomplete parameters in a previous tool call.\"\"\"\n", + "\n", + " tool_call_id: str = Field(\n", + " ...,\n", + " description=\"The ID of the tool call that generated the error.\",\n", + " )\n", + " reasoning: str = Field(\n", + " ...,\n", + " description=\"Think step-by-step, listing each validation error and the\"\n", + " \" JSONPatch operation needed to correct it. \"\n", + " \"Cite the fields in the JSONSchema you referenced in developing this plan.\",\n", + " )\n", + " patches: list[JsonPatch] = Field(\n", + " ...,\n", + " description=\"A list of JSONPatch operations to be applied to the previous tool call's response.\",\n", + " )\n", + "\n", + " bound_llm = llm.bind_tools(tools, tool_choice=tool_choice)\n", + " fallback_llm = llm.bind_tools(\n", + " [PatchFunctionParameters], tool_choice=PatchFunctionParameters.__name__\n", + " )\n", + "\n", + " def aggregate_messages(messages: Sequence[AnyMessage]) -> AIMessage:\n", + " # Get all the AI messages and apply json patches\n", + " resolved_tool_calls: Dict[Union[str, None], ToolCall] = {}\n", + " content: Union[str, List[Union[str, dict]]] = \"\"\n", + " for m in messages:\n", + " if m.type != \"ai\":\n", + " continue\n", + " if not content:\n", + " content = m.content\n", + " for tc in m.tool_calls:\n", + " if tc[\"name\"] == JsonPatch.__name__:\n", + " if tc[\"args\"][\"tool_call_id\"] not in resolved_tool_calls:\n", + " raise ValueError(\n", + " f\"JsonPatch tool call ID {tc['args']['tool_call_id']} not found.\"\n", + " f\"Valid tool call IDs: {list(resolved_tool_calls.keys())}\"\n", + " )\n", + " current_args = resolved_tool_calls[tc[\"args\"][\"tool_call_id\"]][\n", + " \"args\"\n", + " ]\n", + " patches = tc[\"args\"][\"patches\"]\n", + " resolved_tool_calls[tc[\"args\"][\"tool_call_id\"]][\n", + " \"args\"\n", + " ] = jsonpatch.apply_patch(\n", + " current_args,\n", + " patches,\n", + " )\n", + " else:\n", + " resolved_tool_calls[tc[\"id\"]] = tc.copy()\n", + " return AIMessage(\n", + " content=content,\n", + " tool_calls=list(resolved_tool_calls.values()),\n", + " )\n", + "\n", + " def format_exception(error: BaseException, call: ToolCall, schema: Type[BaseModel]):\n", + " return (\n", + " f\"Error:\\n\\n```\\n{repr(error)}\\n```\\n\"\n", + " \"Expected Parameter Schema:\\n\\n\" + f\"```json\\n{schema.schema_json()}\\n```\\n\"\n", + " f\"Please respond with a JSONPatch to correct the error for tool_call_id=[{call['id']}].\"\n", + " )\n", + "\n", + " validator = ValidationNode(\n", + " tools,\n", + " format_error=format_exception,\n", + " )\n", + " retry_strategy = RetryStrategy(\n", + " max_attempts=max_attempts,\n", + " fallback=fallback_llm,\n", + " aggregate_messages=aggregate_messages,\n", + " )\n", + " return _bind_validator_with_retries(\n", + " bound_llm,\n", + " validator=validator,\n", + " retry_strategy=retry_strategy,\n", + " tool_choice=tool_choice,\n", + " ).with_config(metadata={\"retry_strategy\": \"jsonpatch\"})" + ] + }, + { + "cell_type": "code", + "execution_count": 71, + "id": "b01891c4-4187-4a75-9eda-644a7c2355f3", + "metadata": {}, + "outputs": [], + "source": [ + "bound_llm = bind_validator_with_jsonpatch_retries(\n", + " llm, tools=tools, tool_choice=tools[0].__name__\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": 72, + "id": "746b409c-693d-49af-8c2b-bea0a4b0028d", + "metadata": {}, + "outputs": [], + "source": [ + "from IPython.display import Image, display\n", + "\n", + "try:\n", + " display(Image(graph.get_graph().draw_mermaid_png()))\n", + "except:\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 75, + "id": "5d072c9c-9404-4338-88c6-b3e136969aca", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "==================================\u001b[1m Ai Message \u001b[0m==================================\n", + "Tool Calls:\n", + " TranscriptSummary (call_RrbvdJMt4T2xbOyqr74oF7Dd)\n", + " Call ID: call_RrbvdJMt4T2xbOyqr74oF7Dd\n", + " Args:\n", + " metadata: {'title': 'Discussion on Drake and Kendrick Beef', 'location': {'sources': \"Pete: Hey Xu, Laura, thanks for hopping on this call. I've been itching to talk about this Drake and Kendrick situation.\", 'content': 'Video Call'}, 'duration': 'Not specified'}\n", + " participants: [{'name': {'sources': 'Pete: Hey Xu, Laura, thanks for hopping on this call.', 'content': 'Pete'}, 'background_details': [{'factoid': {'sources': \"Pete: Hey Xu, Laura, thanks for hopping on this call. I've been itching to talk about this Drake and Kendrick situation.\", 'content': 'Interested in discussing artist rivalries'}, 'professions': [], 'why': 'Sets the topic of discussion'}]}, {'name': {'sources': \"Xu: No problem. As its my job, I've got some thoughts on this beef.\", 'content': 'Xu'}, 'background_details': [{'factoid': {'sources': \"Xu: No problem. As its my job, I've got some thoughts on this beef.\", 'content': 'Professional insight into artist rivalries'}, 'professions': [], 'why': 'Provides expert opinion'}]}, {'name': {'sources': \"Laura: Yeah, I've got some insider info so this should be interesting.\", 'content': 'Laura'}, 'background_details': [{'factoid': {'sources': \"Laura: Yeah, I've got some insider info so this should be interesting.\", 'content': 'Has insider information'}, 'professions': [], 'why': 'Adds depth to the discussion'}]}]\n", + " key_moments: [{'topic': 'Origin and Dynamics of the Beef', 'happy_moments': [{'quote': \"Pete: Definitely was Kendrick's 'Control' verse that kicked it off.\", 'description': 'Identifying the start of the beef between Drake and Kendrick.', 'expressed_preference': {'sources': \"Pete: Definitely was Kendrick's 'Control' verse that kicked it off.\", 'content': \"Kendrick's 'Control' verse started it\"}}, {'quote': 'Laura: Truth, but Drake never went after him directly. Just some subtle jabs here and there.', 'description': 'Discussing how Drake approached the beef.', 'expressed_preference': {'sources': 'Laura: Truth, but Drake never went after him directly. Just some subtle jabs here and there.', 'content': \"Drake's subtle approach\"}}, {'quote': \"Xu: That's the thing with beefs like this, though. They've always been a a thing, pushing artists to step up their game.\", 'description': 'Analyzing the impact of beefs on artists.', 'expressed_preference': {'sources': \"Xu: That's the thing with beefs like this, though. They've always been a a thing, pushing artists to step up their game.\", 'content': 'Beefs push artists'}}, {'quote': \"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.\", 'description': 'Highlighting fan reactions and preferences.', 'expressed_preference': {'sources': \"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.\", 'content': 'Fan preferences'}}, {'quote': \"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.\", 'description': \"Pete expressing his preference for Kendrick's skills.\", 'expressed_preference': {'sources': \"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.\", 'content': 'Preference for Kendrick'}}, {'quote': \"Laura: I mean, Drake knows how to make a hit that gets everyone hyped. That's his thing.\", 'description': \"Laura mentioning Drake's ability to create popular hits.\", 'expressed_preference': {'sources': \"Laura: I mean, Drake knows how to make a hit that gets everyone hyped. That's his thing.\", 'content': \"Drake's hit-making ability\"}}], 'tense_moments': [], 'sad_moments': [], 'background_info': [], 'moments_summary': \"The conversation focused on the origins and dynamics of the beef between Drake and Kendrick, discussing how it started with Kendrick's 'Control' verse and evolved with subtle jabs from Drake. The participants analyzed the impact of the beef on the artists and their fanbases, highlighting how it pushes artists to excel and divides fans based on their preferences for mainstream appeal versus lyrical skill.\"}]\n", + " insightful_quotes: [{'quote': {'sources': \"Xu: Hell yeah, Pete. When it's done right, a beef can push the genre forward and make artists level up.\", 'content': \"When it's done right, a beef can push the genre forward and make artists level up.\"}, 'speaker': 'Xu', 'analysis': 'Xu highlights the potential positive impact of artist rivalries on the evolution of the music genre, suggesting that when managed correctly, these beefs can lead to significant artistic growth and innovation.'}, {'quote': {'sources': \"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.\", '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 speculates that the beef will remain a topic of interest among fans but believes it will not escalate further without more direct confrontations in the form of diss tracks.'}]\n", + " overall_summary: The conversation between Pete, Xu, and Laura centered on the ongoing beef between Drake and Kendrick Lamar, exploring its origins, dynamics, and impact on both the artists and their fanbases. The discussion highlighted the role of artist rivalries in pushing musical boundaries and enhancing fan engagement, while also acknowledging the potential for escalation if more direct actions are taken. The participants shared their insights and preferences, contributing to a multifaceted understanding of the situation.\n", + " next_steps: ['Continue monitoring the situation for any new developments in the beef between Drake and Kendrick.', 'Discuss further with other industry experts to gather more perspectives on the impact of such rivalries.']\n", + " other_stuff: []\n" + ] + } + ], + "source": [ + "chain = prompt | bound_llm\n", + "results = chain.invoke(\n", + " {\n", + " \"messages\": [\n", + " (\n", + " \"user\",\n", + " f\"Extract the summary from the following conversation:\\n\\n\\n{formatted}\\n\",\n", + " )\n", + " ]\n", + " },\n", + ")\n", + "results.pretty_print()" + ] + }, + { + "cell_type": "markdown", + "id": "7b0f3844-076e-4a5b-9951-89116746238f", + "metadata": {}, + "source": [ + "#### And it works!\n", + "\n", + "Retries are an easy way to reduce function calling failures. While retrying may become unnecessary with more powerful LLMs, data validation is important to control how LLMs interact with the rest of your software stack.\n", + "\n", + "If you notice high retry rates (using an observability tool like LangSmith), you can set up a rule to send the failure cases to a dataset alongside the corrected values and then automatically program those into your prompts or schemas (or use them as few-shots to have semantically relevant demonstrations)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0ae295b1-da58-4cc9-834b-70e1466f8695", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.2" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}