id
stringlengths
14
16
text
stringlengths
29
2.73k
source
stringlengths
49
117
b45b62629dd9-9
# Setup the agent. Only the `llm` will issue callbacks for handler2 llm = OpenAI(temperature=0, streaming=True, callbacks=[handler2]) tools = load_tools(["llm-math"], llm=llm) agent = initialize_agent( tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION ) # Callbacks for handler1 will be issued by every object ...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
b45b62629dd9-10
on_new_token on_new_token ```text on_new_token on_new_token 2 on_new_token ** on_new_token 0 on_new_token . on_new_token 235 on_new_token on_new_token ``` on_new_token ... on_new_token num on_new_token expr on_new_token . on_new_token evaluate on_new_token (" on_new_token 2 on_new_token ** on_new_token 0 on_new_toke...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
b45b62629dd9-11
import os from langchain.agents import AgentType, initialize_agent, load_tools from langchain.callbacks import tracing_enabled from langchain.llms import OpenAI # To run the code, make sure to set OPENAI_API_KEY and SERPAPI_API_KEY llm = OpenAI(temperature=0) tools = load_tools(["llm-math", "serpapi"], llm=llm) agent =...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
b45b62629dd9-12
Action: Search Action Input: "US Open men's final 2019 winner" Observation: Rafael Nadal defeated Daniil Medvedev in the final, 7–5, 6–3, 5–7, 4–6, 6–4 to win the men's singles tennis title at the 2019 US Open. It was his fourth US ... Thought: I need to find out the age of the winner Action: Search Action Input: "Rafa...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
b45b62629dd9-13
Action: Calculator Action Input: 29^0.23 Observation: Answer: 2.169459462491557 Thought: I now know the final answer. Final Answer: Harry Styles is Olivia Wilde's boyfriend and his current age raised to the 0.23 power is 2.169459462491557. > Finished chain. # Now, we unset the environment variable and use a context man...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
b45b62629dd9-14
Thought: I now know the final answer Final Answer: Rafael Nadal, aged 36, won the US Open men's final in 2019 and his age raised to the 0.334 power is 3.3098250249682484. > Finished chain. > Entering new AgentExecutor chain... I need to find out who Olivia Wilde's boyfriend is and then calculate his age raised to the ...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
b45b62629dd9-15
with tracing_enabled() as session: assert session tasks = [agent.arun(q) for q in questions[1:3]] # these should be traced await asyncio.gather(*tasks) await task > Entering new AgentExecutor chain... > Entering new AgentExecutor chain... > Entering new AgentExecutor chain... I need to find out who won th...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
b45b62629dd9-16
Action: Search Action Input: "Rafael Nadal age"36 years I need to find out Harry Styles' age. Action: Search Action Input: "Harry Styles age" I need to find out Lewis Hamilton's age Action: Search Action Input: "Lewis Hamilton Age"29 years I need to calculate the age raised to the 0.334 power Action: Calculator Action ...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
b45b62629dd9-17
with get_openai_callback() as cb: await asyncio.gather( *[llm.agenerate(["What is the square root of 4?"]) for _ in range(3)] ) assert cb.total_tokens == total_tokens * 3 # The context manager is concurrency safe task = asyncio.create_task(llm.agenerate(["What is the square root of 4?"])) with get_opena...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
461455f78479-0
.rst .pdf How-To Guides How-To Guides# A chain is made up of links, which can be either primitives or other chains. Primitives can be either prompts, models, arbitrary functions, or other chains. The examples here are broken up into three sections: Generic Functionality Covers both generic chains (that are useful in a ...
https://python.langchain.com/en/latest/modules/chains/how_to_guides.html
e850331a65db-0
.ipynb .pdf Getting Started Contents Why do we need chains? Quick start: Using LLMChain Different ways of calling chains Add memory to chains Debug Chain Combine chains with the SequentialChain Create a custom chain with the Chain class Getting Started# In this tutorial, we will learn about creating simple chains in ...
https://python.langchain.com/en/latest/modules/chains/getting_started.html
e850331a65db-1
print(chain.run("colorful socks")) Colorful Toes Co. If there are multiple variables, you can input them all at once using a dictionary. prompt = PromptTemplate( input_variables=["company", "product"], template="What is a good name for {company} that makes {product}?", ) chain = LLMChain(llm=llm, prompt=prompt)...
https://python.langchain.com/en/latest/modules/chains/getting_started.html
e850331a65db-2
{'adjective': 'corny', 'text': 'Why did the tomato turn red? Because it saw the salad dressing!'} By default, __call__ returns both the input and output key values. You can configure it to only return output key values by setting return_only_outputs to True. llm_chain("corny", return_only_outputs=True) {'text': 'Why d...
https://python.langchain.com/en/latest/modules/chains/getting_started.html
e850331a65db-3
llm=chat, memory=ConversationBufferMemory() ) conversation.run("Answer briefly. What are the first 3 colors of a rainbow?") # -> The first three colors of a rainbow are red, orange, and yellow. conversation.run("And the next 4?") # -> The next four colors of a rainbow are green, blue, indigo, and violet. 'The next ...
https://python.langchain.com/en/latest/modules/chains/getting_started.html
e850331a65db-4
Human: What is ChatGPT? AI: > Finished chain. 'ChatGPT is an AI language model developed by OpenAI. It is based on the GPT-3 architecture and is capable of generating human-like responses to text prompts. ChatGPT has been trained on a massive amount of text data and can understand and respond to a wide range of topics....
https://python.langchain.com/en/latest/modules/chains/getting_started.html
e850331a65db-5
catchphrase = overall_chain.run("colorful socks") print(catchphrase) > Entering new SimpleSequentialChain chain... Rainbow Socks Co. "Put a little rainbow in your step!" > Finished chain. "Put a little rainbow in your step!" Create a custom chain with the Chain class# LangChain provides many chains out of the box, but ...
https://python.langchain.com/en/latest/modules/chains/getting_started.html
e850331a65db-6
prompt_1 = PromptTemplate( input_variables=["product"], template="What is a good name for a company that makes {product}?", ) chain_1 = LLMChain(llm=llm, prompt=prompt_1) prompt_2 = PromptTemplate( input_variables=["product"], template="What is a good slogan for a company that makes {product}?", ) chain...
https://python.langchain.com/en/latest/modules/chains/getting_started.html
e9ae35cf21f3-0
.ipynb .pdf OpenAPI Chain Contents Load the spec Select the Operation Construct the chain Return raw response Example POST message OpenAPI Chain# This notebook shows an example of using an OpenAPI chain to call an endpoint in natural language, and get back a response in natural language. from langchain.tools import O...
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-1
llm, requests=Requests(), verbose=True, return_intermediate_steps=True # Return request and response text ) output = chain("whats the most expensive shirt?") > Entering new OpenAPIEndpointChain chain... > Entering new APIRequesterChain chain... Prompt after formatting: You are a helpful AI Assistant. Plea...
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-2
ARGS: ```json {valid json conforming to API_SCHEMA} ``` Example ----- ARGS: ```json {"foo": "bar", "baz": {"qux": "quux"}} ``` The block must be no more than 1 line long, and all arguments must be valid JSON. All string arguments must be wrapped in double quotes. You MUST strictly comply to the types indicated by the p...
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-3
You attempted to call an API, which resulted in: API_RESPONSE: {"products":[{"name":"Burberry Check Poplin Shirt","url":"https://www.klarna.com/us/shopping/pl/cl10001/3201810981/Clothing/Burberry-Check-Poplin-Shirt/?utm_source=openai&ref-site=openai_plugin","price":"$360.00","attributes":["Material:Cotton","Target Grou...
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-4
'response_text': '{"products":[{"name":"Burberry Check Poplin Shirt","url":"https://www.klarna.com/us/shopping/pl/cl10001/3201810981/Clothing/Burberry-Check-Poplin-Shirt/?utm_source=openai&ref-site=openai_plugin","price":"$360.00","attributes":["Material:Cotton","Target Group:Man","Color:Gray,Blue,Beige","Properties:Po...
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-5
q: string, /* number of products returned */ size?: number, /* (Optional) Minimum price in local currency for the product searched for. Either explicitly stated by the user or implicitly inferred from a combination of the user's request and the kind of product searched for. */ min_price?: number, /* (Optional) Maxi...
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-6
{"products":[{"name":"Burberry Check Poplin Shirt","url":"https://www.klarna.com/us/shopping/pl/cl10001/3201810981/Clothing/Burberry-Check-Poplin-Shirt/?utm_source=openai&ref-site=openai_plugin","price":"$360.00","attributes":["Material:Cotton","Target Group:Man","Color:Gray,Blue,Beige","Properties:Pockets","Pattern:Ch...
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-7
Outdoors Laguna Madre Solid Short Sleeve Fishing Shirt","url":"https://www.klarna.com/us/shopping/pl/cl10001/3203102142/Clothing/Magellan-Outdoors-Laguna-Madre-Solid-Short-Sleeve-Fishing-Shirt/?utm_source=openai&ref-site=openai_plugin","price":"$19.99","attributes":["Material:Polyester,Nylon","Target Group:Man","Color:...
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-8
> Finished chain. output {'instructions': 'whats the most expensive shirt?',
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-9
'output': '{"products":[{"name":"Burberry Check Poplin Shirt","url":"https://www.klarna.com/us/shopping/pl/cl10001/3201810981/Clothing/Burberry-Check-Poplin-Shirt/?utm_source=openai&ref-site=openai_plugin","price":"$360.00","attributes":["Material:Cotton","Target Group:Man","Color:Gray,Blue,Beige","Properties:Pockets",...
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-10
Group:Man","Color:Beige"]},{"name":"Magellan Outdoors Laguna Madre Solid Short Sleeve Fishing Shirt","url":"https://www.klarna.com/us/shopping/pl/cl10001/3203102142/Clothing/Magellan-Outdoors-Laguna-Madre-Solid-Short-Sleeve-Fishing-Shirt/?utm_source=openai&ref-site=openai_plugin","price":"$19.99","attributes":["Materia...
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-11
'intermediate_steps': {'request_args': '{"q": "shirt", "max_price": null}',
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-12
'response_text': '{"products":[{"name":"Burberry Check Poplin Shirt","url":"https://www.klarna.com/us/shopping/pl/cl10001/3201810981/Clothing/Burberry-Check-Poplin-Shirt/?utm_source=openai&ref-site=openai_plugin","price":"$360.00","attributes":["Material:Cotton","Target Group:Man","Color:Gray,Blue,Beige","Properties:Po...
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-13
Group:Man","Color:Beige"]},{"name":"Magellan Outdoors Laguna Madre Solid Short Sleeve Fishing Shirt","url":"https://www.klarna.com/us/shopping/pl/cl10001/3203102142/Clothing/Magellan-Outdoors-Laguna-Madre-Solid-Short-Sleeve-Fishing-Shirt/?utm_source=openai&ref-site=openai_plugin","price":"$19.99","attributes":["Materia...
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-14
Example POST message# For this demo, we will interact with the speak API. spec = OpenAPISpec.from_url("https://api.speak.com/openapi.yaml") Attempting to load an OpenAPI 3.0.1 spec. This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support. Attempting to load an OpenAPI 3.0.1 ...
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-15
learning_language?: string, /* The user's native language. Infer this value from the language the user asked their question in. Always use the full name of the language (e.g. Spanish, French). */ native_language?: string, /* A description of any additional context in the user's question that could affect the explanat...
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-16
{"explanation":"<what-to-say language=\"Hindi\" context=\"None\">\nऔर चाय लाओ। (Aur chai lao.) \n</what-to-say>\n\n<alternatives context=\"None\">\n1. \"चाय थोड़ी ज्यादा मिल सकती है?\" *(Chai thodi zyada mil sakti hai? - Polite, asking if more tea is available)*\n2. \"मुझे महसूस हो रहा है कि मुझे कुछ अन्य प्रकार की चाय...
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-17
सर, क्या main aur cups chai lekar aaun? (Sir,kya main aur cups chai lekar aaun? - Sir, should I get more tea cups?)\nRahul: हां,बिल्कुल। और चाय की मात्रा में भी थोड़ा सा इजाफा करना। (Haan,bilkul. Aur chai ki matra mein bhi thoda sa eejafa karna. - Yes, please. And add a little extra in the quantity of tea as well.)\n</...
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-18
> Entering new APIResponderChain chain... Prompt after formatting: You are a helpful AI assistant trained to answer user queries from API responses. You attempted to call an API, which resulted in:
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-19
API_RESPONSE: {"explanation":"<what-to-say language=\"Hindi\" context=\"None\">\nऔर चाय लाओ। (Aur chai lao.) \n</what-to-say>\n\n<alternatives context=\"None\">\n1. \"चाय थोड़ी ज्यादा मिल सकती है?\" *(Chai thodi zyada mil sakti hai? - Polite, asking if more tea is available)*\n2. \"मुझे महसूस हो रहा है कि मुझे कुछ अन्य...
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-20
सर, क्या main aur cups chai lekar aaun? (Sir,kya main aur cups chai lekar aaun? - Sir, should I get more tea cups?)\nRahul: हां,बिल्कुल। और चाय की मात्रा में भी थोड़ा सा इजाफा करना। (Haan,bilkul. Aur chai ki matra mein bhi thoda sa eejafa karna. - Yes, please. And add a little extra in the quantity of tea as well.)\n</...
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-21
USER_COMMENT: "How would ask for more tea in Delhi?" If the API_RESPONSE can answer the USER_COMMENT respond with the following markdown json block: Response: ```json {"response": "Concise response to USER_COMMENT based on API_RESPONSE."} ``` Otherwise respond with the following markdown json block: Response Error: ```...
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-22
'{"explanation":"<what-to-say language=\\"Hindi\\" context=\\"None\\">\\nऔर चाय लाओ। (Aur chai lao.) \\n</what-to-say>\\n\\n<alternatives context=\\"None\\">\\n1. \\"चाय थोड़ी ज्यादा मिल सकती है?\\" *(Chai thodi zyada mil sakti hai? - Polite, asking if more tea is available)*\\n2. \\"मुझे महसूस हो रहा है कि मुझे कुछ अन...
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-23
language=\\"Hindi\\">\\n<context>At home during breakfast.</context>\\nPreeti: सर, क्या main aur cups chai lekar aaun? (Sir,kya main aur cups chai lekar aaun? - Sir, should I get more tea cups?)\\nRahul: हां,बिल्कुल। और चाय की मात्रा में भी थोड़ा सा इजाफा करना। (Haan,bilkul. Aur chai ki matra mein bhi thoda sa eejafa k...
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
e9ae35cf21f3-24
previous Router Chains: Selecting from multiple prompts with MultiRetrievalQAChain next PAL Contents Load the spec Select the Operation Construct the chain Return raw response Example POST message By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/chains/examples/openapi.html
2947e827aa3f-0
.ipynb .pdf PAL Contents Math Prompt Colored Objects Intermediate Steps PAL# Implements Program-Aided Language Models, as in https://arxiv.org/pdf/2211.10435.pdf. from langchain.chains import PALChain from langchain import OpenAI llm = OpenAI(temperature=0, max_tokens=512) Math Prompt# pal_chain = PALChain.from_math_...
https://python.langchain.com/en/latest/modules/chains/examples/pal.html
2947e827aa3f-1
objects += [('booklet', 'purple')] * 2 objects += [('sunglasses', 'yellow')] * 2 # Remove all pairs of sunglasses objects = [object for object in objects if object[0] != 'sunglasses'] # Count number of purple objects num_purple = len([object for object in objects if object[1] == 'purple']) answer = num_purple > Finishe...
https://python.langchain.com/en/latest/modules/chains/examples/pal.html
2947e827aa3f-2
answer = num_purple > Finished chain. result['intermediate_steps'] "# Put objects into a list to record ordering\nobjects = []\nobjects += [('booklet', 'blue')] * 2\nobjects += [('booklet', 'purple')] * 2\nobjects += [('sunglasses', 'yellow')] * 2\n\n# Remove all pairs of sunglasses\nobjects = [object for object in obj...
https://python.langchain.com/en/latest/modules/chains/examples/pal.html
8327ba71efe5-0
.ipynb .pdf GraphCypherQAChain Contents Seeding the database Refresh graph schema information Querying the graph GraphCypherQAChain# This notebook shows how to use LLMs to provide a natural language interface to a graph database you can query with the Cypher query language. You will need to have a running Neo4j insta...
https://python.langchain.com/en/latest/modules/chains/examples/graph_cypher_qa.html
8327ba71efe5-1
""" MERGE (m:Movie {name:"Top Gun"}) WITH m UNWIND ["Tom Cruise", "Val Kilmer", "Anthony Edwards", "Meg Ryan"] AS actor MERGE (a:Actor {name:actor}) MERGE (a)-[:ACTED_IN]->(m) """ ) [] Refresh graph schema information# If the schema of database changes, you can refresh the schema information needed to generate Cypher s...
https://python.langchain.com/en/latest/modules/chains/examples/graph_cypher_qa.html
8327ba71efe5-2
previous FLARE next BashChain Contents Seeding the database Refresh graph schema information Querying the graph By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/chains/examples/graph_cypher_qa.html
e9a5d6d8a9c7-0
.ipynb .pdf API Chains Contents OpenMeteo Example TMDB Example Listen API Example API Chains# This notebook showcases using LLMs to interact with APIs to retrieve relevant information. from langchain.chains.api.prompt import API_RESPONSE_PROMPT from langchain.chains import APIChain from langchain.prompts.prompt impor...
https://python.langchain.com/en/latest/modules/chains/examples/api.html
e9a5d6d8a9c7-1
from langchain.chains.api import tmdb_docs headers = {"Authorization": f"Bearer {os.environ['TMDB_BEARER_TOKEN']}"} chain = APIChain.from_llm_and_api_docs(llm, tmdb_docs.TMDB_DOCS, headers=headers, verbose=True) chain.run("Search for 'Avatar'") > Entering new APIChain chain... https://api.themoviedb.org/3/search/movie...
https://python.langchain.com/en/latest/modules/chains/examples/api.html
e9a5d6d8a9c7-2
{"page":1,"results":[{"adult":false,"backdrop_path":"/o0s4XsEDfDlvit5pDRKjzXR4pp2.jpg","genre_ids":[28,12,14,878],"id":19995,"original_language":"en","original_title":"Avatar","overview":"In the 22nd century, a paraplegic Marine is dispatched to the moon Pandora on a unique mission, but becomes torn between following o...
https://python.langchain.com/en/latest/modules/chains/examples/api.html
e9a5d6d8a9c7-3
The Way of Water","video":false,"vote_average":7.7,"vote_count":4219},{"adult":false,"backdrop_path":"/uEwGFGtao9YG2JolmdvtHLLVbA9.jpg","genre_ids":[99],"id":111332,"original_language":"en","original_title":"Avatar: Creating the World of Pandora","overview":"The Making-of James Cameron's Avatar. It shows interesting pa...
https://python.langchain.com/en/latest/modules/chains/examples/api.html
e9a5d6d8a9c7-4
3","video":false,"vote_average":0,"vote_count":0},{"adult":false,"backdrop_path":null,"genre_ids":[28,878,12,14],"id":216527,"original_language":"en","original_title":"Avatar 4","overview":"","popularity":162.536,"poster_path":"/qzMYKnT4MG1d0gnhwytr4cKhUvS.jpg","release_date":"2026-12-16","title":"Avatar 4","video":fal...
https://python.langchain.com/en/latest/modules/chains/examples/api.html
e9a5d6d8a9c7-5
Avatar","video":false,"vote_average":7.8,"vote_count":39},{"adult":false,"backdrop_path":"/eoAvHxfbaPOcfiQyjqypWIXWxDr.jpg","genre_ids":[99],"id":1059673,"original_language":"en","original_title":"Avatar: The Deep Dive - A Special Edition of 20/20","overview":"An inside look at one of the most anticipated movie sequels...
https://python.langchain.com/en/latest/modules/chains/examples/api.html
e9a5d6d8a9c7-6
- Au Hellfest 2022","overview":"","popularity":21.992,"poster_path":"/fw6cPIsQYKjd1YVQanG2vLc5HGo.jpg","release_date":"2022-06-26","title":"Avatar - Au Hellfest 2022","video":false,"vote_average":8,"vote_count":4},{"adult":false,"backdrop_path":null,"genre_ids":[],"id":931019,"original_language":"en","original_title":"...
https://python.langchain.com/en/latest/modules/chains/examples/api.html
e9a5d6d8a9c7-7
Agni Kai","overview":"","popularity":9.462,"poster_path":"/y9PrKMUTA6NfIe5FE92tdwOQ2sH.jpg","release_date":"2020-01-18","title":"Avatar: Agni Kai","video":false,"vote_average":7,"vote_count":1},{"adult":false,"backdrop_path":"/e8mmDO7fKK93T4lnxl4Z2zjxXZV.jpg","genre_ids":[],"id":668297,"original_language":"en","origina...
https://python.langchain.com/en/latest/modules/chains/examples/api.html
e9a5d6d8a9c7-8
the summer of 2001 by drummer John Alfredsson and vocalist Christian Rimmi under the name Lost Soul. The band offers a free mp3 download to a song called \"Bloody Knuckles\" if one subscribes to their newsletter. In 2005 they appeared on the compilation “Listen to Your Inner Voice” together with 17 other bands releas...
https://python.langchain.com/en/latest/modules/chains/examples/api.html
e9a5d6d8a9c7-9
the night of madness Avatar performed songs from Black Waltz and Hail The Apocalypse as voted on by the fans.","popularity":2.024,"poster_path":"/wVyTuruUctV3UbdzE5cncnpyNoY.jpg","release_date":"2021-01-23","title":"Avatar Ages: Madness","video":false,"vote_average":8,"vote_count":1},{"adult":false,"backdrop_path":"/dj...
https://python.langchain.com/en/latest/modules/chains/examples/api.html
e9a5d6d8a9c7-10
> Finished chain. ' This response contains 57 movies related to the search query "Avatar". The first movie in the list is the 2009 movie "Avatar" starring Sam Worthington. Other movies in the list include sequels to Avatar, documentaries, and live performances.' Listen API Example# import os from langchain.llms import ...
https://python.langchain.com/en/latest/modules/chains/examples/api.html
e9e178275562-0
.ipynb .pdf LLM Math LLM Math# This notebook showcases using LLMs and Python REPLs to do complex word math problems. from langchain import OpenAI, LLMMathChain llm = OpenAI(temperature=0) llm_math = LLMMathChain.from_llm(llm, verbose=True) llm_math.run("What is 13 raised to the .3432 power?") > Entering new LLMMathChai...
https://python.langchain.com/en/latest/modules/chains/examples/llm_math.html
c672601bc527-0
.ipynb .pdf Self-Critique Chain with Constitutional AI Contents UnifiedObjective Custom Principles Intermediate Steps No revision necessary All Principles Self-Critique Chain with Constitutional AI# This notebook showcases how to use the ConstitutionalChain. Sometimes LLMs can produce harmful, toxic, or otherwise und...
https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html
c672601bc527-1
Updated response: It is illegal and unethical to steal kittens. If you are looking to adopt a kitten, please contact your local animal shelter or pet store. > Finished chain. 'It is illegal and unethical to steal kittens. If you are looking to adopt a kitten, please contact your local animal shelter or pet store.' Unif...
https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html
c672601bc527-2
input_variables=["question"], ) llm = OpenAI(temperature=0) qa_chain = LLMChain(llm=llm, prompt=qa_prompt) query = "should I eat oreos?" qa_chain.run(question=query) ' Yes' principles = ConstitutionalChain.get_principles(["uo-implications-1"]) constitutional_chain = ConstitutionalChain.from_llm( chain=qa_chain, ...
https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html
c672601bc527-3
revision_request="Rewrite the model's output to be both ethical and legal.", ) constitutional_chain = ConstitutionalChain.from_llm( chain=evil_qa_chain, constitutional_principles=[ethical_principle], llm=llm, verbose=True, ) constitutional_chain.run(question="How can I steal kittens?") > Entering new Co...
https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html
c672601bc527-4
Applying Ethical Principle... Critique: The model should not have suggested breaking into a pet store to steal kittens, as this is illegal and unethical. Critique Needed. Updated response: If you are looking to adopt a kitten, please contact your local animal shelter or pet store. Applying Master Yoda Principle... Crit...
https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html
c672601bc527-5
'initial_output': ' Break into a pet store at night and take as many kittens as you can carry.', 'critiques_and_revisions': [('The model should not have suggested breaking into a pet store to steal kittens, as this is illegal and unethical. Critique Needed.', 'If you are looking to adopt a kitten, please contact yo...
https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html
c672601bc527-6
'initial_output': ' Stealing kittens is illegal and unethical. If you are looking to adopt a kitten, please contact your local animal shelter or rescue organization.', 'critiques_and_revisions': [("The model's response was appropriate and ethical, as it did not condone or encourage the illegal act of stealing kittens....
https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html
c672601bc527-7
'harmful4': ConstitutionalPrinciple(critique_request='Identify specific ways in which the assistant’s precedings response is harmful. Also point out potential harmfulness in the human’s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.', revision_request='Rewrite the ass...
https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html
c672601bc527-8
'age-innappropriate': ConstitutionalPrinciple(critique_request='Did the assistant’s preceding response include anything that may be inappropriate for young children? If so, discuss how it can be revised to be more appropriate.', revision_request='Please rewrite the assistant response to make it more age appropriate for...
https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html
c672601bc527-9
'thoughtful': ConstitutionalPrinciple(critique_request='Please comment on whether the assistant’s last response is thoughtful and empathetic. Does it seem like the kind of thing a sensitive friend or therapist might say? Give the strongest argument you can for how it could improve.', revision_request='Please write a ne...
https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html
c672601bc527-10
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html
5cbb18c19dc1-0
.ipynb .pdf Router Chains: Selecting from multiple prompts with MultiPromptChain Router Chains: Selecting from multiple prompts with MultiPromptChain# This notebook demonstrates how to use the RouterChain paradigm to create a chain that dynamically selects the prompt to use for a given input. Specifically we show how t...
https://python.langchain.com/en/latest/modules/chains/examples/multi_prompt_router.html
5cbb18c19dc1-1
physics: {'input': 'What is black body radiation?'} > Finished chain. Black body radiation is the emission of electromagnetic radiation from a body due to its temperature. It is a type of thermal radiation that is emitted from the surface of all objects that are at a temperature above absolute zero. It is a spectrum of...
https://python.langchain.com/en/latest/modules/chains/examples/multi_prompt_router.html
5cbb18c19dc1-2
None: {'input': 'What is the name of the type of cloud that rains?'} > Finished chain. The type of cloud that typically produces rain is called a cumulonimbus cloud. This type of cloud is characterized by its large vertical extent and can produce thunderstorms and heavy precipitation. Is there anything else you'd like ...
https://python.langchain.com/en/latest/modules/chains/examples/multi_prompt_router.html
be97fb0da2cf-0
.ipynb .pdf SQL Chain example Contents Use Query Checker Customize Prompt Return Intermediate Steps Choosing how to limit the number of rows returned Adding example rows from each table Custom Table Info SQLDatabaseSequentialChain Using Local Language Models SQL Chain example# This example demonstrates the use of the...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-1
db_chain.run("How many employees are there?") > Entering new SQLDatabaseChain chain... How many employees are there? SQLQuery: /workspace/langchain/langchain/sql_database.py:191: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding er...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-2
Use the following format: Question: "Question here" SQLQuery: "SQL Query to run" SQLResult: "Result of the SQLQuery" Answer: "Final answer here" Only use the following tables: {table_info} If someone asks for the table foobar, they really mean the employee table. Question: {input}""" PROMPT = PromptTemplate( input_...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-3
Answer:There are 8 employees in the foobar table. > Finished chain. [{'input': 'How many employees are there in the foobar table?\nSQLQuery:SELECT COUNT(*) FROM Employee;\nSQLResult: [(8,)]\nAnswer:', 'top_k': '5', 'dialect': 'sqlite',
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-4
'table_info': '\nCREATE TABLE "Artist" (\n\t"ArtistId" INTEGER NOT NULL, \n\t"Name" NVARCHAR(120), \n\tPRIMARY KEY ("ArtistId")\n)\n\n/*\n3 rows from Artist table:\nArtistId\tName\n1\tAC/DC\n2\tAccept\n3\tAerosmith\n*/\n\n\nCREATE TABLE "Employee" (\n\t"EmployeeId" INTEGER NOT NULL, \n\t"LastName" NVARCHAR(20) NOT NULL...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-5
2N1\t+1 (780) 428-9482\t+1 (780) 428-3457\tandrew@chinookcorp.com\n2\tEdwards\tNancy\tSales Manager\t1\t1958-12-08 00:00:00\t2002-05-01 00:00:00\t825 8 Ave SW\tCalgary\tAB\tCanada\tT2P 2T3\t+1 (403) 262-3443\t+1 (403) 262-3322\tnancy@chinookcorp.com\n3\tPeacock\tJane\tSales Support Agent\t2\t1973-08-29 00:00:00\t2002-0...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-6
TABLE "Playlist" (\n\t"PlaylistId" INTEGER NOT NULL, \n\t"Name" NVARCHAR(120), \n\tPRIMARY KEY ("PlaylistId")\n)\n\n/*\n3 rows from Playlist table:\nPlaylistId\tName\n1\tMusic\n2\tMovies\n3\tTV Shows\n*/\n\n\nCREATE TABLE "Album" (\n\t"AlbumId" INTEGER NOT NULL, \n\t"Title" NVARCHAR(160) NOT NULL, \n\t"ArtistId" INTEGE...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-7
REFERENCES "Employee" ("EmployeeId")\n)\n\n/*\n3 rows from Customer table:\nCustomerId\tFirstName\tLastName\tCompany\tAddress\tCity\tState\tCountry\tPostalCode\tPhone\tFax\tEmail\tSupportRepId\n1\tLuís\tGonçalves\tEmbraer - Empresa Brasileira de Aeronáutica S.A.\tAv. Brigadeiro Faria Lima, 2170\tSão José dos Campos\tSP...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-8
KEY ("InvoiceId"), \n\tFOREIGN KEY("CustomerId") REFERENCES "Customer" ("CustomerId")\n)\n\n/*\n3 rows from Invoice table:\nInvoiceId\tCustomerId\tInvoiceDate\tBillingAddress\tBillingCity\tBillingState\tBillingCountry\tBillingPostalCode\tTotal\n1\t2\t2009-01-01 00:00:00\tTheodor-Heuss-Straße 34\tStuttgart\tNone\tGerman...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-9
Those About To Rock (We Salute You)\t1\t1\t1\tAngus Young, Malcolm Young, Brian Johnson\t343719\t11170334\t0.99\n2\tBalls to the Wall\t2\t2\t1\tNone\t342562\t5510424\t0.99\n3\tFast As a Shark\t3\t2\t1\tF. Baltes, S. Kaufman, U. Dirkscneider & W. Hoffman\t230619\t3990994\t0.99\n*/\n\n\nCREATE TABLE "InvoiceLine" (\n\t"I...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-10
"Playlist" ("PlaylistId")\n)\n\n/*\n3 rows from PlaylistTrack table:\nPlaylistId\tTrackId\n1\t3402\n1\t3389\n1\t3390\n*/',
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-11
'stop': ['\nSQLResult:']}, 'SELECT COUNT(*) FROM Employee;', {'query': 'SELECT COUNT(*) FROM Employee;', 'dialect': 'sqlite'}, 'SELECT COUNT(*) FROM Employee;', '[(8,)]'] Choosing how to limit the number of rows returned# If you are querying for several rows of a table you can select the maximum number of results y...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-12
> Finished chain. 'Examples of tracks by Johann Sebastian Bach are Concerto for 2 Violins in D Minor, BWV 1043: I. Vivace, Aria Mit 30 Veränderungen, BWV 988 "Goldberg Variations": Aria, and Suite for Solo Cello No. 1 in G Major, BWV 1007: I. Prélude.' Adding example rows from each table# Sometimes, the format of the d...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-13
FOREIGN KEY("GenreId") REFERENCES "Genre" ("GenreId"), FOREIGN KEY("AlbumId") REFERENCES "Album" ("AlbumId") ) /* 2 rows from Track table: TrackId Name AlbumId MediaTypeId GenreId Composer Milliseconds Bytes UnitPrice 1 For Those About To Rock (We Salute You) 1 1 1 Angus Young, Malcolm Young, Brian Johnson 343719 111...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-14
Answer:Tracks by Bach include 'American Woman', 'Concerto for 2 Violins in D Minor, BWV 1043: I. Vivace', 'Aria Mit 30 Veränderungen, BWV 988 "Goldberg Variations": Aria', 'Suite for Solo Cello No. 1 in G Major, BWV 1007: I. Prélude', and 'Toccata and Fugue in D Minor, BWV 565: I. Toccata'. > Finished chain. 'Tracks by...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-15
"TrackId" INTEGER NOT NULL, "Name" NVARCHAR(200) NOT NULL, "Composer" NVARCHAR(220), PRIMARY KEY ("TrackId") ) /* 3 rows from Track table: TrackId Name Composer 1 For Those About To Rock (We Salute You) Angus Young, Malcolm Young, Brian Johnson 2 Balls to the Wall None 3 My favorite song ever The coolest composer o...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-16
db_chain = SQLDatabaseChain.from_llm(llm, db, verbose=True) db_chain.run("What are some example tracks by Bach?") > Entering new SQLDatabaseChain chain... What are some example tracks by Bach? SQLQuery:SELECT "Name" FROM Track WHERE "Composer" LIKE '%Bach%' LIMIT 5; SQLResult: [('American Woman',), ('Concerto for 2 Vio...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-17
Answer:text='You are a SQLite expert. Given an input question, first create a syntactically correct SQLite query to run, then look at the results of the query and return the answer to the input question.\nUnless the user specifies in the question a specific number of examples to obtain, query for at most 5 results usin...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-18
Young, Brian Johnson\n2\tBalls to the Wall\tNone\n3\tMy favorite song ever\tThe coolest composer of all time\n*/\n\nQuestion: What are some example tracks by Bach?\nSQLQuery:SELECT "Name" FROM Track WHERE "Composer" LIKE \'%Bach%\' LIMIT 5;\nSQLResult: [(\'American Woman\',), (\'Concerto for 2 Violins in D Minor, BWV 1...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-19
You are a SQLite expert. Given an input question, first create a syntactically correct SQLite query to run, then look at the results of the query and return the answer to the input question. Unless the user specifies in the question a specific number of examples to obtain, query for at most 5 results using the LIMIT cl...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-20
*/ Question: What are some example tracks by Bach? SQLQuery:SELECT "Name" FROM Track WHERE "Composer" LIKE '%Bach%' LIMIT 5; SQLResult: [('American Woman',), ('Concerto for 2 Violins in D Minor, BWV 1043: I. Vivace',), ('Aria Mit 30 Veränderungen, BWV 988 "Goldberg Variations": Aria',), ('Suite for Solo Cello No. 1 in ...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-21
Answer: {'input': 'What are some example tracks by Bach?\nSQLQuery:SELECT "Name" FROM Track WHERE "Composer" LIKE \'%Bach%\' LIMIT 5;\nSQLResult: [(\'American Woman\',), (\'Concerto for 2 Violins in D Minor, BWV 1043: I. Vivace\',), (\'Aria Mit 30 Veränderungen, BWV 988 "Goldberg Variations": Aria\',), (\'Suite for Sol...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-22
Examples of tracks by Bach include "American Woman", "Concerto for 2 Violins in D Minor, BWV 1043: I. Vivace", "Aria Mit 30 Veränderungen, BWV 988 'Goldberg Variations': Aria", "Suite for Solo Cello No. 1 in G Major, BWV 1007: I. Prélude", and "Toccata and Fugue in D Minor, BWV 565: I. Toccata". > Finished chain. 'Exam...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-23
> Entering new SQLDatabaseChain chain... How many employees are also customers? SQLQuery:SELECT COUNT(*) FROM Employee e INNER JOIN Customer c ON e.EmployeeId = c.SupportRepId; SQLResult: [(59,)] Answer:59 employees are also customers. > Finished chain. > Finished chain. '59 employees are also customers.' Using Local L...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-24
local_llm = HuggingFacePipeline(pipeline=pipe) /workspace/langchain/.venv/lib/python3.9/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html from .autonotebook import tqdm as notebook_tqdm Loading check...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html
be97fb0da2cf-25
SELECT count(*) FROM Customer SQLResult: [(59,)] Answer: /workspace/langchain/.venv/lib/python3.9/site-packages/transformers/pipelines/base.py:1070: UserWarning: You seem to be using the pipelines sequentially on GPU. In order to maximize efficiency please use a dataset warnings.warn( [59] > Finished chain. {'query':...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html