"In this example we'll walk through how to build and iterate on a hotel room search service that leverages an LLM to generate structured filter queries that can then be passed to a vector store.\n",
"\n",
"For an introduction to self-querying retrieval [check out the docs](https://python.langchain.com/docs/modules/data_connection/retrievers/self_query)."
]
},
{
"cell_type": "markdown",
"id": "d621de99-d993-4f4b-b94a-d02b2c7ad4e0",
"metadata": {},
"source": [
"## Imports and data prep\n",
"\n",
"In this example we use `ChatOpenAI` for the model and `ElasticsearchStore` for the vector store, but these can be swapped out with an LLM/ChatModel and [any VectorStore that support self-querying](https://python.langchain.com/docs/integrations/retrievers/self_query/).\n",
"[{'name': 'roomtype', 'description': 'The type of the room', 'type': 'string'},\n",
" {'name': 'onsiterate',\n",
" 'description': 'The rate of the room',\n",
" 'type': 'float'},\n",
" {'name': 'roomamenities',\n",
" 'description': 'Amenities available in the room',\n",
" 'type': 'string'},\n",
" {'name': 'maxoccupancy',\n",
" 'description': 'Maximum number of people that can occupy the room. Valid values are [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 24]',\n",
" 'type': 'integer'},\n",
" {'name': 'roomdescription',\n",
" 'description': 'Description of the room',\n",
" 'type': 'string'},\n",
" {'name': 'hotelname', 'description': 'Name of the hotel', 'type': 'string'},\n",
" {'name': 'city',\n",
" 'description': 'City where the hotel is located',\n",
" 'type': 'string'},\n",
" {'name': 'country',\n",
" 'description': \"Country where the hotel is located. Valid values are ['Austria', 'Belgium', 'Bulgaria', 'Croatia', 'Cyprus', 'Czech Republic', 'Denmark', 'Estonia', 'Finland', 'France', 'Germany', 'Greece', 'Hungary', 'Ireland', 'Italy', 'Latvia', 'Lithuania', 'Luxembourg', 'Malta', 'Netherlands', 'Poland', 'Portugal', 'Romania', 'Slovakia', 'Slovenia', 'Spain', 'Sweden', 'Switzerland', 'United Kingdom']\",\n",
" 'type': 'string'},\n",
" {'name': 'starrating',\n",
" 'description': 'Star rating of the hotel. Valid values are [2, 3, 4]',\n",
" 'type': 'integer'},\n",
" {'name': 'mealsincluded',\n",
" 'description': 'Whether meals are included or not',\n",
" 'type': 'boolean'}]"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"attribute_info"
]
},
{
"cell_type": "markdown",
"id": "81c75a25-9c64-4da6-87ae-580bd47962bb",
"metadata": {},
"source": [
"## Creating a query constructor chain\n",
"\n",
"Let's take a look at the chain that will convert natural language requests into structured queries.\n",
"\n",
"To start we can just load the prompt and see what it looks like"
"Your goal is to structure the user's query to match the request schema provided below.\n",
"\n",
"<< Structured Request Schema >>\n",
"When responding use a markdown code snippet with a JSON object formatted in the following schema:\n",
"\n",
"```json\n",
"{\n",
" \"query\": string \\ text string to compare to document contents\n",
" \"filter\": string \\ logical condition statement for filtering documents\n",
"}\n",
"```\n",
"\n",
"The query string should contain only text that is expected to match the contents of documents. Any conditions in the filter should not be mentioned in the query as well.\n",
"\n",
"A logical condition statement is composed of one or more comparison and logical operation statements.\n",
"\n",
"A comparison statement takes the form: `comp(attr, val)`:\n",
"- `comp` (eq | ne | gt | gte | lt | lte | contain | like | in | nin): comparator\n",
"- `attr` (string): name of attribute to apply the comparison to\n",
"- `val` (string): is the comparison value\n",
"\n",
"A logical operation statement takes the form `op(statement1, statement2, ...)`:\n",
"- `op` (and | or | not): logical operator\n",
"- `statement1`, `statement2`, ... (comparison statements or logical operation statements): one or more statements to apply the operation to\n",
"\n",
"Make sure that you only use the comparators and logical operators listed above and no others.\n",
"Make sure that filters only refer to attributes that exist in the data source.\n",
"Make sure that filters only use the attributed names with its function names if there are functions applied on them.\n",
"Make sure that filters only use format `YYYY-MM-DD` when handling timestamp data typed values.\n",
"Make sure that filters take into account the descriptions of attributes and only make comparisons that are feasible given the type of data being stored.\n",
"Make sure that filters are only used as needed. If there are no filters that should be applied return \"NO_FILTER\" for the filter value.\n",
"\n",
"<< Example 1. >>\n",
"Data Source:\n",
"```json\n",
"{\n",
" \"content\": \"Lyrics of a song\",\n",
" \"attributes\": {\n",
" \"artist\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"Name of the song artist\"\n",
" },\n",
" \"length\": {\n",
" \"type\": \"integer\",\n",
" \"description\": \"Length of the song in seconds\"\n",
" },\n",
" \"genre\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"The song genre, one of \"pop\", \"rock\" or \"rap\"\"\n",
" }\n",
" }\n",
"}\n",
"```\n",
"\n",
"User Query:\n",
"What are songs by Taylor Swift or Katy Perry about teenage romance under 3 minutes long in the dance pop genre\n",
" \"description\": \"Name of the song artist\"\n",
" },\n",
" \"length\": {\n",
" \"type\": \"integer\",\n",
" \"description\": \"Length of the song in seconds\"\n",
" },\n",
" \"genre\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"The song genre, one of \"pop\", \"rock\" or \"rap\"\"\n",
" }\n",
" }\n",
"}\n",
"```\n",
"\n",
"User Query:\n",
"What are songs that were not published on Spotify\n",
"\n",
"Structured Request:\n",
"```json\n",
"{\n",
" \"query\": \"\",\n",
" \"filter\": \"NO_FILTER\"\n",
"}\n",
"```\n",
"\n",
"\n",
"<< Example 3. >>\n",
"Data Source:\n",
"```json\n",
"{\n",
" \"content\": \"Detailed description of a hotel room\",\n",
" \"attributes\": {\n",
" \"roomtype\": {\n",
" \"description\": \"The type of the room\",\n",
" \"type\": \"string\"\n",
" },\n",
" \"onsiterate\": {\n",
" \"description\": \"The rate of the room\",\n",
" \"type\": \"float\"\n",
" },\n",
" \"roomamenities\": {\n",
" \"description\": \"Amenities available in the room\",\n",
" \"type\": \"string\"\n",
" },\n",
" \"maxoccupancy\": {\n",
" \"description\": \"Maximum number of people that can occupy the room. Valid values are [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 24]\",\n",
" \"type\": \"integer\"\n",
" },\n",
" \"roomdescription\": {\n",
" \"description\": \"Description of the room\",\n",
" \"type\": \"string\"\n",
" },\n",
" \"hotelname\": {\n",
" \"description\": \"Name of the hotel\",\n",
" \"type\": \"string\"\n",
" },\n",
" \"city\": {\n",
" \"description\": \"City where the hotel is located\",\n",
" \"type\": \"string\"\n",
" },\n",
" \"country\": {\n",
" \"description\": \"Country where the hotel is located. Valid values are ['Austria', 'Belgium', 'Bulgaria', 'Croatia', 'Cyprus', 'Czech Republic', 'Denmark', 'Estonia', 'Finland', 'France', 'Germany', 'Greece', 'Hungary', 'Ireland', 'Italy', 'Latvia', 'Lithuania', 'Luxembourg', 'Malta', 'Netherlands', 'Poland', 'Portugal', 'Romania', 'Slovakia', 'Slovenia', 'Spain', 'Sweden', 'Switzerland', 'United Kingdom']\",\n",
" \"type\": \"string\"\n",
" },\n",
" \"starrating\": {\n",
" \"description\": \"Star rating of the hotel. Valid values are [2, 3, 4]\",\n",
" \"type\": \"integer\"\n",
" },\n",
" \"mealsincluded\": {\n",
" \"description\": \"Whether meals are included or not\",\n",
" \"type\": \"boolean\"\n",
" }\n",
"}\n",
"}\n",
"```\n",
"\n",
"User Query:\n",
"{query}\n",
"\n",
"Structured Request:\n",
"\n"
]
}
],
"source": [
"doc_contents = \"Detailed description of a hotel room\"\n",
"We can see that at least two issues above. First is that when we ask for a Southern European destination we're only getting a filter for Italy, and second when we ask for AC we get a literal string lookup for AC (which isn't so bad but will miss things like 'Air conditioning').\n",
"As a first step, let's try to update our description of the 'country' attribute to emphasize that equality should only be used when a specific country is mentioned."
"] += \". NOTE: Only use the 'eq' operator if a specific country is mentioned. If a region is mentioned, include all relevant countries in filter.\"\n",
"chain.invoke({\"query\": \"I want a hotel in Southern Europe and my budget is 200 bucks.\"})"
]
},
{
"cell_type": "markdown",
"id": "eb793908-ea10-4a55-96b8-ab6915262c50",
"metadata": {},
"source": [
"## Refining which attributes to filter on\n",
"\n",
"This seems to have helped! Now let's try to narrow the attributes we're filtering on. More freeform attributes we can leave to the main query, which is better for capturing semantic meaning than searching for specific substrings."
"We've removed the strict filter for 'AC' but it's still not being included in the query string. Our chain prompt is a few-shot prompt with some default examples. Let's see if adding use case-specific examples will help:"
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "62b903c1-3861-4aef-9ea6-1666eeee503c",
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Your goal is to structure the user's query to match the request schema provided below.\n",
"\n",
"<< Structured Request Schema >>\n",
"When responding use a markdown code snippet with a JSON object formatted in the following schema:\n",
"\n",
"```json\n",
"{\n",
" \"query\": string \\ text string to compare to document contents\n",
" \"filter\": string \\ logical condition statement for filtering documents\n",
"}\n",
"```\n",
"\n",
"The query string should contain only text that is expected to match the contents of documents. Any conditions in the filter should not be mentioned in the query as well.\n",
"\n",
"A logical condition statement is composed of one or more comparison and logical operation statements.\n",
"\n",
"A comparison statement takes the form: `comp(attr, val)`:\n",
"- `comp` (eq | ne | gt | gte | lt | lte | contain | like | in | nin): comparator\n",
"- `attr` (string): name of attribute to apply the comparison to\n",
"- `val` (string): is the comparison value\n",
"\n",
"A logical operation statement takes the form `op(statement1, statement2, ...)`:\n",
"- `op` (and | or | not): logical operator\n",
"- `statement1`, `statement2`, ... (comparison statements or logical operation statements): one or more statements to apply the operation to\n",
"\n",
"Make sure that you only use the comparators and logical operators listed above and no others.\n",
"Make sure that filters only refer to attributes that exist in the data source.\n",
"Make sure that filters only use the attributed names with its function names if there are functions applied on them.\n",
"Make sure that filters only use format `YYYY-MM-DD` when handling timestamp data typed values.\n",
"Make sure that filters take into account the descriptions of attributes and only make comparisons that are feasible given the type of data being stored.\n",
"Make sure that filters are only used as needed. If there are no filters that should be applied return \"NO_FILTER\" for the filter value.\n",
"\n",
"<< Data Source >>\n",
"```json\n",
"{\n",
" \"content\": \"A detailed description of a hotel room, including information about the room type and room amenities.\",\n",
" \"attributes\": {\n",
" \"onsiterate\": {\n",
" \"description\": \"The rate of the room\",\n",
" \"type\": \"float\"\n",
" },\n",
" \"maxoccupancy\": {\n",
" \"description\": \"Maximum number of people that can occupy the room. Valid values are [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 24]\",\n",
" \"type\": \"integer\"\n",
" },\n",
" \"city\": {\n",
" \"description\": \"City where the hotel is located\",\n",
" \"type\": \"string\"\n",
" },\n",
" \"country\": {\n",
" \"description\": \"Country where the hotel is located. Valid values are ['Austria', 'Belgium', 'Bulgaria', 'Croatia', 'Cyprus', 'Czech Republic', 'Denmark', 'Estonia', 'Finland', 'France', 'Germany', 'Greece', 'Hungary', 'Ireland', 'Italy', 'Latvia', 'Lithuania', 'Luxembourg', 'Malta', 'Netherlands', 'Poland', 'Portugal', 'Romania', 'Slovakia', 'Slovenia', 'Spain', 'Sweden', 'Switzerland', 'United Kingdom']. NOTE: Only use the 'eq' operator if a specific country is mentioned. If a region is mentioned, include all relevant countries in filter.\",\n",
" \"type\": \"string\"\n",
" },\n",
" \"starrating\": {\n",
" \"description\": \"Star rating of the hotel. Valid values are [2, 3, 4]\",\n",
" \"type\": \"integer\"\n",
" },\n",
" \"mealsincluded\": {\n",
" \"description\": \"Whether meals are included or not\",\n",
" \"type\": \"boolean\"\n",
" }\n",
"}\n",
"}\n",
"```\n",
"\n",
"\n",
"<< Example 1. >>\n",
"User Query:\n",
"I want a hotel in the Balkans with a king sized bed and a hot tub. Budget is $300 a night\n",
"Cell \u001b[0;32mIn[21], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43mchain\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43minvoke\u001b[49m\u001b[43m(\u001b[49m\u001b[43m{\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mquery\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mI want to stay somewhere highly rated along the coast. I want a room with a patio and a fireplace.\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m}\u001b[49m\u001b[43m)\u001b[49m\n",
"File \u001b[0;32m~/langchain/libs/langchain/langchain/schema/runnable/base.py:1113\u001b[0m, in \u001b[0;36mRunnableSequence.invoke\u001b[0;34m(self, input, config)\u001b[0m\n\u001b[1;32m 1111\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m 1112\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m i, step \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28menumerate\u001b[39m(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msteps):\n\u001b[0;32m-> 1113\u001b[0m \u001b[38;5;28minput\u001b[39m \u001b[38;5;241m=\u001b[39m \u001b[43mstep\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43minvoke\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 1114\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1115\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;66;43;03m# mark each step as a child run\u001b[39;49;00m\n\u001b[1;32m 1116\u001b[0m \u001b[43m \u001b[49m\u001b[43mpatch_config\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 1117\u001b[0m \u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mcallbacks\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mrun_manager\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mget_child\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43mf\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mseq:step:\u001b[39;49m\u001b[38;5;132;43;01m{\u001b[39;49;00m\u001b[43mi\u001b[49m\u001b[38;5;241;43m+\u001b[39;49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[38;5;132;43;01m}\u001b[39;49;00m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1118\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1119\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1120\u001b[0m \u001b[38;5;66;03m# finish the root run\u001b[39;00m\n\u001b[1;32m 1121\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n",
"File \u001b[0;32m~/langchain/libs/langchain/langchain/schema/output_parser.py:225\u001b[0m, in \u001b[0;36mBaseOutputParser.parse_result\u001b[0;34m(self, result, partial)\u001b[0m\n\u001b[1;32m 212\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mparse_result\u001b[39m(\u001b[38;5;28mself\u001b[39m, result: List[Generation], \u001b[38;5;241m*\u001b[39m, partial: \u001b[38;5;28mbool\u001b[39m \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mFalse\u001b[39;00m) \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m>\u001b[39m T:\n\u001b[1;32m 213\u001b[0m \u001b[38;5;250m \u001b[39m\u001b[38;5;124;03m\"\"\"Parse a list of candidate model Generations into a specific format.\u001b[39;00m\n\u001b[1;32m 214\u001b[0m \n\u001b[1;32m 215\u001b[0m \u001b[38;5;124;03m The return value is parsed from only the first Generation in the result, which\u001b[39;00m\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 223\u001b[0m \u001b[38;5;124;03m Structured output.\u001b[39;00m\n\u001b[1;32m 224\u001b[0m \u001b[38;5;124;03m \"\"\"\u001b[39;00m\n\u001b[0;32m--> 225\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mparse\u001b[49m\u001b[43m(\u001b[49m\u001b[43mresult\u001b[49m\u001b[43m[\u001b[49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m]\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mtext\u001b[49m\u001b[43m)\u001b[49m\n",
"File \u001b[0;32m~/langchain/libs/langchain/langchain/chains/query_constructor/base.py:60\u001b[0m, in \u001b[0;36mStructuredQueryOutputParser.parse\u001b[0;34m(self, text)\u001b[0m\n\u001b[1;32m 56\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m StructuredQuery(\n\u001b[1;32m 57\u001b[0m \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39m{k: v \u001b[38;5;28;01mfor\u001b[39;00m k, v \u001b[38;5;129;01min\u001b[39;00m parsed\u001b[38;5;241m.\u001b[39mitems() \u001b[38;5;28;01mif\u001b[39;00m k \u001b[38;5;129;01min\u001b[39;00m allowed_keys}\n\u001b[1;32m 58\u001b[0m )\n\u001b[1;32m 59\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[0;32m---> 60\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m OutputParserException(\n\u001b[1;32m 61\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mParsing text\u001b[39m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;132;01m{\u001b[39;00mtext\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;124m raised following error:\u001b[39m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;132;01m{\u001b[39;00me\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 62\u001b[0m )\n",
"It seems our model get's tripped up on this more complex query and tries to search over an attribute ('description') that doesn't exist. By setting `fix_invalid=True` in our query constructor chain, we can automatically remove any parts of the filter that is invalid (meaning it's using disallowed operations, comparisons or attributes)."
"Now that our query construction chain is in a decent place, let's try using it with an actual retriever. For this example we'll use the [ElasticsearchStore](https://python.langchain.com/docs/integrations/vectorstores/elasticsearch)."
" \"roomdescription\": \"Room size: 110 m\\u00b2/1184 ft\\u00b2, Balcony/terrace, Shower and bathtub, Kitchenette, 4 bedrooms, 1 single bed or 1 queen bed or 1 double bed or 2 single beds\",\n",
" \"hotelname\": \"1 Elliot Terrace\",\n",
" \"city\": \"Plymouth\",\n",
" \"country\": \"United Kingdom\",\n",
" \"starrating\": 4,\n",
" \"mealsincluded\": false\n",
"}\n",
"\n",
"--------------------\n",
"\n",
"{\n",
" \"roomtype\": \"Three-Bedroom Holiday Home with Terrace and Sea View\",\n",
" \"roomdescription\": \"Room size: 157 m\\u00b2/1690 ft\\u00b2, Balcony/terrace, 3 bathrooms, Shower, Kitchenette, 3 bedrooms, 1 queen bed or 1 queen bed or 1 queen bed or 1 sofa bed\",\n",
" \"hotelname\": \"Seaside holiday house Artatore (Losinj) - 17102\",\n",