mirror of
https://github.com/hwchase17/langchain.git
synced 2025-05-17 21:11:40 +00:00
579 lines
19 KiB
Plaintext
579 lines
19 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "54ccb772",
|
|
"metadata": {},
|
|
"source": [
|
|
"# Using OpenAI functions\n",
|
|
"This walkthrough demonstrates how to incorporate OpenAI function-calling API's in a chain. We'll go over: \n",
|
|
"1. How to use functions to get structured outputs from ChatOpenAI\n",
|
|
"2. How to create a generic chain that uses (multiple) functions\n",
|
|
"3. How to create a chain that actually executes the chosen function"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 1,
|
|
"id": "767ac575",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from typing import Optional\n",
|
|
"\n",
|
|
"from langchain.chains.openai_functions import (\n",
|
|
" create_openai_fn_chain, create_structured_output_chain\n",
|
|
")\n",
|
|
"from langchain.prompts import ChatPromptTemplate"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "976b6496",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Getting structured outputs\n",
|
|
"We can take advantage of OpenAI functions to try and force the model to return a particular kind of structured output. We'll use the `create_structured_output_chain` to create our chain, which takes the desired structured output either as a Pydantic object or as JsonSchema.\n",
|
|
"\n",
|
|
"See here for relevant [reference docs](https://api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.base.create_structured_output_chain.html)."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "e052faae",
|
|
"metadata": {},
|
|
"source": [
|
|
"### Using Pydantic objects\n",
|
|
"When passing in Pydantic objects to structure our text, we need to make sure to have a docstring description for the class. It also helps to have descriptions for each of the object attributes."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 2,
|
|
"id": "b459a33e",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"\n",
|
|
"\n",
|
|
"\u001b[1m> Entering new chain...\u001b[0m\n",
|
|
"Prompt after formatting:\n",
|
|
"\u001b[32;1m\u001b[1;3mHuman: Sally is 13\u001b[0m\n",
|
|
"\n",
|
|
"\u001b[1m> Finished chain.\u001b[0m\n"
|
|
]
|
|
},
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"{'name': 'Sally', 'age': 13}"
|
|
]
|
|
},
|
|
"execution_count": 2,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"from pydantic import BaseModel, Field\n",
|
|
"\n",
|
|
"class Person(BaseModel):\n",
|
|
" \"\"\"Identifying information about a person.\"\"\"\n",
|
|
" name: str = Field(..., description=\"The person's name\")\n",
|
|
" age: int = Field(..., description=\"The person's age\")\n",
|
|
" fav_food: Optional[str] = Field(None, description=\"The person's favorite food\")\n",
|
|
" \n",
|
|
"chain = create_structured_output_chain(Person, verbose=True)\n",
|
|
"chain.run(\"Sally is 13\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "e3539936",
|
|
"metadata": {},
|
|
"source": [
|
|
"To extract arbitrarily many structured outputs of a given format, we can just create a wrapper Pydantic object that takes a sequence of the original object."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 3,
|
|
"id": "4d8ea815",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"\n",
|
|
"\n",
|
|
"\u001b[1m> Entering new chain...\u001b[0m\n",
|
|
"Prompt after formatting:\n",
|
|
"\u001b[32;1m\u001b[1;3mHuman: Sally is 13, Joey just turned 12 and loves spinach. Caroline is 10 years older than Sally, so she's 23.\u001b[0m\n",
|
|
"\n",
|
|
"\u001b[1m> Finished chain.\u001b[0m\n"
|
|
]
|
|
},
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"{'people': [{'name': 'Sally', 'age': 13, 'fav_food': ''},\n",
|
|
" {'name': 'Joey', 'age': 12, 'fav_food': 'spinach'},\n",
|
|
" {'name': 'Caroline', 'age': 23, 'fav_food': ''}]}"
|
|
]
|
|
},
|
|
"execution_count": 3,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"from typing import Sequence\n",
|
|
"\n",
|
|
"class People(BaseModel):\n",
|
|
" \"\"\"Identifying information about all people in a text.\"\"\"\n",
|
|
" people: Sequence[Person] = Field(..., description=\"The people in the text\")\n",
|
|
" \n",
|
|
"chain = create_structured_output_chain(People, verbose=True)\n",
|
|
"chain.run(\"Sally is 13, Joey just turned 12 and loves spinach. Caroline is 10 years older than Sally, so she's 23.\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "ea66e10e",
|
|
"metadata": {},
|
|
"source": [
|
|
"### Using JsonSchema\n",
|
|
"\n",
|
|
"We can also pass in JsonSchema instead of Pydantic objects to specify the desired structure. When we do this, our chain will output json corresponding to the properties described in the JsonSchema, instead of a Pydantic object."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 4,
|
|
"id": "3484415e",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"json_schema = {\n",
|
|
" \"title\": \"Person\",\n",
|
|
" \"description\": \"Identifying information about a person.\",\n",
|
|
" \"type\": \"object\",\n",
|
|
" \"properties\": {\n",
|
|
" \"name\": {\n",
|
|
" \"title\": \"Name\",\n",
|
|
" \"description\": \"The person's name\",\n",
|
|
" \"type\": \"string\"\n",
|
|
" },\n",
|
|
" \"age\": {\n",
|
|
" \"title\": \"Age\",\n",
|
|
" \"description\": \"The person's age\",\n",
|
|
" \"type\": \"integer\"\n",
|
|
" },\n",
|
|
" \"fav_food\": {\n",
|
|
" \"title\": \"Fav Food\",\n",
|
|
" \"description\": \"The person's favorite food\",\n",
|
|
" \"type\": \"string\"\n",
|
|
" }\n",
|
|
" },\n",
|
|
" \"required\": [\n",
|
|
" \"name\",\n",
|
|
" \"age\"\n",
|
|
" ]\n",
|
|
"}\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 5,
|
|
"id": "be9b76b3",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"\n",
|
|
"\n",
|
|
"\u001b[1m> Entering new chain...\u001b[0m\n",
|
|
"Prompt after formatting:\n",
|
|
"\u001b[32;1m\u001b[1;3mHuman: Sally is 13\u001b[0m\n",
|
|
"\n",
|
|
"\u001b[1m> Finished chain.\u001b[0m\n"
|
|
]
|
|
},
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"{'name': 'Sally', 'age': 13}"
|
|
]
|
|
},
|
|
"execution_count": 5,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"chain = create_structured_output_chain(json_schema, verbose=True)\n",
|
|
"chain.run(\"Sally is 13\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "12394696",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Creating a generic OpenAI functions chain\n",
|
|
"To create a generic OpenAI functions chain, we can use the `create_openai_fn_chain` method. This is the same as `create_structured_output_chain` except that instead of taking a single output schema, it takes a sequence of function definitions.\n",
|
|
"\n",
|
|
"Functions can be passed in as:\n",
|
|
"- dicts conforming to OpenAI functions spec,\n",
|
|
"- Pydantic objects, in which case they should have docstring descriptions of the function they represent and descriptions for each of the parameters,\n",
|
|
"- Python functions, in which case they should have docstring descriptions of the function and args, along with type hints.\n",
|
|
"\n",
|
|
"See here for relevant [reference docs](https://api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.base.create_openai_fn_chain.html)."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "ff19be25",
|
|
"metadata": {},
|
|
"source": [
|
|
"### Using Pydantic objects"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 6,
|
|
"id": "a4658ad8",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"\n",
|
|
"\n",
|
|
"\u001b[1m> Entering new chain...\u001b[0m\n",
|
|
"Prompt after formatting:\n",
|
|
"\u001b[32;1m\u001b[1;3mHuman: Harry was a chubby brown beagle who loved chicken\u001b[0m\n",
|
|
"\n",
|
|
"\u001b[1m> Finished chain.\u001b[0m\n"
|
|
]
|
|
},
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"RecordDog(name='Harry', color='brown', fav_food='chicken')"
|
|
]
|
|
},
|
|
"execution_count": 6,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"class RecordPerson(BaseModel):\n",
|
|
" \"\"\"Record some identifying information about a pe.\"\"\"\n",
|
|
" name: str = Field(..., description=\"The person's name\")\n",
|
|
" age: int = Field(..., description=\"The person's age\")\n",
|
|
" fav_food: Optional[str] = Field(None, description=\"The person's favorite food\")\n",
|
|
"\n",
|
|
"class RecordDog(BaseModel):\n",
|
|
" \"\"\"Record some identifying information about a dog.\"\"\"\n",
|
|
" name: str = Field(..., description=\"The dog's name\")\n",
|
|
" color: str = Field(..., description=\"The dog's color\")\n",
|
|
" fav_food: Optional[str] = Field(None, description=\"The dog's favorite food\")\n",
|
|
"\n",
|
|
"chain = create_openai_fn_chain([RecordPerson, RecordDog], verbose=True)\n",
|
|
"chain.run(\"Harry was a chubby brown beagle who loved chicken\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "df6d9147",
|
|
"metadata": {},
|
|
"source": [
|
|
"### Using Python functions\n",
|
|
"We can pass in functions as Pydantic objects, directly as OpenAI function dicts, or Python functions. To pass Python function in directly, we'll want to make sure our parameters have type hints, we have a docstring, and we use [Google Python style docstrings](https://google.github.io/styleguide/pyguide.html#doc-function-args) to describe the parameters.\n",
|
|
"\n",
|
|
"**NOTE**: To use Python functions, make sure the function arguments are of primitive types (str, float, int, bool) or that they are Pydantic objects."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 41,
|
|
"id": "95ac5825",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"\n",
|
|
"\n",
|
|
"\u001b[1m> Entering new chain...\u001b[0m\n",
|
|
"Prompt after formatting:\n",
|
|
"\u001b[32;1m\u001b[1;3mHuman: The most important thing to remember about Tommy, my 12 year old, is that he'll do anything for apple pie.\u001b[0m\n",
|
|
"\n",
|
|
"\u001b[1m> Finished chain.\u001b[0m\n"
|
|
]
|
|
},
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"{'name': 'Tommy', 'age': 12, 'fav_food': {'food': 'apple pie'}}"
|
|
]
|
|
},
|
|
"execution_count": 41,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"class OptionalFavFood(BaseModel):\n",
|
|
" \"\"\"Either a food or null.\"\"\"\n",
|
|
" food: Optional[str] = Field(None, description=\"Either the name of a food or null. Should be null if the food isn't known.\")\n",
|
|
"\n",
|
|
"def record_person(name: str, age: int, fav_food: OptionalFavFood) -> str:\n",
|
|
" \"\"\"Record some basic identifying information about a person.\n",
|
|
" \n",
|
|
" Args:\n",
|
|
" name: The person's name.\n",
|
|
" age: The person's age in years.\n",
|
|
" fav_food: An OptionalFavFood object that either contains the person's favorite food or a null value. Food should be null if it's not known.\n",
|
|
" \"\"\"\n",
|
|
" return f\"Recording person {name} of age {age} with favorite food {fav_food.food}!\"\n",
|
|
"\n",
|
|
" \n",
|
|
"chain = create_openai_fn_chain([record_person], verbose=True)\n",
|
|
"chain.run(\"The most important thing to remember about Tommy, my 12 year old, is that he'll do anything for apple pie.\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "403ea5dd",
|
|
"metadata": {},
|
|
"source": [
|
|
"If we pass in multiple Python functions or OpenAI functions, then the returned output will be of the form\n",
|
|
"```python\n",
|
|
"{\"name\": \"<<function_name>>\", \"arguments\": {<<function_arguments>>}}\n",
|
|
"```"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 42,
|
|
"id": "8b0d11de",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"\n",
|
|
"\n",
|
|
"\u001b[1m> Entering new chain...\u001b[0m\n",
|
|
"Prompt after formatting:\n",
|
|
"\u001b[32;1m\u001b[1;3mHuman: I can't find my dog Henry anywhere, he's a small brown beagle. Could you send a message about him?\u001b[0m\n",
|
|
"\n",
|
|
"\u001b[1m> Finished chain.\u001b[0m\n"
|
|
]
|
|
},
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"{'name': 'report_dog',\n",
|
|
" 'arguments': {'name': 'Henry', 'color': 'brown', 'fav_food': {'food': None}}}"
|
|
]
|
|
},
|
|
"execution_count": 42,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"def record_dog(name: str, color: str, fav_food: OptionalFavFood) -> str:\n",
|
|
" \"\"\"Record some basic identifying information about a dog.\n",
|
|
" \n",
|
|
" Args:\n",
|
|
" name: The dog's name.\n",
|
|
" color: The dog's color.\n",
|
|
" fav_food: An OptionalFavFood object that either contains the dog's favorite food or a null value. Food should be null if it's not known.\n",
|
|
" \"\"\"\n",
|
|
" return f\"Recording dog {name} of color {color} with favorite food {fav_food}!\"\n",
|
|
"\n",
|
|
"\n",
|
|
"chain = create_openai_fn_chain([record_person, report_dog], verbose=True)\n",
|
|
"chain.run(\"I can't find my dog Henry anywhere, he's a small brown beagle. Could you send a message about him?\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "4535ce33",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Creating a Chain that runs the chosen function\n",
|
|
"We can go one step further and create a chain that actually executes the function chosen by the model."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 43,
|
|
"id": "43b0dfe0",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"import json\n",
|
|
"import inspect\n",
|
|
"from typing import Any, Callable, Dict, List, Optional\n",
|
|
"\n",
|
|
"from langchain.callbacks.manager import CallbackManagerForChainRun\n",
|
|
"from langchain.chains.base import Chain\n",
|
|
"from langchain.input import get_colored_text\n",
|
|
"\n",
|
|
"\n",
|
|
"class FunctionExecutorChain(Chain):\n",
|
|
" functions: Dict[str, Callable]\n",
|
|
" output_key: str = \"output\"\n",
|
|
" input_key: str = \"function\"\n",
|
|
"\n",
|
|
" @property\n",
|
|
" def input_keys(self) -> List[str]:\n",
|
|
" return [self.input_key]\n",
|
|
"\n",
|
|
" @property\n",
|
|
" def output_keys(self) -> List[str]:\n",
|
|
" return [self.output_key]\n",
|
|
"\n",
|
|
" def _call(\n",
|
|
" self,\n",
|
|
" inputs: Dict[str, Any],\n",
|
|
" run_manager: Optional[CallbackManagerForChainRun] = None,\n",
|
|
" ) -> Dict[str, Any]:\n",
|
|
" \"\"\"Run the logic of this chain and return the output.\"\"\"\n",
|
|
" _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()\n",
|
|
" name = inputs[\"function\"].pop(\"name\")\n",
|
|
" args = inputs[\"function\"].pop(\"arguments\")\n",
|
|
" _pretty_name = get_colored_text(name, \"green\")\n",
|
|
" _pretty_args = get_colored_text(json.dumps(args, indent=2), \"green\")\n",
|
|
" _text = f\"Calling function {_pretty_name} with arguments:\\n\" + _pretty_args\n",
|
|
" _run_manager.on_text(_text)\n",
|
|
" _args = {}\n",
|
|
" function = self.functions[name]\n",
|
|
" for arg_name, arg_type in inspect.getfullargspec(function).annotations.items():\n",
|
|
" if isinstance(arg_type, type) and issubclass(arg_type, BaseModel):\n",
|
|
" args[arg_name] = arg_type.parse_obj(args[arg_name])\n",
|
|
" output = function(**args)\n",
|
|
" return {self.output_key: output}"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 44,
|
|
"id": "b8391857",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"\n",
|
|
"\n",
|
|
"\u001b[1m> Entering new chain...\u001b[0m\n",
|
|
"\n",
|
|
"\n",
|
|
"\u001b[1m> Entering new chain...\u001b[0m\n",
|
|
"Calling function \u001b[32;1m\u001b[1;3mrecord_person\u001b[0m with arguments:\n",
|
|
"\u001b[32;1m\u001b[1;3m{\n",
|
|
" \"name\": \"Tommy\",\n",
|
|
" \"age\": 12,\n",
|
|
" \"fav_food\": {\n",
|
|
" \"food\": \"apple pie\"\n",
|
|
" }\n",
|
|
"}\u001b[0m\n",
|
|
"\u001b[1m> Finished chain.\u001b[0m\n",
|
|
"\n",
|
|
"\u001b[1m> Finished chain.\u001b[0m\n"
|
|
]
|
|
},
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"'Recording person Tommy of age 12 with favorite food apple pie!'"
|
|
]
|
|
},
|
|
"execution_count": 44,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"from langchain.chains import SequentialChain\n",
|
|
"from langchain.chains.openai_functions.base import convert_to_openai_function\n",
|
|
"\n",
|
|
"functions = [record_person, record_dog]\n",
|
|
"openai_functions = [convert_to_openai_function(f) for f in functions]\n",
|
|
"fn_map = {\n",
|
|
" openai_fn[\"name\"]: fn for openai_fn, fn in zip(openai_functions, functions)\n",
|
|
"}\n",
|
|
"llm_chain = create_openai_fn_chain(functions)\n",
|
|
"exec_chain = FunctionExecutorChain(functions=fn_map, verbose=True)\n",
|
|
"chain = SequentialChain(\n",
|
|
" chains=[llm_chain, exec_chain],\n",
|
|
" input_variables=llm_chain.input_keys,\n",
|
|
" output_variables=[\"output\"],\n",
|
|
" verbose=True\n",
|
|
")\n",
|
|
"chain.run(\"The most important thing to remember about Tommy, my 12 year old, is that he'll do anything for apple pie.\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "5f93686b",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Other Chains using OpenAI functions\n",
|
|
"\n",
|
|
"There are a number of more specific chains that use OpenAI functions.\n",
|
|
"- [Extraction](/docs/modules/chains/additional/extraction): very similar to structured output chain, intended for information/entity extraction specifically.\n",
|
|
"- [Tagging](/docs/modules/chains/additional/tagging): tag inputs.\n",
|
|
"- [OpenAPI](/docs/modules/chains/additional/openapi_openai): take an OpenAPI spec and create + execute valid requests against the API, using OpenAI functions under the hood.\n",
|
|
"- [QA with citations](/docs/modules/chains/additional/qa_citations): use OpenAI functions ability to extract citations from text."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "93425c66",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": []
|
|
}
|
|
],
|
|
"metadata": {
|
|
"kernelspec": {
|
|
"display_name": "venv",
|
|
"language": "python",
|
|
"name": "venv"
|
|
},
|
|
"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.3"
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 5
|
|
}
|