docs: runnable list operations

pull/20349/head
Erick Friis 2 months ago
parent 9d302c1b57
commit bca1f3e1bf

@ -0,0 +1,145 @@
{
"cells": [
{
"cell_type": "raw",
"metadata": {
"vscode": {
"languageId": "raw"
}
},
"source": [
"---\n",
"title: Lists\n",
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Operating on Lists\n",
"\n",
"Lists are a fundamental data structure in Python. In this tutorial, we will explore the different ways of using lists of inputs in LCEL."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Note: you may need to restart the kernel to use updated packages.\n"
]
}
],
"source": [
"%pip install -qU langchain-anthropic"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[AIMessage(content='There is no single \"best\" rock, as different types of rocks have different properties and uses. However, some rocks that are highly valued or widely used include:\\n\\n1. Granite - A very hard, durable igneous rock that is widely used in construction, countertops, and monuments.\\n\\n2. Marble - A metamorphic rock that is prized for its beauty and used in sculpture, construction, and tiles.\\n\\n3. Sandstone - A sedimentary rock that is relatively soft but durable, often used for buildings and decorative purposes.\\n\\n4. Limestone - Another sedimentary rock that is an important building material and is also the primary component of cement.\\n\\n5. Slate - A metamorphic rock valued for its ability to split into thin sheets, used for roofing, flooring, and chalkboards.\\n\\n6. Quartzite - An extremely hard metamorphic rock that is durable and used for building materials and road construction.\\n\\nThe \"best\" rock often depends on the specific application or desired qualities, such as hardness, appearance, availability, or workability. Different rocks excel in different areas, so there is no single best rock for all purposes.', response_metadata={'id': 'msg_014dGS6LgH443TvJa6jAjBHS', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 20, 'output_tokens': 258}}, id='run-0c6b4ce2-459b-46ec-8bc0-82cf54a305a0-0'),\n",
" AIMessage(content=\"As a professional pirate, I'd say the best type of treasure is gold and jewels! Nothing beats hauling in a huge haul of glittering coins, gemstones, and priceless jewelry after plundering a galleon or raiding a royal treasury. That kind of loot is not only extremely valuable, but it has a delightfully piratical flair. Plus, gold and jewels are easy to transport and fence compared to more cumbersome treasures. Though I must admit, maps leading to even more treasure hordes are a close second when it comes to a pirate's favorite booty!\", response_metadata={'id': 'msg_01WjfUc6LqbVvLqwGYzWbX54', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 22, 'output_tokens': 135}}, id='run-5082008e-fe85-4927-a03c-a67a65b8b76c-0'),\n",
" AIMessage(content='There is no definitive \"best\" planet, as that is a subjective opinion. However, here are some of the most interesting and potentially habitable planets we know about so far:\\n\\nEarth - Remains the only planet known to definitively harbor life. It has a atmosphere, liquid water on its surface, and lies within the Sun\\'s habitable zone.\\n\\nMars - Shows geological evidence of liquid water existing on its surface in the ancient past. It has seasons, polar caps and weather systems, though a very thin atmosphere today.\\n\\nProxima Centauri b - This exoplanet orbits in the habitable zone of the nearest star to our solar system, Proxima Centauri. Its mass suggests it could be terrestrial.\\n\\nTRAPPIST-1d - One of seven planets orbiting the ultra-cool dwarf star TRAPPIST-1. At least three of these exoplanets may lie in the star\\'s habitable zone.\\n\\nKepler-452b - A super Earth exoplanet orbiting a sun-like star in the habitable zone. It may have conditions amenable for liquid water on its surface.\\n\\nOf course, we haven\\'t been able to study most exoplanets in great detail yet. Continued exploration and research is needed to determine if life could exist on any of them. Earth remains the best current example of a life-bearing planet we know of.', response_metadata={'id': 'msg_01Rcj8Zf1XdpUSYpLeQGH98W', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 20, 'output_tokens': 304}}, id='run-b3de467a-234c-4b43-9cce-2747abd70946-0'),\n",
" AIMessage(content='As a professional chef, I don\\'t think there is any single \"best\" food. Different foods excel in different ways - flavors, textures, nutritional values, cultural significance, etc. Some of my personal favorites to cook with are:\\n\\n- Fresh seasonal produce - Their flavors really shine when used at peak ripeness.\\n\\n- High-quality proteins like dry-aged beef, fresh seafood, and pasture-raised poultry and eggs. Proper sourcing makes a big difference.\\n\\n- Artisan cheeses and charcuterie from skilled producers.\\n\\n- Interesting spices, herbs, and global ingredients that add unique flavors.\\n\\nRather than declaring any one food the \"best,\" I prefer to appreciate foods for their distinct qualities and purposes. A perfect summer tomato, a decadent chocolate ganache, a bright citrusy ceviche - each can be sublime in its own way when made with care and skill. As a chef, bringing out the best in quality ingredients is always my goal.', response_metadata={'id': 'msg_01331sCPT26v6rbaYvTrsVMp', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 19, 'output_tokens': 218}}, id='run-00e5982b-76e2-4dce-bc38-155dda9f06b7-0')]"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# todo - clean it up\n",
"\n",
"# lists as inputs, pass to .batch\n",
"\n",
"from langchain_core.prompts import ChatPromptTemplate\n",
"from langchain_anthropic import ChatAnthropic\n",
"\n",
"my_list = [\n",
" {\"profession\": \"geologist\", \"question\": \"what is the best rock?\" },\n",
" {\"profession\": \"pirate\", \"question\": \"what is the best type of treasure?\" },\n",
" {\"profession\": \"astronaut\", \"question\": \"what is the best planet?\" },\n",
" {\"profession\": \"chef\", \"question\": \"what is the best food?\" },\n",
"]\n",
"\n",
"prompt = ChatPromptTemplate.from_messages([(\"system\", \"You are a professional {profession}.\"), (\"human\", \"{question}\")])\n",
"model = ChatAnthropic(model='claude-3-sonnet-20240229')\n",
"chain = prompt | model\n",
"\n",
"# invoke straight batch\n",
"chain.batch(my_list)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[AIMessage(content='There is no single \"best\" rock, as different rock types have different properties and uses. However, here are some of the most interesting and valuable rocks:\\n\\n- Diamond - Extremely hard and prized as a gemstone. Formed under immense heat and pressure.\\n\\n- Gold - A highly coveted precious metal used for jewelry, electronics and investment. Found in certain types of mineral deposits.\\n\\n- Marble - A metamorphic rock prized for its beauty and used widely in sculpture and architecture. Forms from metamorphosed limestone.\\n\\n- Obsidian - A volcanic glass that can produce extremely sharp edges, formerly used to make arrowheads and knives.\\n\\n- Sandstone - A sedimentary rock used as a building material from ancient times to the present day due to its abundance.\\n\\n- Slate - A metamorphic rock that splits into thin sheets, used for roofing, flooring and chalkboards.\\n\\n- Pumice - A volcanic rock with a very porous, lightweight texture useful for abrasives and filters.\\n\\nThe \"best\" really depends on what properties or applications you are looking for in a rock. Different rocks excel in different areas based on their mineral composition and formation process.', response_metadata={'id': 'msg_01CfzzW5TAw2XRDshZ9QQo5i', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 20, 'output_tokens': 261}}, id='run-33e4dd97-e64a-4311-b546-2e14abd07bc7-0'),\n",
" AIMessage(content=\"As a professional pirate, I'd say the best type of treasure is gold! Nothing quite matches the luster and value of a huge haul of gold doubloons, jewelry, and ornate goblets plundered from merchant ships or raided from royal galleons. Though jewels and pearls are nice too if you can get your hands on them. The real prize is finding those legendary hoards of ancient pirate gold that have been buried on remote islands for centuries just waiting to be dug up. A pirate's life is all about seeking that ultimate treasure that'll set you up permanently on a private island paradise! Arrrr!\", response_metadata={'id': 'msg_01FCJdiNfiFptcCySzLjubeq', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 22, 'output_tokens': 138}}, id='run-3b83de8b-dfcd-44a8-b269-87b7cbbdaf51-0')]"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from langchain_core.runnables import RunnableLambda\n",
"# now what if we want to invoke a step that has an output of a list?\n",
"def my_runnable(input):\n",
" if input == \"first\":\n",
" return my_list[0:2]\n",
" else:\n",
" return my_list[2:]\n",
"\n",
"\n",
"# pipe the output list into a batch function\n",
"chain = RunnableLambda(my_runnable) | chain.batch\n",
"chain.invoke(\"first\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"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.4"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

@ -3,10 +3,13 @@
{
"cell_type": "raw",
"id": "0bdb3b97-4989-4237-b43b-5943dbbd8302",
"metadata": {},
"metadata": {
"vscode": {
"languageId": "raw"
}
},
"source": [
"---\n",
"sidebar_position: 1.5\n",
"title: Streaming\n",
"---"
]

@ -117,6 +117,7 @@
{ type: "category", label: "Primitives", collapsed: true, items: [{ type: "autogenerated", dirName: "expression_language/primitives", }], link: { type: "doc", id: "expression_language/primitives/index" } },
"expression_language/why",
"expression_language/streaming",
"expression_language/lists",
"expression_language/how_to/message_history",
{
type: "category",

Loading…
Cancel
Save