id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
11a2e7329284-4
Current conversation: 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. It is often used for chatbots, virtual assistants, and other conversational AI applications.' Combine chains with the SequentialChain# The next step after calling a language model is to make a series of calls to a language model. We can do this using sequential chains, which are chains that execute their links in a predefined order. Specifically, we will use the SimpleSequentialChain. This is the simplest type of a sequential chain, where each step has a single input/output, and the output of one step is the input to the next. In this tutorial, our sequential chain will: First, create a company name for a product. We will reuse the LLMChain we’d previously initialized to create this company name. Then, create a catchphrase for the product. We will initialize a new LLMChain to create this catchphrase, as shown below. second_prompt = PromptTemplate( input_variables=["company_name"], template="Write a catchphrase for the following company: {company_name}", ) chain_two = LLMChain(llm=llm, prompt=second_prompt) Now we can combine the two LLMChains, so that we can create a company name and a catchphrase in a single step. from langchain.chains import SimpleSequentialChain overall_chain = SimpleSequentialChain(chains=[chain, chain_two], verbose=True) # Run the chain specifying only the input variable for the first chain. catchphrase = overall_chain.run("colorful socks") print(catchphrase)
https://python.langchain.com/en/latest/modules/chains/getting_started.html
11a2e7329284-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 sometimes you may want to create a custom chain for your specific use case. For this example, we will create a custom chain that concatenates the outputs of 2 LLMChains. In order to create a custom chain: Start by subclassing the Chain class, Fill out the input_keys and output_keys properties, Add the _call method that shows how to execute the chain. These steps are demonstrated in the example below: from langchain.chains import LLMChain from langchain.chains.base import Chain from typing import Dict, List class ConcatenateChain(Chain): chain_1: LLMChain chain_2: LLMChain @property def input_keys(self) -> List[str]: # Union of the input keys of the two chains. all_input_vars = set(self.chain_1.input_keys).union(set(self.chain_2.input_keys)) return list(all_input_vars) @property def output_keys(self) -> List[str]: return ['concat_output'] def _call(self, inputs: Dict[str, str]) -> Dict[str, str]: output_1 = self.chain_1.run(inputs) output_2 = self.chain_2.run(inputs) return {'concat_output': output_1 + output_2} Now, we can try running the chain that we called. prompt_1 = PromptTemplate( input_variables=["product"],
https://python.langchain.com/en/latest/modules/chains/getting_started.html
11a2e7329284-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_2 = LLMChain(llm=llm, prompt=prompt_2) concat_chain = ConcatenateChain(chain_1=chain_1, chain_2=chain_2) concat_output = concat_chain.run("colorful socks") print(f"Concatenated output:\n{concat_output}") Concatenated output: Funky Footwear Company "Brighten Up Your Day with Our Colorful Socks!" That’s it! For more details about how to do cool things with Chains, check out the how-to guide for chains. previous Chains next How-To Guides 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 By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/chains/getting_started.html
d02a5dc3cc5b-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 wide variety of applications) as well as generic functionality related to those chains. Async API for Chain Creating a custom Chain Loading from LangChainHub LLM Chain Additional ways of running LLM Chain Parsing the outputs Initialize from string Router Chains Sequential Chains Serialization Transformation Chain Index-related Chains Chains related to working with indexes. Analyze Document Chat Over Documents with Chat History Graph QA Hypothetical Document Embeddings Question Answering with Sources Question Answering Summarization Retrieval Question/Answering Retrieval Question Answering with Sources Vector DB Text Generation All other chains All other types of chains! API Chains Self-Critique Chain with Constitutional AI FLARE GraphCypherQAChain BashChain LLMCheckerChain LLM Math LLMRequestsChain LLMSummarizationCheckerChain Moderation Router Chains: Selecting from multiple prompts with MultiPromptChain Router Chains: Selecting from multiple prompts with MultiRetrievalQAChain OpenAPI Chain PAL SQL Chain example previous Getting Started next Async API for Chain By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/chains/how_to_guides.html
3e0c50dbea64-0
.ipynb .pdf Transformation Chain Transformation Chain# This notebook showcases using a generic transformation chain. As an example, we will create a dummy transformation that takes in a super long text, filters the text to only the first 3 paragraphs, and then passes that into an LLMChain to summarize those. from langchain.chains import TransformChain, LLMChain, SimpleSequentialChain from langchain.llms import OpenAI from langchain.prompts import PromptTemplate with open("../../state_of_the_union.txt") as f: state_of_the_union = f.read() def transform_func(inputs: dict) -> dict: text = inputs["text"] shortened_text = "\n\n".join(text.split("\n\n")[:3]) return {"output_text": shortened_text} transform_chain = TransformChain(input_variables=["text"], output_variables=["output_text"], transform=transform_func) template = """Summarize this text: {output_text} Summary:""" prompt = PromptTemplate(input_variables=["output_text"], template=template) llm_chain = LLMChain(llm=OpenAI(), prompt=prompt) sequential_chain = SimpleSequentialChain(chains=[transform_chain, llm_chain]) sequential_chain.run(state_of_the_union) ' The speaker addresses the nation, noting that while last year they were kept apart due to COVID-19, this year they are together again. They are reminded that regardless of their political affiliations, they are all Americans.' previous Serialization next Analyze Document By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/chains/generic/transformation.html
e8a8ec72634a-0
.ipynb .pdf Sequential Chains Contents SimpleSequentialChain Sequential Chain Memory in Sequential Chains Sequential Chains# The next step after calling a language model is make a series of calls to a language model. This is particularly useful when you want to take the output from one call and use it as the input to another. In this notebook we will walk through some examples for how to do this, using sequential chains. Sequential chains are defined as a series of chains, called in deterministic order. There are two types of sequential chains: SimpleSequentialChain: The simplest form of sequential chains, where each step has a singular input/output, and the output of one step is the input to the next. SequentialChain: A more general form of sequential chains, allowing for multiple inputs/outputs. SimpleSequentialChain# In this series of chains, each individual chain has a single input and a single output, and the output of one step is used as input to the next. Let’s walk through a toy example of doing this, where the first chain takes in the title of an imaginary play and then generates a synopsis for that title, and the second chain takes in the synopsis of that play and generates an imaginary review for that play. from langchain.llms import OpenAI from langchain.chains import LLMChain from langchain.prompts import PromptTemplate # This is an LLMChain to write a synopsis given a title of a play. llm = OpenAI(temperature=.7) template = """You are a playwright. Given the title of play, it is your job to write a synopsis for that title. Title: {title} Playwright: This is a synopsis for the above play:""" prompt_template = PromptTemplate(input_variables=["title"], template=template) synopsis_chain = LLMChain(llm=llm, prompt=prompt_template)
https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html
e8a8ec72634a-1
synopsis_chain = LLMChain(llm=llm, prompt=prompt_template) # This is an LLMChain to write a review of a play given a synopsis. llm = OpenAI(temperature=.7) template = """You are a play critic from the New York Times. Given the synopsis of play, it is your job to write a review for that play. Play Synopsis: {synopsis} Review from a New York Times play critic of the above play:""" prompt_template = PromptTemplate(input_variables=["synopsis"], template=template) review_chain = LLMChain(llm=llm, prompt=prompt_template) # This is the overall chain where we run these two chains in sequence. from langchain.chains import SimpleSequentialChain overall_chain = SimpleSequentialChain(chains=[synopsis_chain, review_chain], verbose=True) review = overall_chain.run("Tragedy at sunset on the beach") > Entering new SimpleSequentialChain chain... Tragedy at Sunset on the Beach is a story of a young couple, Jack and Sarah, who are in love and looking forward to their future together. On the night of their anniversary, they decide to take a walk on the beach at sunset. As they are walking, they come across a mysterious figure, who tells them that their love will be tested in the near future. The figure then tells the couple that the sun will soon set, and with it, a tragedy will strike. If Jack and Sarah can stay together and pass the test, they will be granted everlasting love. However, if they fail, their love will be lost forever.
https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html
e8a8ec72634a-2
The play follows the couple as they struggle to stay together and battle the forces that threaten to tear them apart. Despite the tragedy that awaits them, they remain devoted to one another and fight to keep their love alive. In the end, the couple must decide whether to take a chance on their future together or succumb to the tragedy of the sunset. Tragedy at Sunset on the Beach is an emotionally gripping story of love, hope, and sacrifice. Through the story of Jack and Sarah, the audience is taken on a journey of self-discovery and the power of love to overcome even the greatest of obstacles. The play's talented cast brings the characters to life, allowing us to feel the depths of their emotion and the intensity of their struggle. With its compelling story and captivating performances, this play is sure to draw in audiences and leave them on the edge of their seats. The play's setting of the beach at sunset adds a touch of poignancy and romanticism to the story, while the mysterious figure serves to keep the audience enthralled. Overall, Tragedy at Sunset on the Beach is an engaging and thought-provoking play that is sure to leave audiences feeling inspired and hopeful. > Finished chain. print(review) Tragedy at Sunset on the Beach is an emotionally gripping story of love, hope, and sacrifice. Through the story of Jack and Sarah, the audience is taken on a journey of self-discovery and the power of love to overcome even the greatest of obstacles. The play's talented cast brings the characters to life, allowing us to feel the depths of their emotion and the intensity of their struggle. With its compelling story and captivating performances, this play is sure to draw in audiences and leave them on the edge of their seats.
https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html
e8a8ec72634a-3
The play's setting of the beach at sunset adds a touch of poignancy and romanticism to the story, while the mysterious figure serves to keep the audience enthralled. Overall, Tragedy at Sunset on the Beach is an engaging and thought-provoking play that is sure to leave audiences feeling inspired and hopeful. Sequential Chain# Of course, not all sequential chains will be as simple as passing a single string as an argument and getting a single string as output for all steps in the chain. In this next example, we will experiment with more complex chains that involve multiple inputs, and where there also multiple final outputs. Of particular importance is how we name the input/output variable names. In the above example we didn’t have to think about that because we were just passing the output of one chain directly as input to the next, but here we do have worry about that because we have multiple inputs. # This is an LLMChain to write a synopsis given a title of a play and the era it is set in. llm = OpenAI(temperature=.7) template = """You are a playwright. Given the title of play and the era it is set in, it is your job to write a synopsis for that title. Title: {title} Era: {era} Playwright: This is a synopsis for the above play:""" prompt_template = PromptTemplate(input_variables=["title", 'era'], template=template) synopsis_chain = LLMChain(llm=llm, prompt=prompt_template, output_key="synopsis") # This is an LLMChain to write a review of a play given a synopsis. llm = OpenAI(temperature=.7) template = """You are a play critic from the New York Times. Given the synopsis of play, it is your job to write a review for that play. Play Synopsis: {synopsis}
https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html
e8a8ec72634a-4
Play Synopsis: {synopsis} Review from a New York Times play critic of the above play:""" prompt_template = PromptTemplate(input_variables=["synopsis"], template=template) review_chain = LLMChain(llm=llm, prompt=prompt_template, output_key="review") # This is the overall chain where we run these two chains in sequence. from langchain.chains import SequentialChain overall_chain = SequentialChain( chains=[synopsis_chain, review_chain], input_variables=["era", "title"], # Here we return multiple variables output_variables=["synopsis", "review"], verbose=True) overall_chain({"title":"Tragedy at sunset on the beach", "era": "Victorian England"}) > Entering new SequentialChain chain... > Finished chain. {'title': 'Tragedy at sunset on the beach', 'era': 'Victorian England',
https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html
e8a8ec72634a-5
'era': 'Victorian England', 'synopsis': "\n\nThe play follows the story of John, a young man from a wealthy Victorian family, who dreams of a better life for himself. He soon meets a beautiful young woman named Mary, who shares his dream. The two fall in love and decide to elope and start a new life together.\n\nOn their journey, they make their way to a beach at sunset, where they plan to exchange their vows of love. Unbeknownst to them, their plans are overheard by John's father, who has been tracking them. He follows them to the beach and, in a fit of rage, confronts them. \n\nA physical altercation ensues, and in the struggle, John's father accidentally stabs Mary in the chest with his sword. The two are left in shock and disbelief as Mary dies in John's arms, her last words being a declaration of her love for him.\n\nThe tragedy of the play comes to a head when John, broken and with no hope of a future, chooses to take his own life by jumping off the cliffs into the sea below. \n\nThe play is a powerful story of love, hope, and loss set against the backdrop of 19th century England.",
https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html
e8a8ec72634a-6
'review': "\n\nThe latest production from playwright X is a powerful and heartbreaking story of love and loss set against the backdrop of 19th century England. The play follows John, a young man from a wealthy Victorian family, and Mary, a beautiful young woman with whom he falls in love. The two decide to elope and start a new life together, and the audience is taken on a journey of hope and optimism for the future.\n\nUnfortunately, their dreams are cut short when John's father discovers them and in a fit of rage, fatally stabs Mary. The tragedy of the play is further compounded when John, broken and without hope, takes his own life. The storyline is not only realistic, but also emotionally compelling, drawing the audience in from start to finish.\n\nThe acting was also commendable, with the actors delivering believable and nuanced performances. The playwright and director have successfully crafted a timeless tale of love and loss that will resonate with audiences for years to come. Highly recommended."} Memory in Sequential Chains# Sometimes you may want to pass along some context to use in each step of the chain or in a later part of the chain, but maintaining and chaining together the input/output variables can quickly get messy. Using SimpleMemory is a convenient way to do manage this and clean up your chains. For example, using the previous playwright SequentialChain, lets say you wanted to include some context about date, time and location of the play, and using the generated synopsis and review, create some social media post text. You could add these new context variables as input_variables, or we can add a SimpleMemory to the chain to manage this context: from langchain.chains import SequentialChain from langchain.memory import SimpleMemory llm = OpenAI(temperature=.7)
https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html
e8a8ec72634a-7
from langchain.memory import SimpleMemory llm = OpenAI(temperature=.7) template = """You are a social media manager for a theater company. Given the title of play, the era it is set in, the date,time and location, the synopsis of the play, and the review of the play, it is your job to write a social media post for that play. Here is some context about the time and location of the play: Date and Time: {time} Location: {location} Play Synopsis: {synopsis} Review from a New York Times play critic of the above play: {review} Social Media Post: """ prompt_template = PromptTemplate(input_variables=["synopsis", "review", "time", "location"], template=template) social_chain = LLMChain(llm=llm, prompt=prompt_template, output_key="social_post_text") overall_chain = SequentialChain( memory=SimpleMemory(memories={"time": "December 25th, 8pm PST", "location": "Theater in the Park"}), chains=[synopsis_chain, review_chain, social_chain], input_variables=["era", "title"], # Here we return multiple variables output_variables=["social_post_text"], verbose=True) overall_chain({"title":"Tragedy at sunset on the beach", "era": "Victorian England"}) > Entering new SequentialChain chain... > Finished chain. {'title': 'Tragedy at sunset on the beach', 'era': 'Victorian England', 'time': 'December 25th, 8pm PST', 'location': 'Theater in the Park',
https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html
e8a8ec72634a-8
'location': 'Theater in the Park', 'social_post_text': "\nSpend your Christmas night with us at Theater in the Park and experience the heartbreaking story of love and loss that is 'A Walk on the Beach'. Set in Victorian England, this romantic tragedy follows the story of Frances and Edward, a young couple whose love is tragically cut short. Don't miss this emotional and thought-provoking production that is sure to leave you in tears. #AWalkOnTheBeach #LoveAndLoss #TheaterInThePark #VictorianEngland"} previous Router Chains next Serialization Contents SimpleSequentialChain Sequential Chain Memory in Sequential Chains By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html
d63b362400a4-0
.ipynb .pdf LLM Chain Contents LLM Chain Additional ways of running LLM Chain Parsing the outputs Initialize from string LLM Chain# LLMChain is perhaps one of the most popular ways of querying an LLM object. It formats the prompt template using the input key values provided (and also memory key values, if available), passes the formatted string to LLM and returns the LLM output. Below we show additional functionalities of LLMChain class. from langchain import PromptTemplate, OpenAI, LLMChain prompt_template = "What is a good name for a company that makes {product}?" llm = OpenAI(temperature=0) llm_chain = LLMChain( llm=llm, prompt=PromptTemplate.from_template(prompt_template) ) llm_chain("colorful socks") {'product': 'colorful socks', 'text': '\n\nSocktastic!'} Additional ways of running LLM Chain# Aside from __call__ and run methods shared by all Chain object (see Getting Started to learn more), LLMChain offers a few more ways of calling the chain logic: apply allows you run the chain against a list of inputs: input_list = [ {"product": "socks"}, {"product": "computer"}, {"product": "shoes"} ] llm_chain.apply(input_list) [{'text': '\n\nSocktastic!'}, {'text': '\n\nTechCore Solutions.'}, {'text': '\n\nFootwear Factory.'}] generate is similar to apply, except it return an LLMResult instead of string. LLMResult often contains useful generation such as token usages and finish reason. llm_chain.generate(input_list)
https://python.langchain.com/en/latest/modules/chains/generic/llm_chain.html
d63b362400a4-1
llm_chain.generate(input_list) LLMResult(generations=[[Generation(text='\n\nSocktastic!', generation_info={'finish_reason': 'stop', 'logprobs': None})], [Generation(text='\n\nTechCore Solutions.', generation_info={'finish_reason': 'stop', 'logprobs': None})], [Generation(text='\n\nFootwear Factory.', generation_info={'finish_reason': 'stop', 'logprobs': None})]], llm_output={'token_usage': {'prompt_tokens': 36, 'total_tokens': 55, 'completion_tokens': 19}, 'model_name': 'text-davinci-003'}) predict is similar to run method except that the input keys are specified as keyword arguments instead of a Python dict. # Single input example llm_chain.predict(product="colorful socks") '\n\nSocktastic!' # Multiple inputs example template = """Tell me a {adjective} joke about {subject}.""" prompt = PromptTemplate(template=template, input_variables=["adjective", "subject"]) llm_chain = LLMChain(prompt=prompt, llm=OpenAI(temperature=0)) llm_chain.predict(adjective="sad", subject="ducks") '\n\nQ: What did the duck say when his friend died?\nA: Quack, quack, goodbye.' Parsing the outputs# By default, LLMChain does not parse the output even if the underlying prompt object has an output parser. If you would like to apply that output parser on the LLM output, use predict_and_parse instead of predict and apply_and_parse instead of apply. With predict: from langchain.output_parsers import CommaSeparatedListOutputParser output_parser = CommaSeparatedListOutputParser() template = """List all the colors in a rainbow"""
https://python.langchain.com/en/latest/modules/chains/generic/llm_chain.html
d63b362400a4-2
template = """List all the colors in a rainbow""" prompt = PromptTemplate(template=template, input_variables=[], output_parser=output_parser) llm_chain = LLMChain(prompt=prompt, llm=llm) llm_chain.predict() '\n\nRed, orange, yellow, green, blue, indigo, violet' With predict_and_parser: llm_chain.predict_and_parse() ['Red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'] Initialize from string# You can also construct an LLMChain from a string template directly. template = """Tell me a {adjective} joke about {subject}.""" llm_chain = LLMChain.from_string(llm=llm, template=template) llm_chain.predict(adjective="sad", subject="ducks") '\n\nQ: What did the duck say when his friend died?\nA: Quack, quack, goodbye.' previous Loading from LangChainHub next Router Chains Contents LLM Chain Additional ways of running LLM Chain Parsing the outputs Initialize from string By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/chains/generic/llm_chain.html
bd9631a98ec2-0
.ipynb .pdf Loading from LangChainHub Loading from LangChainHub# This notebook covers how to load chains from LangChainHub. from langchain.chains import load_chain chain = load_chain("lc://chains/llm-math/chain.json") chain.run("whats 2 raised to .12") > Entering new LLMMathChain chain... whats 2 raised to .12 Answer: 1.0791812460476249 > Finished chain. 'Answer: 1.0791812460476249' Sometimes chains will require extra arguments that were not serialized with the chain. For example, a chain that does question answering over a vector database will require a vector database. from langchain.embeddings.openai import OpenAIEmbeddings from langchain.vectorstores import Chroma from langchain.text_splitter import CharacterTextSplitter from langchain import OpenAI, VectorDBQA from langchain.document_loaders import TextLoader loader = TextLoader('../../state_of_the_union.txt') documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) texts = text_splitter.split_documents(documents) embeddings = OpenAIEmbeddings() vectorstore = Chroma.from_documents(texts, embeddings) Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient. chain = load_chain("lc://chains/vector-db-qa/stuff/chain.json", vectorstore=vectorstore) query = "What did the president say about Ketanji Brown Jackson" chain.run(query)
https://python.langchain.com/en/latest/modules/chains/generic/from_hub.html
bd9631a98ec2-1
query = "What did the president say about Ketanji Brown Jackson" chain.run(query) " The president said that Ketanji Brown Jackson is a Circuit Court of Appeals Judge, one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans, and will continue Justice Breyer's legacy of excellence." previous Creating a custom Chain next LLM Chain By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/chains/generic/from_hub.html
7a0cac2281f3-0
.ipynb .pdf Async API for Chain Async API for Chain# LangChain provides async support for Chains by leveraging the asyncio library. Async methods are currently supported in LLMChain (through arun, apredict, acall) and LLMMathChain (through arun and acall), ChatVectorDBChain, and QA chains. Async support for other chains is on the roadmap. import asyncio import time from langchain.llms import OpenAI from langchain.prompts import PromptTemplate from langchain.chains import LLMChain def generate_serially(): llm = OpenAI(temperature=0.9) prompt = PromptTemplate( input_variables=["product"], template="What is a good name for a company that makes {product}?", ) chain = LLMChain(llm=llm, prompt=prompt) for _ in range(5): resp = chain.run(product="toothpaste") print(resp) async def async_generate(chain): resp = await chain.arun(product="toothpaste") print(resp) async def generate_concurrently(): llm = OpenAI(temperature=0.9) prompt = PromptTemplate( input_variables=["product"], template="What is a good name for a company that makes {product}?", ) chain = LLMChain(llm=llm, prompt=prompt) tasks = [async_generate(chain) for _ in range(5)] await asyncio.gather(*tasks) s = time.perf_counter() # If running this outside of Jupyter, use asyncio.run(generate_concurrently()) await generate_concurrently() elapsed = time.perf_counter() - s
https://python.langchain.com/en/latest/modules/chains/generic/async_chain.html
7a0cac2281f3-1
await generate_concurrently() elapsed = time.perf_counter() - s print('\033[1m' + f"Concurrent executed in {elapsed:0.2f} seconds." + '\033[0m') s = time.perf_counter() generate_serially() elapsed = time.perf_counter() - s print('\033[1m' + f"Serial executed in {elapsed:0.2f} seconds." + '\033[0m') BrightSmile Toothpaste Company BrightSmile Toothpaste Co. BrightSmile Toothpaste Gleaming Smile Inc. SparkleSmile Toothpaste Concurrent executed in 1.54 seconds. BrightSmile Toothpaste Co. MintyFresh Toothpaste Co. SparkleSmile Toothpaste. Pearly Whites Toothpaste Co. BrightSmile Toothpaste. Serial executed in 6.38 seconds. previous How-To Guides next Creating a custom Chain By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/chains/generic/async_chain.html
79e26189e2e0-0
.ipynb .pdf Serialization Contents Saving a chain to disk Loading a chain from disk Saving components separately Serialization# This notebook covers how to serialize chains to and from disk. The serialization format we use is json or yaml. Currently, only some chains support this type of serialization. We will grow the number of supported chains over time. Saving a chain to disk# First, let’s go over how to save a chain to disk. This can be done with the .save method, and specifying a file path with a json or yaml extension. from langchain import PromptTemplate, OpenAI, LLMChain template = """Question: {question} Answer: Let's think step by step.""" prompt = PromptTemplate(template=template, input_variables=["question"]) llm_chain = LLMChain(prompt=prompt, llm=OpenAI(temperature=0), verbose=True) llm_chain.save("llm_chain.json") Let’s now take a look at what’s inside this saved file !cat llm_chain.json { "memory": null, "verbose": true, "prompt": { "input_variables": [ "question" ], "output_parser": null, "template": "Question: {question}\n\nAnswer: Let's think step by step.", "template_format": "f-string" }, "llm": { "model_name": "text-davinci-003", "temperature": 0.0, "max_tokens": 256, "top_p": 1, "frequency_penalty": 0, "presence_penalty": 0, "n": 1, "best_of": 1, "request_timeout": null,
https://python.langchain.com/en/latest/modules/chains/generic/serialization.html
79e26189e2e0-1
"best_of": 1, "request_timeout": null, "logit_bias": {}, "_type": "openai" }, "output_key": "text", "_type": "llm_chain" } Loading a chain from disk# We can load a chain from disk by using the load_chain method. from langchain.chains import load_chain chain = load_chain("llm_chain.json") chain.run("whats 2 + 2") > Entering new LLMChain chain... Prompt after formatting: Question: whats 2 + 2 Answer: Let's think step by step. > Finished chain. ' 2 + 2 = 4' Saving components separately# In the above example, we can see that the prompt and llm configuration information is saved in the same json as the overall chain. Alternatively, we can split them up and save them separately. This is often useful to make the saved components more modular. In order to do this, we just need to specify llm_path instead of the llm component, and prompt_path instead of the prompt component. llm_chain.prompt.save("prompt.json") !cat prompt.json { "input_variables": [ "question" ], "output_parser": null, "template": "Question: {question}\n\nAnswer: Let's think step by step.", "template_format": "f-string" } llm_chain.llm.save("llm.json") !cat llm.json { "model_name": "text-davinci-003", "temperature": 0.0, "max_tokens": 256, "top_p": 1, "frequency_penalty": 0,
https://python.langchain.com/en/latest/modules/chains/generic/serialization.html
79e26189e2e0-2
"top_p": 1, "frequency_penalty": 0, "presence_penalty": 0, "n": 1, "best_of": 1, "request_timeout": null, "logit_bias": {}, "_type": "openai" } config = { "memory": None, "verbose": True, "prompt_path": "prompt.json", "llm_path": "llm.json", "output_key": "text", "_type": "llm_chain" } import json with open("llm_chain_separate.json", "w") as f: json.dump(config, f, indent=2) !cat llm_chain_separate.json { "memory": null, "verbose": true, "prompt_path": "prompt.json", "llm_path": "llm.json", "output_key": "text", "_type": "llm_chain" } We can then load it in the same way chain = load_chain("llm_chain_separate.json") chain.run("whats 2 + 2") > Entering new LLMChain chain... Prompt after formatting: Question: whats 2 + 2 Answer: Let's think step by step. > Finished chain. ' 2 + 2 = 4' previous Sequential Chains next Transformation Chain Contents Saving a chain to disk Loading a chain from disk Saving components separately By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/chains/generic/serialization.html
e16768666b51-0
.ipynb .pdf Creating a custom Chain Creating a custom Chain# To implement your own custom chain you can subclass Chain and implement the following methods: from __future__ import annotations from typing import Any, Dict, List, Optional from pydantic import Extra from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, ) from langchain.chains.base import Chain from langchain.prompts.base import BasePromptTemplate class MyCustomChain(Chain): """ An example of a custom chain. """ prompt: BasePromptTemplate """Prompt object to use.""" llm: BaseLanguageModel output_key: str = "text" #: :meta private: class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @property def input_keys(self) -> List[str]: """Will be whatever keys the prompt expects. :meta private: """ return self.prompt.input_variables @property def output_keys(self) -> List[str]: """Will always return text key. :meta private: """ return [self.output_key] def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, str]: # Your custom chain logic goes here # This is just an example that mimics LLMChain prompt_value = self.prompt.format_prompt(**inputs) # Whenever you call a language model, or another chain, you should pass
https://python.langchain.com/en/latest/modules/chains/generic/custom_chain.html
e16768666b51-1
# Whenever you call a language model, or another chain, you should pass # a callback manager to it. This allows the inner run to be tracked by # any callbacks that are registered on the outer run. # You can always obtain a callback manager for this by calling # `run_manager.get_child()` as shown below. response = self.llm.generate_prompt( [prompt_value], callbacks=run_manager.get_child() if run_manager else None ) # If you want to log something about this run, you can do so by calling # methods on the `run_manager`, as shown below. This will trigger any # callbacks that are registered for that event. if run_manager: run_manager.on_text("Log something about this run") return {self.output_key: response.generations[0][0].text} async def _acall( self, inputs: Dict[str, Any], run_manager: Optional[AsyncCallbackManagerForChainRun] = None, ) -> Dict[str, str]: # Your custom chain logic goes here # This is just an example that mimics LLMChain prompt_value = self.prompt.format_prompt(**inputs) # Whenever you call a language model, or another chain, you should pass # a callback manager to it. This allows the inner run to be tracked by # any callbacks that are registered on the outer run. # You can always obtain a callback manager for this by calling # `run_manager.get_child()` as shown below. response = await self.llm.agenerate_prompt( [prompt_value], callbacks=run_manager.get_child() if run_manager else None )
https://python.langchain.com/en/latest/modules/chains/generic/custom_chain.html
e16768666b51-2
callbacks=run_manager.get_child() if run_manager else None ) # If you want to log something about this run, you can do so by calling # methods on the `run_manager`, as shown below. This will trigger any # callbacks that are registered for that event. if run_manager: await run_manager.on_text("Log something about this run") return {self.output_key: response.generations[0][0].text} @property def _chain_type(self) -> str: return "my_custom_chain" from langchain.callbacks.stdout import StdOutCallbackHandler from langchain.chat_models.openai import ChatOpenAI from langchain.prompts.prompt import PromptTemplate chain = MyCustomChain( prompt=PromptTemplate.from_template('tell us a joke about {topic}'), llm=ChatOpenAI() ) chain.run({'topic': 'callbacks'}, callbacks=[StdOutCallbackHandler()]) > Entering new MyCustomChain chain... Log something about this run > Finished chain. 'Why did the callback function feel lonely? Because it was always waiting for someone to call it back!' previous Async API for Chain next Loading from LangChainHub By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/chains/generic/custom_chain.html
2dccacae8eab-0
.ipynb .pdf Router Chains Contents LLMRouterChain EmbeddingRouterChain Router Chains# This notebook demonstrates how to use the RouterChain paradigm to create a chain that dynamically selects the next chain to use for a given input. Router chains are made up of two components: The RouterChain itself (responsible for selecting the next chain to call) destination_chains: chains that the router chain can route to In this notebook we will focus on the different types of routing chains. We will show these routing chains used in a MultiPromptChain to create a question-answering chain that selects the prompt which is most relevant for a given question, and then answers the question using that prompt. from langchain.chains.router import MultiPromptChain from langchain.llms import OpenAI from langchain.chains import ConversationChain from langchain.chains.llm import LLMChain from langchain.prompts import PromptTemplate physics_template = """You are a very smart physics professor. \ You are great at answering questions about physics in a concise and easy to understand manner. \ When you don't know the answer to a question you admit that you don't know. Here is a question: {input}""" math_template = """You are a very good mathematician. You are great at answering math questions. \ You are so good because you are able to break down hard problems into their component parts, \ answer the component parts, and then put them together to answer the broader question. Here is a question: {input}""" prompt_infos = [ { "name": "physics", "description": "Good for answering questions about physics", "prompt_template": physics_template }, { "name": "math", "description": "Good for answering math questions",
https://python.langchain.com/en/latest/modules/chains/generic/router.html
2dccacae8eab-1
"description": "Good for answering math questions", "prompt_template": math_template } ] llm = OpenAI() destination_chains = {} for p_info in prompt_infos: name = p_info["name"] prompt_template = p_info["prompt_template"] prompt = PromptTemplate(template=prompt_template, input_variables=["input"]) chain = LLMChain(llm=llm, prompt=prompt) destination_chains[name] = chain default_chain = ConversationChain(llm=llm, output_key="text") LLMRouterChain# This chain uses an LLM to determine how to route things. from langchain.chains.router.llm_router import LLMRouterChain, RouterOutputParser from langchain.chains.router.multi_prompt_prompt import MULTI_PROMPT_ROUTER_TEMPLATE destinations = [f"{p['name']}: {p['description']}" for p in prompt_infos] destinations_str = "\n".join(destinations) router_template = MULTI_PROMPT_ROUTER_TEMPLATE.format( destinations=destinations_str ) router_prompt = PromptTemplate( template=router_template, input_variables=["input"], output_parser=RouterOutputParser(), ) router_chain = LLMRouterChain.from_llm(llm, router_prompt) chain = MultiPromptChain(router_chain=router_chain, destination_chains=destination_chains, default_chain=default_chain, verbose=True) print(chain.run("What is black body radiation?")) > Entering new MultiPromptChain chain... physics: {'input': 'What is black body radiation?'} > Finished chain.
https://python.langchain.com/en/latest/modules/chains/generic/router.html
2dccacae8eab-2
physics: {'input': 'What is black body radiation?'} > Finished chain. Black body radiation is the term used to describe the electromagnetic radiation emitted by a “black body”—an object that absorbs all radiation incident upon it. A black body is an idealized physical body that absorbs all incident electromagnetic radiation, regardless of frequency or angle of incidence. It does not reflect, emit or transmit energy. This type of radiation is the result of the thermal motion of the body's atoms and molecules, and it is emitted at all wavelengths. The spectrum of radiation emitted is described by Planck's law and is known as the black body spectrum. print(chain.run("What is the first prime number greater than 40 such that one plus the prime number is divisible by 3")) > Entering new MultiPromptChain chain... math: {'input': 'What is the first prime number greater than 40 such that one plus the prime number is divisible by 3'} > Finished chain. ? The answer is 43. One plus 43 is 44 which is divisible by 3. print(chain.run("What is the name of the type of cloud that rins")) > Entering new MultiPromptChain chain... None: {'input': 'What is the name of the type of cloud that rains?'} > Finished chain. The type of cloud that rains is called a cumulonimbus cloud. It is a tall and dense cloud that is often accompanied by thunder and lightning. EmbeddingRouterChain# The EmbeddingRouterChain uses embeddings and similarity to route between destination chains. from langchain.chains.router.embedding_router import EmbeddingRouterChain from langchain.embeddings import CohereEmbeddings from langchain.vectorstores import Chroma names_and_descriptions = [ ("physics", ["for questions about physics"]), ("math", ["for questions about math"]), ]
https://python.langchain.com/en/latest/modules/chains/generic/router.html
2dccacae8eab-3
("math", ["for questions about math"]), ] router_chain = EmbeddingRouterChain.from_names_and_descriptions( names_and_descriptions, Chroma, CohereEmbeddings(), routing_keys=["input"] ) Using embedded DuckDB without persistence: data will be transient chain = MultiPromptChain(router_chain=router_chain, destination_chains=destination_chains, default_chain=default_chain, verbose=True) print(chain.run("What is black body radiation?")) > Entering new MultiPromptChain chain... physics: {'input': 'What is black body radiation?'} > Finished chain. Black body radiation is the emission of energy from an idealized physical body (known as a black body) that is in thermal equilibrium with its environment. It is emitted in a characteristic pattern of frequencies known as a black-body spectrum, which depends only on the temperature of the body. The study of black body radiation is an important part of astrophysics and atmospheric physics, as the thermal radiation emitted by stars and planets can often be approximated as black body radiation. print(chain.run("What is the first prime number greater than 40 such that one plus the prime number is divisible by 3")) > Entering new MultiPromptChain chain... math: {'input': 'What is the first prime number greater than 40 such that one plus the prime number is divisible by 3'} > Finished chain. ? Answer: The first prime number greater than 40 such that one plus the prime number is divisible by 3 is 43. previous LLM Chain next Sequential Chains Contents LLMRouterChain EmbeddingRouterChain By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/chains/generic/router.html
85aa46e76b85-0
.ipynb .pdf Moderation Contents How to use the moderation chain How to append a Moderation chain to an LLMChain Moderation# This notebook walks through examples of how to use a moderation chain, and several common ways for doing so. Moderation chains are useful for detecting text that could be hateful, violent, etc. This can be useful to apply on both user input, but also on the output of a Language Model. Some API providers, like OpenAI, specifically prohibit you, or your end users, from generating some types of harmful content. To comply with this (and to just generally prevent your application from being harmful) you may often want to append a moderation chain to any LLMChains, in order to make sure any output the LLM generates is not harmful. If the content passed into the moderation chain is harmful, there is not one best way to handle it, it probably depends on your application. Sometimes you may want to throw an error in the Chain (and have your application handle that). Other times, you may want to return something to the user explaining that the text was harmful. There could even be other ways to handle it! We will cover all these ways in this notebook. In this notebook, we will show: How to run any piece of text through a moderation chain. How to append a Moderation chain to an LLMChain. from langchain.llms import OpenAI from langchain.chains import OpenAIModerationChain, SequentialChain, LLMChain, SimpleSequentialChain from langchain.prompts import PromptTemplate How to use the moderation chain# Here’s an example of using the moderation chain with default settings (will return a string explaining stuff was flagged). moderation_chain = OpenAIModerationChain() moderation_chain.run("This is okay") 'This is okay' moderation_chain.run("I will kill you")
https://python.langchain.com/en/latest/modules/chains/examples/moderation.html
85aa46e76b85-1
'This is okay' moderation_chain.run("I will kill you") "Text was found that violates OpenAI's content policy." Here’s an example of using the moderation chain to throw an error. moderation_chain_error = OpenAIModerationChain(error=True) moderation_chain_error.run("This is okay") 'This is okay' moderation_chain_error.run("I will kill you") --------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[7], line 1 ----> 1 moderation_chain_error.run("I will kill you") File ~/workplace/langchain/langchain/chains/base.py:138, in Chain.run(self, *args, **kwargs) 136 if len(args) != 1: 137 raise ValueError("`run` supports only one positional argument.") --> 138 return self(args[0])[self.output_keys[0]] 140 if kwargs and not args: 141 return self(kwargs)[self.output_keys[0]] File ~/workplace/langchain/langchain/chains/base.py:112, in Chain.__call__(self, inputs, return_only_outputs) 108 if self.verbose: 109 print( 110 f"\n\n\033[1m> Entering new {self.__class__.__name__} chain...\033[0m" 111 ) --> 112 outputs = self._call(inputs) 113 if self.verbose: 114 print(f"\n\033[1m> Finished {self.__class__.__name__} chain.\033[0m") File ~/workplace/langchain/langchain/chains/moderation.py:81, in OpenAIModerationChain._call(self, inputs) 79 text = inputs[self.input_key]
https://python.langchain.com/en/latest/modules/chains/examples/moderation.html
85aa46e76b85-2
79 text = inputs[self.input_key] 80 results = self.client.create(text) ---> 81 output = self._moderate(text, results["results"][0]) 82 return {self.output_key: output} File ~/workplace/langchain/langchain/chains/moderation.py:73, in OpenAIModerationChain._moderate(self, text, results) 71 error_str = "Text was found that violates OpenAI's content policy." 72 if self.error: ---> 73 raise ValueError(error_str) 74 else: 75 return error_str ValueError: Text was found that violates OpenAI's content policy. Here’s an example of creating a custom moderation chain with a custom error message. It requires some knowledge of OpenAI’s moderation endpoint results (see docs here). class CustomModeration(OpenAIModerationChain): def _moderate(self, text: str, results: dict) -> str: if results["flagged"]: error_str = f"The following text was found that violates OpenAI's content policy: {text}" return error_str return text custom_moderation = CustomModeration() custom_moderation.run("This is okay") 'This is okay' custom_moderation.run("I will kill you") "The following text was found that violates OpenAI's content policy: I will kill you" How to append a Moderation chain to an LLMChain# To easily combine a moderation chain with an LLMChain, you can use the SequentialChain abstraction. Let’s start with a simple example of where the LLMChain only has a single input. For this purpose, we will prompt the model so it says something harmful. prompt = PromptTemplate(template="{text}", input_variables=["text"])
https://python.langchain.com/en/latest/modules/chains/examples/moderation.html
85aa46e76b85-3
prompt = PromptTemplate(template="{text}", input_variables=["text"]) llm_chain = LLMChain(llm=OpenAI(temperature=0, model_name="text-davinci-002"), prompt=prompt) text = """We are playing a game of repeat after me. Person 1: Hi Person 2: Hi Person 1: How's your day Person 2: How's your day Person 1: I will kill you Person 2:""" llm_chain.run(text) ' I will kill you' chain = SimpleSequentialChain(chains=[llm_chain, moderation_chain]) chain.run(text) "Text was found that violates OpenAI's content policy." Now let’s walk through an example of using it with an LLMChain which has multiple inputs (a bit more tricky because we can’t use the SimpleSequentialChain) prompt = PromptTemplate(template="{setup}{new_input}Person2:", input_variables=["setup", "new_input"]) llm_chain = LLMChain(llm=OpenAI(temperature=0, model_name="text-davinci-002"), prompt=prompt) setup = """We are playing a game of repeat after me. Person 1: Hi Person 2: Hi Person 1: How's your day Person 2: How's your day Person 1:""" new_input = "I will kill you" inputs = {"setup": setup, "new_input": new_input} llm_chain(inputs, return_only_outputs=True) {'text': ' I will kill you'} # Setting the input/output keys so it lines up moderation_chain.input_key = "text" moderation_chain.output_key = "sanitized_text" chain = SequentialChain(chains=[llm_chain, moderation_chain], input_variables=["setup", "new_input"])
https://python.langchain.com/en/latest/modules/chains/examples/moderation.html
85aa46e76b85-4
chain(inputs, return_only_outputs=True) {'sanitized_text': "Text was found that violates OpenAI's content policy."} previous LLMSummarizationCheckerChain next Router Chains: Selecting from multiple prompts with MultiPromptChain Contents How to use the moderation chain How to append a Moderation chain to an LLMChain By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/chains/examples/moderation.html
b81fc3a40a5a-0
.ipynb .pdf LLMSummarizationCheckerChain LLMSummarizationCheckerChain# This notebook shows some examples of LLMSummarizationCheckerChain in use with different types of texts. It has a few distinct differences from the LLMCheckerChain, in that it doesn’t have any assumptions to the format of the input text (or summary). Additionally, as the LLMs like to hallucinate when fact checking or get confused by context, it is sometimes beneficial to run the checker multiple times. It does this by feeding the rewritten “True” result back on itself, and checking the “facts” for truth. As you can see from the examples below, this can be very effective in arriving at a generally true body of text. You can control the number of times the checker runs by setting the max_checks parameter. The default is 2, but you can set it to 1 if you don’t want any double-checking. from langchain.chains import LLMSummarizationCheckerChain from langchain.llms import OpenAI llm = OpenAI(temperature=0) checker_chain = LLMSummarizationCheckerChain.from_llm(llm, verbose=True, max_checks=2) text = """ Your 9-year old might like these recent discoveries made by The James Webb Space Telescope (JWST): • In 2023, The JWST spotted a number of galaxies nicknamed "green peas." They were given this name because they are small, round, and green, like peas. • The telescope captured images of galaxies that are over 13 billion years old. This means that the light from these galaxies has been traveling for over 13 billion years to reach us. • JWST took the very first pictures of a planet outside of our own solar system. These distant worlds are called "exoplanets." Exo means "from outside."
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-1
These discoveries can spark a child's imagination about the infinite wonders of the universe.""" checker_chain.run(text) > Entering new LLMSummarizationCheckerChain chain... > Entering new SequentialChain chain... > Entering new LLMChain chain... Prompt after formatting: Given some text, extract a list of facts from the text. Format your output as a bulleted list. Text: """ Your 9-year old might like these recent discoveries made by The James Webb Space Telescope (JWST): • In 2023, The JWST spotted a number of galaxies nicknamed "green peas." They were given this name because they are small, round, and green, like peas. • The telescope captured images of galaxies that are over 13 billion years old. This means that the light from these galaxies has been traveling for over 13 billion years to reach us. • JWST took the very first pictures of a planet outside of our own solar system. These distant worlds are called "exoplanets." Exo means "from outside." These discoveries can spark a child's imagination about the infinite wonders of the universe. """ Facts: > Finished chain. > Entering new LLMChain chain... Prompt after formatting: You are an expert fact checker. You have been hired by a major news organization to fact check a very important story. Here is a bullet point list of facts: """ • The James Webb Space Telescope (JWST) spotted a number of galaxies nicknamed "green peas." • The telescope captured images of galaxies that are over 13 billion years old. • JWST took the very first pictures of a planet outside of our own solar system. • These distant worlds are called "exoplanets." """
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-2
• These distant worlds are called "exoplanets." """ For each fact, determine whether it is true or false about the subject. If you are unable to determine whether the fact is true or false, output "Undetermined". If the fact is false, explain why. > Finished chain. > Entering new LLMChain chain... Prompt after formatting: Below are some assertions that have been fact checked and are labeled as true of false. If the answer is false, a suggestion is given for a correction. Checked Assertions: """ • The James Webb Space Telescope (JWST) spotted a number of galaxies nicknamed "green peas." - True • The telescope captured images of galaxies that are over 13 billion years old. - True • JWST took the very first pictures of a planet outside of our own solar system. - False. The first exoplanet was discovered in 1992, before the JWST was launched. • These distant worlds are called "exoplanets." - True """ Original Summary: """ Your 9-year old might like these recent discoveries made by The James Webb Space Telescope (JWST): • In 2023, The JWST spotted a number of galaxies nicknamed "green peas." They were given this name because they are small, round, and green, like peas. • The telescope captured images of galaxies that are over 13 billion years old. This means that the light from these galaxies has been traveling for over 13 billion years to reach us. • JWST took the very first pictures of a planet outside of our own solar system. These distant worlds are called "exoplanets." Exo means "from outside." These discoveries can spark a child's imagination about the infinite wonders of the universe. """ Using these checked assertions, rewrite the original summary to be completely true.
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-3
""" Using these checked assertions, rewrite the original summary to be completely true. The output should have the same structure and formatting as the original summary. Summary: > Finished chain. > Entering new LLMChain chain... Prompt after formatting: Below are some assertions that have been fact checked and are labeled as true or false. If all of the assertions are true, return "True". If any of the assertions are false, return "False". Here are some examples: === Checked Assertions: """ - The sky is red: False - Water is made of lava: False - The sun is a star: True """ Result: False === Checked Assertions: """ - The sky is blue: True - Water is wet: True - The sun is a star: True """ Result: True === Checked Assertions: """ - The sky is blue - True - Water is made of lava- False - The sun is a star - True """ Result: False === Checked Assertions:""" • The James Webb Space Telescope (JWST) spotted a number of galaxies nicknamed "green peas." - True • The telescope captured images of galaxies that are over 13 billion years old. - True • JWST took the very first pictures of a planet outside of our own solar system. - False. The first exoplanet was discovered in 1992, before the JWST was launched. • These distant worlds are called "exoplanets." - True """ Result: > Finished chain. > Finished chain. Your 9-year old might like these recent discoveries made by The James Webb Space Telescope (JWST):
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-4
• In 2023, The JWST spotted a number of galaxies nicknamed "green peas." They were given this name because they are small, round, and green, like peas. • The telescope captured images of galaxies that are over 13 billion years old. This means that the light from these galaxies has been traveling for over 13 billion years to reach us. • JWST has provided us with the first images of exoplanets, which are planets outside of our own solar system. These distant worlds were first discovered in 1992, and the JWST has allowed us to see them in greater detail. These discoveries can spark a child's imagination about the infinite wonders of the universe. > Entering new SequentialChain chain... > Entering new LLMChain chain... Prompt after formatting: Given some text, extract a list of facts from the text. Format your output as a bulleted list. Text: """ Your 9-year old might like these recent discoveries made by The James Webb Space Telescope (JWST): • In 2023, The JWST spotted a number of galaxies nicknamed "green peas." They were given this name because they are small, round, and green, like peas. • The telescope captured images of galaxies that are over 13 billion years old. This means that the light from these galaxies has been traveling for over 13 billion years to reach us. • JWST has provided us with the first images of exoplanets, which are planets outside of our own solar system. These distant worlds were first discovered in 1992, and the JWST has allowed us to see them in greater detail. These discoveries can spark a child's imagination about the infinite wonders of the universe. """ Facts: > Finished chain. > Entering new LLMChain chain... Prompt after formatting:
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-5
> Finished chain. > Entering new LLMChain chain... Prompt after formatting: You are an expert fact checker. You have been hired by a major news organization to fact check a very important story. Here is a bullet point list of facts: """ • The James Webb Space Telescope (JWST) spotted a number of galaxies nicknamed "green peas." • The light from these galaxies has been traveling for over 13 billion years to reach us. • JWST has provided us with the first images of exoplanets, which are planets outside of our own solar system. • Exoplanets were first discovered in 1992. • The JWST has allowed us to see exoplanets in greater detail. """ For each fact, determine whether it is true or false about the subject. If you are unable to determine whether the fact is true or false, output "Undetermined". If the fact is false, explain why. > Finished chain. > Entering new LLMChain chain... Prompt after formatting: Below are some assertions that have been fact checked and are labeled as true of false. If the answer is false, a suggestion is given for a correction. Checked Assertions: """ • The James Webb Space Telescope (JWST) spotted a number of galaxies nicknamed "green peas." - True • The light from these galaxies has been traveling for over 13 billion years to reach us. - True • JWST has provided us with the first images of exoplanets, which are planets outside of our own solar system. - False. The first exoplanet was discovered in 1992, but the first images of exoplanets were taken by the Hubble Space Telescope in 2004. • Exoplanets were first discovered in 1992. - True
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-6
• Exoplanets were first discovered in 1992. - True • The JWST has allowed us to see exoplanets in greater detail. - Undetermined. The JWST has not yet been launched, so it is not yet known how much detail it will be able to provide. """ Original Summary: """ Your 9-year old might like these recent discoveries made by The James Webb Space Telescope (JWST): • In 2023, The JWST spotted a number of galaxies nicknamed "green peas." They were given this name because they are small, round, and green, like peas. • The telescope captured images of galaxies that are over 13 billion years old. This means that the light from these galaxies has been traveling for over 13 billion years to reach us. • JWST has provided us with the first images of exoplanets, which are planets outside of our own solar system. These distant worlds were first discovered in 1992, and the JWST has allowed us to see them in greater detail. These discoveries can spark a child's imagination about the infinite wonders of the universe. """ Using these checked assertions, rewrite the original summary to be completely true. The output should have the same structure and formatting as the original summary. Summary: > Finished chain. > Entering new LLMChain chain... Prompt after formatting: Below are some assertions that have been fact checked and are labeled as true or false. If all of the assertions are true, return "True". If any of the assertions are false, return "False". Here are some examples: === Checked Assertions: """ - The sky is red: False - Water is made of lava: False - The sun is a star: True """ Result: False === Checked Assertions: """ - The sky is blue: True
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-7
""" Result: False === Checked Assertions: """ - The sky is blue: True - Water is wet: True - The sun is a star: True """ Result: True === Checked Assertions: """ - The sky is blue - True - Water is made of lava- False - The sun is a star - True """ Result: False === Checked Assertions:""" • The James Webb Space Telescope (JWST) spotted a number of galaxies nicknamed "green peas." - True • The light from these galaxies has been traveling for over 13 billion years to reach us. - True • JWST has provided us with the first images of exoplanets, which are planets outside of our own solar system. - False. The first exoplanet was discovered in 1992, but the first images of exoplanets were taken by the Hubble Space Telescope in 2004. • Exoplanets were first discovered in 1992. - True • The JWST has allowed us to see exoplanets in greater detail. - Undetermined. The JWST has not yet been launched, so it is not yet known how much detail it will be able to provide. """ Result: > Finished chain. > Finished chain. Your 9-year old might like these recent discoveries made by The James Webb Space Telescope (JWST): • In 2023, The JWST will spot a number of galaxies nicknamed "green peas." They were given this name because they are small, round, and green, like peas. • The telescope will capture images of galaxies that are over 13 billion years old. This means that the light from these galaxies has been traveling for over 13 billion years to reach us.
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-8
• Exoplanets, which are planets outside of our own solar system, were first discovered in 1992. The JWST will allow us to see them in greater detail when it is launched in 2023. These discoveries can spark a child's imagination about the infinite wonders of the universe. > Finished chain. 'Your 9-year old might like these recent discoveries made by The James Webb Space Telescope (JWST):\n• In 2023, The JWST will spot a number of galaxies nicknamed "green peas." They were given this name because they are small, round, and green, like peas.\n• The telescope will capture images of galaxies that are over 13 billion years old. This means that the light from these galaxies has been traveling for over 13 billion years to reach us.\n• Exoplanets, which are planets outside of our own solar system, were first discovered in 1992. The JWST will allow us to see them in greater detail when it is launched in 2023.\nThese discoveries can spark a child\'s imagination about the infinite wonders of the universe.' from langchain.chains import LLMSummarizationCheckerChain from langchain.llms import OpenAI llm = OpenAI(temperature=0) checker_chain = LLMSummarizationCheckerChain.from_llm(llm, verbose=True, max_checks=3)
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-9
text = "The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is one of five oceans in the world, alongside the Pacific Ocean, Atlantic Ocean, Indian Ocean, and the Southern Ocean. It is the smallest of the five oceans and is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. The sea is named after the island of Greenland, and is the Arctic Ocean's main outlet to the Atlantic. It is often frozen over so navigation is limited, and is considered the northern branch of the Norwegian Sea." checker_chain.run(text) > Entering new LLMSummarizationCheckerChain chain... > Entering new SequentialChain chain... > Entering new LLMChain chain... Prompt after formatting: Given some text, extract a list of facts from the text. Format your output as a bulleted list. Text: """ The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is one of five oceans in the world, alongside the Pacific Ocean, Atlantic Ocean, Indian Ocean, and the Southern Ocean. It is the smallest of the five oceans and is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. The sea is named after the island of Greenland, and is the Arctic Ocean's main outlet to the Atlantic. It is often frozen over so navigation is limited, and is considered the northern branch of the Norwegian Sea. """ Facts: > Finished chain. > Entering new LLMChain chain... Prompt after formatting:
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-10
> Finished chain. > Entering new LLMChain chain... Prompt after formatting: You are an expert fact checker. You have been hired by a major news organization to fact check a very important story. Here is a bullet point list of facts: """ - The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. - It has an area of 465,000 square miles. - It is one of five oceans in the world, alongside the Pacific Ocean, Atlantic Ocean, Indian Ocean, and the Southern Ocean. - It is the smallest of the five oceans. - It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. - The sea is named after the island of Greenland. - It is the Arctic Ocean's main outlet to the Atlantic. - It is often frozen over so navigation is limited. - It is considered the northern branch of the Norwegian Sea. """ For each fact, determine whether it is true or false about the subject. If you are unable to determine whether the fact is true or false, output "Undetermined". If the fact is false, explain why. > Finished chain. > Entering new LLMChain chain... Prompt after formatting: Below are some assertions that have been fact checked and are labeled as true of false. If the answer is false, a suggestion is given for a correction. Checked Assertions: """ - The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. True - It has an area of 465,000 square miles. True
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-11
- It has an area of 465,000 square miles. True - It is one of five oceans in the world, alongside the Pacific Ocean, Atlantic Ocean, Indian Ocean, and the Southern Ocean. False - The Greenland Sea is not an ocean, it is an arm of the Arctic Ocean. - It is the smallest of the five oceans. False - The Greenland Sea is not an ocean, it is an arm of the Arctic Ocean. - It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. True - The sea is named after the island of Greenland. True - It is the Arctic Ocean's main outlet to the Atlantic. True - It is often frozen over so navigation is limited. True - It is considered the northern branch of the Norwegian Sea. True """ Original Summary: """ The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is one of five oceans in the world, alongside the Pacific Ocean, Atlantic Ocean, Indian Ocean, and the Southern Ocean. It is the smallest of the five oceans and is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. The sea is named after the island of Greenland, and is the Arctic Ocean's main outlet to the Atlantic. It is often frozen over so navigation is limited, and is considered the northern branch of the Norwegian Sea. """ Using these checked assertions, rewrite the original summary to be completely true. The output should have the same structure and formatting as the original summary. Summary: > Finished chain. > Entering new LLMChain chain... Prompt after formatting: Below are some assertions that have been fact checked and are labeled as true or false.
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-12
Below are some assertions that have been fact checked and are labeled as true or false. If all of the assertions are true, return "True". If any of the assertions are false, return "False". Here are some examples: === Checked Assertions: """ - The sky is red: False - Water is made of lava: False - The sun is a star: True """ Result: False === Checked Assertions: """ - The sky is blue: True - Water is wet: True - The sun is a star: True """ Result: True === Checked Assertions: """ - The sky is blue - True - Water is made of lava- False - The sun is a star - True """ Result: False === Checked Assertions:""" - The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. True - It has an area of 465,000 square miles. True - It is one of five oceans in the world, alongside the Pacific Ocean, Atlantic Ocean, Indian Ocean, and the Southern Ocean. False - The Greenland Sea is not an ocean, it is an arm of the Arctic Ocean. - It is the smallest of the five oceans. False - The Greenland Sea is not an ocean, it is an arm of the Arctic Ocean. - It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. True - The sea is named after the island of Greenland. True - It is the Arctic Ocean's main outlet to the Atlantic. True - It is often frozen over so navigation is limited. True - It is considered the northern branch of the Norwegian Sea. True """ Result: > Finished chain. > Finished chain.
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-13
""" Result: > Finished chain. > Finished chain. The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is an arm of the Arctic Ocean. It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. The sea is named after the island of Greenland, and is the Arctic Ocean's main outlet to the Atlantic. It is often frozen over so navigation is limited, and is considered the northern branch of the Norwegian Sea. > Entering new SequentialChain chain... > Entering new LLMChain chain... Prompt after formatting: Given some text, extract a list of facts from the text. Format your output as a bulleted list. Text: """ The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is an arm of the Arctic Ocean. It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. The sea is named after the island of Greenland, and is the Arctic Ocean's main outlet to the Atlantic. It is often frozen over so navigation is limited, and is considered the northern branch of the Norwegian Sea. """ Facts: > Finished chain. > Entering new LLMChain chain... Prompt after formatting: You are an expert fact checker. You have been hired by a major news organization to fact check a very important story. Here is a bullet point list of facts: """ - The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland.
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-14
- It has an area of 465,000 square miles. - It is an arm of the Arctic Ocean. - It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. - It is named after the island of Greenland. - It is the Arctic Ocean's main outlet to the Atlantic. - It is often frozen over so navigation is limited. - It is considered the northern branch of the Norwegian Sea. """ For each fact, determine whether it is true or false about the subject. If you are unable to determine whether the fact is true or false, output "Undetermined". If the fact is false, explain why. > Finished chain. > Entering new LLMChain chain... Prompt after formatting: Below are some assertions that have been fact checked and are labeled as true of false. If the answer is false, a suggestion is given for a correction. Checked Assertions: """ - The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. True - It has an area of 465,000 square miles. True - It is an arm of the Arctic Ocean. True - It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. True - It is named after the island of Greenland. False - It is named after the country of Greenland. - It is the Arctic Ocean's main outlet to the Atlantic. True - It is often frozen over so navigation is limited. True - It is considered the northern branch of the Norwegian Sea. False - It is considered the northern branch of the Atlantic Ocean. """ Original Summary: """
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-15
""" Original Summary: """ The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is an arm of the Arctic Ocean. It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. The sea is named after the island of Greenland, and is the Arctic Ocean's main outlet to the Atlantic. It is often frozen over so navigation is limited, and is considered the northern branch of the Norwegian Sea. """ Using these checked assertions, rewrite the original summary to be completely true. The output should have the same structure and formatting as the original summary. Summary: > Finished chain. > Entering new LLMChain chain... Prompt after formatting: Below are some assertions that have been fact checked and are labeled as true or false. If all of the assertions are true, return "True". If any of the assertions are false, return "False". Here are some examples: === Checked Assertions: """ - The sky is red: False - Water is made of lava: False - The sun is a star: True """ Result: False === Checked Assertions: """ - The sky is blue: True - Water is wet: True - The sun is a star: True """ Result: True === Checked Assertions: """ - The sky is blue - True - Water is made of lava- False - The sun is a star - True """ Result: False === Checked Assertions:""" - The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. True - It has an area of 465,000 square miles. True
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-16
- It has an area of 465,000 square miles. True - It is an arm of the Arctic Ocean. True - It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. True - It is named after the island of Greenland. False - It is named after the country of Greenland. - It is the Arctic Ocean's main outlet to the Atlantic. True - It is often frozen over so navigation is limited. True - It is considered the northern branch of the Norwegian Sea. False - It is considered the northern branch of the Atlantic Ocean. """ Result: > Finished chain. > Finished chain. The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is an arm of the Arctic Ocean. It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. The sea is named after the country of Greenland, and is the Arctic Ocean's main outlet to the Atlantic. It is often frozen over so navigation is limited, and is considered the northern branch of the Atlantic Ocean. > Entering new SequentialChain chain... > Entering new LLMChain chain... Prompt after formatting: Given some text, extract a list of facts from the text. Format your output as a bulleted list. Text: """
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-17
Format your output as a bulleted list. Text: """ The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is an arm of the Arctic Ocean. It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. The sea is named after the country of Greenland, and is the Arctic Ocean's main outlet to the Atlantic. It is often frozen over so navigation is limited, and is considered the northern branch of the Atlantic Ocean. """ Facts: > Finished chain. > Entering new LLMChain chain... Prompt after formatting: You are an expert fact checker. You have been hired by a major news organization to fact check a very important story. Here is a bullet point list of facts: """ - The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. - It has an area of 465,000 square miles. - It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. - The sea is named after the country of Greenland. - It is the Arctic Ocean's main outlet to the Atlantic. - It is often frozen over so navigation is limited. - It is considered the northern branch of the Atlantic Ocean. """ For each fact, determine whether it is true or false about the subject. If you are unable to determine whether the fact is true or false, output "Undetermined". If the fact is false, explain why. > Finished chain. > Entering new LLMChain chain... Prompt after formatting:
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-18
> Finished chain. > Entering new LLMChain chain... Prompt after formatting: Below are some assertions that have been fact checked and are labeled as true of false. If the answer is false, a suggestion is given for a correction. Checked Assertions: """ - The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. True - It has an area of 465,000 square miles. True - It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. True - The sea is named after the country of Greenland. True - It is the Arctic Ocean's main outlet to the Atlantic. False - The Arctic Ocean's main outlet to the Atlantic is the Barents Sea. - It is often frozen over so navigation is limited. True - It is considered the northern branch of the Atlantic Ocean. False - The Greenland Sea is considered part of the Arctic Ocean, not the Atlantic Ocean. """ Original Summary: """ The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is an arm of the Arctic Ocean. It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. The sea is named after the country of Greenland, and is the Arctic Ocean's main outlet to the Atlantic. It is often frozen over so navigation is limited, and is considered the northern branch of the Atlantic Ocean. """ Using these checked assertions, rewrite the original summary to be completely true. The output should have the same structure and formatting as the original summary. Summary: > Finished chain. > Entering new LLMChain chain... Prompt after formatting:
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-19
> Finished chain. > Entering new LLMChain chain... Prompt after formatting: Below are some assertions that have been fact checked and are labeled as true or false. If all of the assertions are true, return "True". If any of the assertions are false, return "False". Here are some examples: === Checked Assertions: """ - The sky is red: False - Water is made of lava: False - The sun is a star: True """ Result: False === Checked Assertions: """ - The sky is blue: True - Water is wet: True - The sun is a star: True """ Result: True === Checked Assertions: """ - The sky is blue - True - Water is made of lava- False - The sun is a star - True """ Result: False === Checked Assertions:""" - The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. True - It has an area of 465,000 square miles. True - It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. True - The sea is named after the country of Greenland. True - It is the Arctic Ocean's main outlet to the Atlantic. False - The Arctic Ocean's main outlet to the Atlantic is the Barents Sea. - It is often frozen over so navigation is limited. True - It is considered the northern branch of the Atlantic Ocean. False - The Greenland Sea is considered part of the Arctic Ocean, not the Atlantic Ocean. """ Result: > Finished chain. > Finished chain.
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-20
""" Result: > Finished chain. > Finished chain. The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. The sea is named after the country of Greenland, and is the Arctic Ocean's main outlet to the Barents Sea. It is often frozen over so navigation is limited, and is considered part of the Arctic Ocean. > Finished chain. "The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. The sea is named after the country of Greenland, and is the Arctic Ocean's main outlet to the Barents Sea. It is often frozen over so navigation is limited, and is considered part of the Arctic Ocean." from langchain.chains import LLMSummarizationCheckerChain from langchain.llms import OpenAI llm = OpenAI(temperature=0) checker_chain = LLMSummarizationCheckerChain.from_llm(llm, max_checks=3, verbose=True) text = "Mammals can lay eggs, birds can lay eggs, therefore birds are mammals." checker_chain.run(text) > Entering new LLMSummarizationCheckerChain chain... > Entering new SequentialChain chain... > Entering new LLMChain chain... Prompt after formatting: Given some text, extract a list of facts from the text. Format your output as a bulleted list. Text: """
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-21
Format your output as a bulleted list. Text: """ Mammals can lay eggs, birds can lay eggs, therefore birds are mammals. """ Facts: > Finished chain. > Entering new LLMChain chain... Prompt after formatting: You are an expert fact checker. You have been hired by a major news organization to fact check a very important story. Here is a bullet point list of facts: """ - Mammals can lay eggs - Birds can lay eggs - Birds are mammals """ For each fact, determine whether it is true or false about the subject. If you are unable to determine whether the fact is true or false, output "Undetermined". If the fact is false, explain why. > Finished chain. > Entering new LLMChain chain... Prompt after formatting: Below are some assertions that have been fact checked and are labeled as true of false. If the answer is false, a suggestion is given for a correction. Checked Assertions: """ - Mammals can lay eggs: False. Mammals are not capable of laying eggs, as they give birth to live young. - Birds can lay eggs: True. Birds are capable of laying eggs. - Birds are mammals: False. Birds are not mammals, they are a class of their own. """ Original Summary: """ Mammals can lay eggs, birds can lay eggs, therefore birds are mammals. """ Using these checked assertions, rewrite the original summary to be completely true. The output should have the same structure and formatting as the original summary. Summary: > Finished chain. > Entering new LLMChain chain... Prompt after formatting: Below are some assertions that have been fact checked and are labeled as true or false.
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-22
Below are some assertions that have been fact checked and are labeled as true or false. If all of the assertions are true, return "True". If any of the assertions are false, return "False". Here are some examples: === Checked Assertions: """ - The sky is red: False - Water is made of lava: False - The sun is a star: True """ Result: False === Checked Assertions: """ - The sky is blue: True - Water is wet: True - The sun is a star: True """ Result: True === Checked Assertions: """ - The sky is blue - True - Water is made of lava- False - The sun is a star - True """ Result: False === Checked Assertions:""" - Mammals can lay eggs: False. Mammals are not capable of laying eggs, as they give birth to live young. - Birds can lay eggs: True. Birds are capable of laying eggs. - Birds are mammals: False. Birds are not mammals, they are a class of their own. """ Result: > Finished chain. > Finished chain. Birds and mammals are both capable of laying eggs, however birds are not mammals, they are a class of their own. > Entering new SequentialChain chain... > Entering new LLMChain chain... Prompt after formatting: Given some text, extract a list of facts from the text. Format your output as a bulleted list. Text: """ Birds and mammals are both capable of laying eggs, however birds are not mammals, they are a class of their own. """ Facts: > Finished chain. > Entering new LLMChain chain... Prompt after formatting:
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-23
> Finished chain. > Entering new LLMChain chain... Prompt after formatting: You are an expert fact checker. You have been hired by a major news organization to fact check a very important story. Here is a bullet point list of facts: """ - Birds and mammals are both capable of laying eggs. - Birds are not mammals. - Birds are a class of their own. """ For each fact, determine whether it is true or false about the subject. If you are unable to determine whether the fact is true or false, output "Undetermined". If the fact is false, explain why. > Finished chain. > Entering new LLMChain chain... Prompt after formatting: Below are some assertions that have been fact checked and are labeled as true of false. If the answer is false, a suggestion is given for a correction. Checked Assertions: """ - Birds and mammals are both capable of laying eggs: False. Mammals give birth to live young, while birds lay eggs. - Birds are not mammals: True. Birds are a class of their own, separate from mammals. - Birds are a class of their own: True. Birds are a class of their own, separate from mammals. """ Original Summary: """ Birds and mammals are both capable of laying eggs, however birds are not mammals, they are a class of their own. """ Using these checked assertions, rewrite the original summary to be completely true. The output should have the same structure and formatting as the original summary. Summary: > Finished chain. > Entering new LLMChain chain... Prompt after formatting: Below are some assertions that have been fact checked and are labeled as true or false. If all of the assertions are true, return "True". If any of the assertions are false, return "False".
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
b81fc3a40a5a-24
Here are some examples: === Checked Assertions: """ - The sky is red: False - Water is made of lava: False - The sun is a star: True """ Result: False === Checked Assertions: """ - The sky is blue: True - Water is wet: True - The sun is a star: True """ Result: True === Checked Assertions: """ - The sky is blue - True - Water is made of lava- False - The sun is a star - True """ Result: False === Checked Assertions:""" - Birds and mammals are both capable of laying eggs: False. Mammals give birth to live young, while birds lay eggs. - Birds are not mammals: True. Birds are a class of their own, separate from mammals. - Birds are a class of their own: True. Birds are a class of their own, separate from mammals. """ Result: > Finished chain. > Finished chain. > Finished chain. 'Birds are not mammals, but they are a class of their own. They lay eggs, unlike mammals which give birth to live young.' previous LLMRequestsChain next Moderation By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html
67b839a0f41c-0
.ipynb .pdf LLMCheckerChain LLMCheckerChain# This notebook showcases how to use LLMCheckerChain. from langchain.chains import LLMCheckerChain from langchain.llms import OpenAI llm = OpenAI(temperature=0.7) text = "What type of mammal lays the biggest eggs?" checker_chain = LLMCheckerChain.from_llm(llm, verbose=True) checker_chain.run(text) > Entering new LLMCheckerChain chain... > Entering new SequentialChain chain... > Finished chain. > Finished chain. ' No mammal lays the biggest eggs. The Elephant Bird, which was a species of giant bird, laid the largest eggs of any bird.' previous BashChain next LLM Math By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/chains/examples/llm_checker.html
35159417279b-0
.ipynb .pdf LLMRequestsChain LLMRequestsChain# Using the request library to get HTML results from a URL and then an LLM to parse results from langchain.llms import OpenAI from langchain.chains import LLMRequestsChain, LLMChain from langchain.prompts import PromptTemplate template = """Between >>> and <<< are the raw search result text from google. Extract the answer to the question '{query}' or say "not found" if the information is not contained. Use the format Extracted:<answer or "not found"> >>> {requests_result} <<< Extracted:""" PROMPT = PromptTemplate( input_variables=["query", "requests_result"], template=template, ) chain = LLMRequestsChain(llm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=PROMPT)) question = "What are the Three (3) biggest countries, and their respective sizes?" inputs = { "query": question, "url": "https://www.google.com/search?q=" + question.replace(" ", "+") } chain(inputs) {'query': 'What are the Three (3) biggest countries, and their respective sizes?', 'url': 'https://www.google.com/search?q=What+are+the+Three+(3)+biggest+countries,+and+their+respective+sizes?', 'output': ' Russia (17,098,242 km²), Canada (9,984,670 km²), United States (9,826,675 km²)'} previous LLM Math next LLMSummarizationCheckerChain By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/chains/examples/llm_requests.html
05d2ce2554e8-0
.ipynb .pdf BashChain Contents Customize Prompt Persistent Terminal BashChain# This notebook showcases using LLMs and a bash process to perform simple filesystem commands. from langchain.chains import LLMBashChain from langchain.llms import OpenAI llm = OpenAI(temperature=0) text = "Please write a bash script that prints 'Hello World' to the console." bash_chain = LLMBashChain.from_llm(llm, verbose=True) bash_chain.run(text) > Entering new LLMBashChain chain... Please write a bash script that prints 'Hello World' to the console. ```bash echo "Hello World" ``` Code: ['echo "Hello World"'] Answer: Hello World > Finished chain. 'Hello World\n' Customize Prompt# You can also customize the prompt that is used. Here is an example prompting to avoid using the ‘echo’ utility from langchain.prompts.prompt import PromptTemplate from langchain.chains.llm_bash.prompt import BashOutputParser _PROMPT_TEMPLATE = """If someone asks you to perform a task, your job is to come up with a series of bash commands that will perform the task. There is no need to put "#!/bin/bash" in your answer. Make sure to reason step by step, using this format: Question: "copy the files in the directory named 'target' into a new directory at the same level as target called 'myNewDirectory'" I need to take the following actions: - List all files in the directory - Create a new directory - Copy the files from the first directory into the second directory ```bash ls mkdir myNewDirectory cp -r target/* myNewDirectory ``` Do not use 'echo' when writing the script. That is the format. Begin!
https://python.langchain.com/en/latest/modules/chains/examples/llm_bash.html
05d2ce2554e8-1
Do not use 'echo' when writing the script. That is the format. Begin! Question: {question}""" PROMPT = PromptTemplate(input_variables=["question"], template=_PROMPT_TEMPLATE, output_parser=BashOutputParser()) bash_chain = LLMBashChain.from_llm(llm, prompt=PROMPT, verbose=True) text = "Please write a bash script that prints 'Hello World' to the console." bash_chain.run(text) > Entering new LLMBashChain chain... Please write a bash script that prints 'Hello World' to the console. ```bash printf "Hello World\n" ``` Code: ['printf "Hello World\\n"'] Answer: Hello World > Finished chain. 'Hello World\n' Persistent Terminal# By default, the chain will run in a separate subprocess each time it is called. This behavior can be changed by instantiating with a persistent bash process. from langchain.utilities.bash import BashProcess persistent_process = BashProcess(persistent=True) bash_chain = LLMBashChain.from_llm(llm, bash_process=persistent_process, verbose=True) text = "List the current directory then move up a level." bash_chain.run(text) > Entering new LLMBashChain chain... List the current directory then move up a level. ```bash ls cd .. ``` Code: ['ls', 'cd ..'] Answer: api.ipynb llm_summarization_checker.ipynb constitutional_chain.ipynb moderation.ipynb llm_bash.ipynb openai_openapi.yaml llm_checker.ipynb openapi.ipynb llm_math.ipynb pal.ipynb llm_requests.ipynb sqlite.ipynb > Finished chain.
https://python.langchain.com/en/latest/modules/chains/examples/llm_bash.html
05d2ce2554e8-2
llm_requests.ipynb sqlite.ipynb > Finished chain. 'api.ipynb\t\t\tllm_summarization_checker.ipynb\r\nconstitutional_chain.ipynb\tmoderation.ipynb\r\nllm_bash.ipynb\t\t\topenai_openapi.yaml\r\nllm_checker.ipynb\t\topenapi.ipynb\r\nllm_math.ipynb\t\t\tpal.ipynb\r\nllm_requests.ipynb\t\tsqlite.ipynb' # Run the same command again and see that the state is maintained between calls bash_chain.run(text) > Entering new LLMBashChain chain... List the current directory then move up a level. ```bash ls cd .. ``` Code: ['ls', 'cd ..'] Answer: examples getting_started.ipynb index_examples generic how_to_guides.rst > Finished chain. 'examples\t\tgetting_started.ipynb\tindex_examples\r\ngeneric\t\t\thow_to_guides.rst' previous GraphCypherQAChain next LLMCheckerChain Contents Customize Prompt Persistent Terminal By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/chains/examples/llm_bash.html
39fb24e40cf6-0
.ipynb .pdf FLARE Contents Imports Retriever FLARE Chain FLARE# This notebook is an implementation of Forward-Looking Active REtrieval augmented generation (FLARE). Please see the original repo here. The basic idea is: Start answering a question If you start generating tokens the model is uncertain about, look up relevant documents Use those documents to continue generating Repeat until finished There is a lot of cool detail in how the lookup of relevant documents is done. Basically, the tokens that model is uncertain about are highlighted, and then an LLM is called to generate a question that would lead to that answer. For example, if the generated text is Joe Biden went to Harvard, and the tokens the model was uncertain about was Harvard, then a good generated question would be where did Joe Biden go to college. This generated question is then used in a retrieval step to fetch relevant documents. In order to set up this chain, we will need three things: An LLM to generate the answer An LLM to generate hypothetical questions to use in retrieval A retriever to use to look up answers for The LLM that we use to generate the answer needs to return logprobs so we can identify uncertain tokens. For that reason, we HIGHLY recommend that you use the OpenAI wrapper (NB: not the ChatOpenAI wrapper, as that does not return logprobs). The LLM we use to generate hypothetical questions to use in retrieval can be anything. In this notebook we will use ChatOpenAI because it is fast and cheap. The retriever can be anything. In this notebook we will use SERPER search engine, because it is cheap. Other important parameters to understand: max_generation_len: The maximum number of tokens to generate before stopping to check if any are uncertain min_prob: Any tokens generated with probability below this will be considered uncertain
https://python.langchain.com/en/latest/modules/chains/examples/flare.html
39fb24e40cf6-1
min_prob: Any tokens generated with probability below this will be considered uncertain Imports# import os os.environ["SERPER_API_KEY"] = "" import re import numpy as np from langchain.schema import BaseRetriever from langchain.utilities import GoogleSerperAPIWrapper from langchain.embeddings import OpenAIEmbeddings from langchain.chat_models import ChatOpenAI from langchain.llms import OpenAI from langchain.schema import Document Retriever# class SerperSearchRetriever(BaseRetriever): def __init__(self, search): self.search = search def get_relevant_documents(self, query: str): return [Document(page_content=self.search.run(query))] async def aget_relevant_documents(self, query: str): raise NotImplemented retriever = SerperSearchRetriever(GoogleSerperAPIWrapper()) FLARE Chain# # We set this so we can see what exactly is going on import langchain langchain.verbose = True from langchain.chains import FlareChain flare = FlareChain.from_llm( ChatOpenAI(temperature=0), retriever=retriever, max_generation_len=164, min_prob=.3, ) query = "explain in great detail the difference between the langchain framework and baby agi" flare.run(query) > Entering new FlareChain chain... Current Response: Prompt after formatting: Respond to the user message using any relevant context. If context is provided, you should ground your answer in that context. Once you're done responding return FINISHED. >>> CONTEXT: >>> USER INPUT: explain in great detail the difference between the langchain framework and baby agi >>> RESPONSE:
https://python.langchain.com/en/latest/modules/chains/examples/flare.html
39fb24e40cf6-2
>>> RESPONSE: > Entering new QuestionGeneratorChain chain... Prompt after formatting: Given a user input and an existing partial response as context, ask a question to which the answer is the given term/entity/phrase: >>> USER INPUT: explain in great detail the difference between the langchain framework and baby agi >>> EXISTING PARTIAL RESPONSE: The Langchain Framework is a decentralized platform for natural language processing (NLP) applications. It uses a blockchain-based distributed ledger to store and process data, allowing for secure and transparent data sharing. The Langchain Framework also provides a set of tools and services to help developers create and deploy NLP applications. Baby AGI, on the other hand, is an artificial general intelligence (AGI) platform. It uses a combination of deep learning and reinforcement learning to create an AI system that can learn and adapt to new tasks. Baby AGI is designed to be a general-purpose AI system that can be used for a variety of applications, including natural language processing. In summary, the Langchain Framework is a platform for NLP applications, while Baby AGI is an AI system designed for The question to which the answer is the term/entity/phrase " decentralized platform for natural language processing" is: Prompt after formatting: Given a user input and an existing partial response as context, ask a question to which the answer is the given term/entity/phrase: >>> USER INPUT: explain in great detail the difference between the langchain framework and baby agi >>> EXISTING PARTIAL RESPONSE: The Langchain Framework is a decentralized platform for natural language processing (NLP) applications. It uses a blockchain-based distributed ledger to store and process data, allowing for secure and transparent data sharing. The Langchain Framework also provides a set of tools and services to help developers create and deploy NLP applications.
https://python.langchain.com/en/latest/modules/chains/examples/flare.html
39fb24e40cf6-3
Baby AGI, on the other hand, is an artificial general intelligence (AGI) platform. It uses a combination of deep learning and reinforcement learning to create an AI system that can learn and adapt to new tasks. Baby AGI is designed to be a general-purpose AI system that can be used for a variety of applications, including natural language processing. In summary, the Langchain Framework is a platform for NLP applications, while Baby AGI is an AI system designed for The question to which the answer is the term/entity/phrase " uses a blockchain" is: Prompt after formatting: Given a user input and an existing partial response as context, ask a question to which the answer is the given term/entity/phrase: >>> USER INPUT: explain in great detail the difference between the langchain framework and baby agi >>> EXISTING PARTIAL RESPONSE: The Langchain Framework is a decentralized platform for natural language processing (NLP) applications. It uses a blockchain-based distributed ledger to store and process data, allowing for secure and transparent data sharing. The Langchain Framework also provides a set of tools and services to help developers create and deploy NLP applications. Baby AGI, on the other hand, is an artificial general intelligence (AGI) platform. It uses a combination of deep learning and reinforcement learning to create an AI system that can learn and adapt to new tasks. Baby AGI is designed to be a general-purpose AI system that can be used for a variety of applications, including natural language processing. In summary, the Langchain Framework is a platform for NLP applications, while Baby AGI is an AI system designed for The question to which the answer is the term/entity/phrase " distributed ledger to" is: Prompt after formatting: Given a user input and an existing partial response as context, ask a question to which the answer is the given term/entity/phrase:
https://python.langchain.com/en/latest/modules/chains/examples/flare.html
39fb24e40cf6-4
>>> USER INPUT: explain in great detail the difference between the langchain framework and baby agi >>> EXISTING PARTIAL RESPONSE: The Langchain Framework is a decentralized platform for natural language processing (NLP) applications. It uses a blockchain-based distributed ledger to store and process data, allowing for secure and transparent data sharing. The Langchain Framework also provides a set of tools and services to help developers create and deploy NLP applications. Baby AGI, on the other hand, is an artificial general intelligence (AGI) platform. It uses a combination of deep learning and reinforcement learning to create an AI system that can learn and adapt to new tasks. Baby AGI is designed to be a general-purpose AI system that can be used for a variety of applications, including natural language processing. In summary, the Langchain Framework is a platform for NLP applications, while Baby AGI is an AI system designed for The question to which the answer is the term/entity/phrase " process data, allowing for secure and transparent data sharing." is: Prompt after formatting: Given a user input and an existing partial response as context, ask a question to which the answer is the given term/entity/phrase: >>> USER INPUT: explain in great detail the difference between the langchain framework and baby agi >>> EXISTING PARTIAL RESPONSE: The Langchain Framework is a decentralized platform for natural language processing (NLP) applications. It uses a blockchain-based distributed ledger to store and process data, allowing for secure and transparent data sharing. The Langchain Framework also provides a set of tools and services to help developers create and deploy NLP applications.
https://python.langchain.com/en/latest/modules/chains/examples/flare.html
39fb24e40cf6-5
Baby AGI, on the other hand, is an artificial general intelligence (AGI) platform. It uses a combination of deep learning and reinforcement learning to create an AI system that can learn and adapt to new tasks. Baby AGI is designed to be a general-purpose AI system that can be used for a variety of applications, including natural language processing. In summary, the Langchain Framework is a platform for NLP applications, while Baby AGI is an AI system designed for The question to which the answer is the term/entity/phrase " set of tools" is: Prompt after formatting: Given a user input and an existing partial response as context, ask a question to which the answer is the given term/entity/phrase: >>> USER INPUT: explain in great detail the difference between the langchain framework and baby agi >>> EXISTING PARTIAL RESPONSE: The Langchain Framework is a decentralized platform for natural language processing (NLP) applications. It uses a blockchain-based distributed ledger to store and process data, allowing for secure and transparent data sharing. The Langchain Framework also provides a set of tools and services to help developers create and deploy NLP applications. Baby AGI, on the other hand, is an artificial general intelligence (AGI) platform. It uses a combination of deep learning and reinforcement learning to create an AI system that can learn and adapt to new tasks. Baby AGI is designed to be a general-purpose AI system that can be used for a variety of applications, including natural language processing. In summary, the Langchain Framework is a platform for NLP applications, while Baby AGI is an AI system designed for The question to which the answer is the term/entity/phrase " help developers create" is: Prompt after formatting: Given a user input and an existing partial response as context, ask a question to which the answer is the given term/entity/phrase:
https://python.langchain.com/en/latest/modules/chains/examples/flare.html
39fb24e40cf6-6
>>> USER INPUT: explain in great detail the difference between the langchain framework and baby agi >>> EXISTING PARTIAL RESPONSE: The Langchain Framework is a decentralized platform for natural language processing (NLP) applications. It uses a blockchain-based distributed ledger to store and process data, allowing for secure and transparent data sharing. The Langchain Framework also provides a set of tools and services to help developers create and deploy NLP applications. Baby AGI, on the other hand, is an artificial general intelligence (AGI) platform. It uses a combination of deep learning and reinforcement learning to create an AI system that can learn and adapt to new tasks. Baby AGI is designed to be a general-purpose AI system that can be used for a variety of applications, including natural language processing. In summary, the Langchain Framework is a platform for NLP applications, while Baby AGI is an AI system designed for The question to which the answer is the term/entity/phrase " create an AI system" is: Prompt after formatting: Given a user input and an existing partial response as context, ask a question to which the answer is the given term/entity/phrase: >>> USER INPUT: explain in great detail the difference between the langchain framework and baby agi >>> EXISTING PARTIAL RESPONSE: The Langchain Framework is a decentralized platform for natural language processing (NLP) applications. It uses a blockchain-based distributed ledger to store and process data, allowing for secure and transparent data sharing. The Langchain Framework also provides a set of tools and services to help developers create and deploy NLP applications.
https://python.langchain.com/en/latest/modules/chains/examples/flare.html
39fb24e40cf6-7
Baby AGI, on the other hand, is an artificial general intelligence (AGI) platform. It uses a combination of deep learning and reinforcement learning to create an AI system that can learn and adapt to new tasks. Baby AGI is designed to be a general-purpose AI system that can be used for a variety of applications, including natural language processing. In summary, the Langchain Framework is a platform for NLP applications, while Baby AGI is an AI system designed for The question to which the answer is the term/entity/phrase " NLP applications" is: > Finished chain. Generated Questions: ['What is the Langchain Framework?', 'What technology does the Langchain Framework use to store and process data for secure and transparent data sharing?', 'What technology does the Langchain Framework use to store and process data?', 'What does the Langchain Framework use a blockchain-based distributed ledger for?', 'What does the Langchain Framework provide in addition to a decentralized platform for natural language processing applications?', 'What set of tools and services does the Langchain Framework provide?', 'What is the purpose of Baby AGI?', 'What type of applications is the Langchain Framework designed for?'] > Entering new _OpenAIResponseChain chain... Prompt after formatting: Respond to the user message using any relevant context. If context is provided, you should ground your answer in that context. Once you're done responding return FINISHED.
https://python.langchain.com/en/latest/modules/chains/examples/flare.html
39fb24e40cf6-8
>>> CONTEXT: LangChain: Software. LangChain is a software development framework designed to simplify the creation of applications using large language models. LangChain Initial release date: October 2022. LangChain Programming languages: Python and JavaScript. LangChain Developer(s): Harrison Chase. LangChain License: MIT License. LangChain is a framework for developing applications powered by language models. We believe that the most powerful and differentiated applications will not only ... Type: Software framework. At its core, LangChain is a framework built around LLMs. We can use it for chatbots, Generative Question-Answering (GQA), summarization, and much more. LangChain is a powerful tool that can be used to work with Large Language Models (LLMs). LLMs are very general in nature, which means that while they can ... LangChain is an intuitive framework created to assist in developing applications driven by a language model, such as OpenAI or Hugging Face. LangChain is a software development framework designed to simplify the creation of applications using large language models (LLMs). Written in: Python and JavaScript. Initial release: October 2022. LangChain - The A.I-native developer toolkit We started LangChain with the intent to build a modular and flexible framework for developing A.I- ... LangChain explained in 3 minutes - LangChain is a ... Duration: 3:03. Posted: Apr 13, 2023. LangChain is a framework built to help you build LLM-powered applications more easily by providing you with the following:. LangChain is a framework that enables quick and easy development of applications that make use of Large Language Models, for example, GPT-3. LangChain is a powerful open-source framework for developing applications powered by language models. It connects to the AI models you want to ...
https://python.langchain.com/en/latest/modules/chains/examples/flare.html
39fb24e40cf6-9
LangChain is a framework for including AI from large language models inside data pipelines and applications. This tutorial provides an overview of what you ... Missing: secure | Must include:secure. Blockchain is the best way to secure the data of the shared community. Utilizing the capabilities of the blockchain nobody can read or interfere ... This modern technology consists of a chain of blocks that allows to securely store all committed transactions using shared and distributed ... A Blockchain network is used in the healthcare system to preserve and exchange patient data through hospitals, diagnostic laboratories, pharmacy firms, and ... In this article, I will walk you through the process of using the LangChain.js library with Google Cloud Functions, helping you leverage the ... LangChain is an intuitive framework created to assist in developing applications driven by a language model, such as OpenAI or Hugging Face. Missing: transparent | Must include:transparent. This technology keeps a distributed ledger on each blockchain node, making it more secure and transparent. The blockchain network can operate smart ... blockchain technology can offer a highly secured health data ledger to ... framework can be employed to store encrypted healthcare data in a ... In a simplified way, Blockchain is a data structure that stores transactions in an ordered way and linked to the previous block, serving as a ... Blockchain technology is a decentralized, distributed ledger that stores the record of ownership of digital assets. Missing: Langchain | Must include:Langchain.
https://python.langchain.com/en/latest/modules/chains/examples/flare.html
39fb24e40cf6-10
LangChain is a framework for including AI from large language models inside data pipelines and applications. This tutorial provides an overview of what you ... LangChain is an intuitive framework created to assist in developing applications driven by a language model, such as OpenAI or Hugging Face. This documentation covers the steps to integrate Pinecone, a high-performance vector database, with LangChain, a framework for building applications powered ... The ability to connect to any model, ingest any custom database, and build upon a framework that can take action provides numerous use cases for ... With LangChain, developers can use a framework that abstracts the core building blocks of LLM applications. LangChain empowers developers to ... Build a question-answering tool based on financial data with LangChain & Deep Lake's unified & streamable data store. Browse applications built on LangChain technology. Explore PoC and MVP applications created by our community and discover innovative use cases for LangChain ... LangChain is a great framework that can be used for developing applications powered by LLMs. When you intend to enhance your application ... In this blog, we'll introduce you to LangChain and Ray Serve and how to use them to build a search engine using LLM embeddings and a vector ... The LinkChain Framework simplifies embedding creation and storage using Pinecone and Chroma, with code that loads files, splits documents, and creates embedding ... Missing: technology | Must include:technology.
https://python.langchain.com/en/latest/modules/chains/examples/flare.html
39fb24e40cf6-11
Blockchain is one type of a distributed ledger. Distributed ledgers use independent computers (referred to as nodes) to record, share and ... Missing: Langchain | Must include:Langchain. Blockchain is used in distributed storage software where huge data is broken down into chunks. This is available in encrypted data across a ... People sometimes use the terms 'Blockchain' and 'Distributed Ledger' interchangeably. This post aims to analyze the features of each. A distributed ledger ... Missing: Framework | Must include:Framework. Think of a “distributed ledger” that uses cryptography to allow each participant in the transaction to add to the ledger in a secure way without ... In this paper, we provide an overview of the history of trade settlement and discuss this nascent technology that may now transform traditional ... Missing: Langchain | Must include:Langchain. LangChain is a blockchain-based language education platform that aims to revolutionize the way people learn languages. Missing: Framework | Must include:Framework. It uses the distributed ledger technology framework and Smart contract engine for building scalable Business Blockchain applications. The fabric ... It looks at the assets the use case is handling, the different parties conducting transactions, and the smart contract, distributed ... Are you curious to know how Blockchain and Distributed ... Duration: 44:31. Posted: May 4, 2021. A blockchain is a distributed and immutable ledger to transfer ownership, record transactions, track assets, and ensure transparency, security, trust and value ... Missing: Langchain | Must include:Langchain.
https://python.langchain.com/en/latest/modules/chains/examples/flare.html
39fb24e40cf6-12
LangChain is an intuitive framework created to assist in developing applications driven by a language model, such as OpenAI or Hugging Face. Missing: decentralized | Must include:decentralized. LangChain, created by Harrison Chase, is a Python library that provides out-of-the-box support to build NLP applications using LLMs. Missing: decentralized | Must include:decentralized. LangChain provides a standard interface for chains, enabling developers to create sequences of calls that go beyond a single LLM call. Chains ... Missing: decentralized platform natural. LangChain is a powerful framework that simplifies the process of building advanced language model applications. Missing: platform | Must include:platform. Are your language models ignoring previous instructions ... Duration: 32:23. Posted: Feb 21, 2023. LangChain is a framework that enables quick and easy development of applications ... Prompting is the new way of programming NLP models. Missing: decentralized platform. It then uses natural language processing and machine learning algorithms to search ... Summarization is handled via cohere, QnA is handled via langchain, ... LangChain is a framework for developing applications powered by language models. ... There are several main modules that LangChain provides support for. Missing: decentralized platform. In the healthcare-chain system, blockchain provides an appreciated secure ... The entire process of adding new and previous block data is performed based on ... ChatGPT is a large language model developed by OpenAI, ... tool for a wide range of applications, including natural language processing, ...
https://python.langchain.com/en/latest/modules/chains/examples/flare.html
39fb24e40cf6-13
LangChain is a powerful tool that can be used to work with Large Language ... If an API key has been provided, create an OpenAI language model instance At its core, LangChain is a framework built around LLMs. We can use it for chatbots, Generative Question-Answering (GQA), summarization, and much more. A tutorial of the six core modules of the LangChain Python package covering models, prompts, chains, agents, indexes, and memory with OpenAI ... LangChain's collection of tools refers to a set of tools provided by the LangChain framework for developing applications powered by language models. LangChain is a framework for developing applications powered by language models. We believe that the most powerful and differentiated applications will not only ... LangChain is an open-source library that provides developers with the tools to build applications powered by large language models (LLMs). LangChain is a framework for including AI from large language models inside data pipelines and applications. This tutorial provides an overview of what you ... Plan-and-Execute Agents · Feature Stores and LLMs · Structured Tools · Auto-Evaluator Opportunities · Callbacks Improvements · Unleashing the power ... Tool: A function that performs a specific duty. This can be things like: Google Search, Database lookup, Python REPL, other chains. · LLM: The language model ... LangChain provides a standard interface for chains, lots of integrations with other tools, and end-to-end chains for common applications. Baby AGI has the ability to complete tasks, generate new tasks based on previous results, and prioritize tasks in real-time. This system is exploring and demonstrating to us the potential of large language models, such as GPT and how it can autonomously perform tasks. Apr 17, 2023
https://python.langchain.com/en/latest/modules/chains/examples/flare.html
39fb24e40cf6-14
At its core, LangChain is a framework built around LLMs. We can use it for chatbots, Generative Question-Answering (GQA), summarization, and much more. The core idea of the library is that we can “chain” together different components to create more advanced use cases around LLMs. >>> USER INPUT: explain in great detail the difference between the langchain framework and baby agi >>> RESPONSE: > Finished chain. > Finished chain. ' LangChain is a framework for developing applications powered by language models. It provides a standard interface for chains, lots of integrations with other tools, and end-to-end chains for common applications. On the other hand, Baby AGI is an AI system that is exploring and demonstrating the potential of large language models, such as GPT, and how it can autonomously perform tasks. Baby AGI has the ability to complete tasks, generate new tasks based on previous results, and prioritize tasks in real-time. ' llm = OpenAI() llm(query)
https://python.langchain.com/en/latest/modules/chains/examples/flare.html
39fb24e40cf6-15
llm = OpenAI() llm(query) '\n\nThe Langchain framework and Baby AGI are both artificial intelligence (AI) frameworks that are used to create intelligent agents. The Langchain framework is a supervised learning system that is based on the concept of “language chains”. It uses a set of rules to map natural language inputs to specific outputs. It is a general-purpose AI framework and can be used to build applications such as natural language processing (NLP), chatbots, and more.\n\nBaby AGI, on the other hand, is an unsupervised learning system that uses neural networks and reinforcement learning to learn from its environment. It is used to create intelligent agents that can adapt to changing environments. It is a more advanced AI system and can be used to build more complex applications such as game playing, robotic vision, and more.\n\nThe main difference between the two is that the Langchain framework uses supervised learning while Baby AGI uses unsupervised learning. The Langchain framework is a general-purpose AI framework that can be used for various applications, while Baby AGI is a more advanced AI system that can be used to create more complex applications.' flare.run("how are the origin stories of langchain and bitcoin similar or different?") > Entering new FlareChain chain... Current Response: Prompt after formatting: Respond to the user message using any relevant context. If context is provided, you should ground your answer in that context. Once you're done responding return FINISHED. >>> CONTEXT: >>> USER INPUT: how are the origin stories of langchain and bitcoin similar or different? >>> RESPONSE: > Entering new QuestionGeneratorChain chain... Prompt after formatting: Given a user input and an existing partial response as context, ask a question to which the answer is the given term/entity/phrase:
https://python.langchain.com/en/latest/modules/chains/examples/flare.html
39fb24e40cf6-16
>>> USER INPUT: how are the origin stories of langchain and bitcoin similar or different? >>> EXISTING PARTIAL RESPONSE: Langchain and Bitcoin have very different origin stories. Bitcoin was created by the mysterious Satoshi Nakamoto in 2008 as a decentralized digital currency. Langchain, on the other hand, was created in 2020 by a team of developers as a platform for creating and managing decentralized language learning applications. FINISHED The question to which the answer is the term/entity/phrase " very different origin" is: Prompt after formatting: Given a user input and an existing partial response as context, ask a question to which the answer is the given term/entity/phrase: >>> USER INPUT: how are the origin stories of langchain and bitcoin similar or different? >>> EXISTING PARTIAL RESPONSE: Langchain and Bitcoin have very different origin stories. Bitcoin was created by the mysterious Satoshi Nakamoto in 2008 as a decentralized digital currency. Langchain, on the other hand, was created in 2020 by a team of developers as a platform for creating and managing decentralized language learning applications. FINISHED The question to which the answer is the term/entity/phrase " 2020 by a" is: Prompt after formatting: Given a user input and an existing partial response as context, ask a question to which the answer is the given term/entity/phrase: >>> USER INPUT: how are the origin stories of langchain and bitcoin similar or different? >>> EXISTING PARTIAL RESPONSE: Langchain and Bitcoin have very different origin stories. Bitcoin was created by the mysterious Satoshi Nakamoto in 2008 as a decentralized digital currency. Langchain, on the other hand, was created in 2020 by a team of developers as a platform for creating and managing decentralized language learning applications. FINISHED
https://python.langchain.com/en/latest/modules/chains/examples/flare.html
39fb24e40cf6-17
FINISHED The question to which the answer is the term/entity/phrase " developers as a platform for creating and managing decentralized language learning applications." is: > Finished chain. Generated Questions: ['How would you describe the origin stories of Langchain and Bitcoin in terms of their similarities or differences?', 'When was Langchain created and by whom?', 'What was the purpose of creating Langchain?'] > Entering new _OpenAIResponseChain chain... Prompt after formatting: Respond to the user message using any relevant context. If context is provided, you should ground your answer in that context. Once you're done responding return FINISHED.
https://python.langchain.com/en/latest/modules/chains/examples/flare.html
39fb24e40cf6-18
>>> CONTEXT: Bitcoin and Ethereum have many similarities but different long-term visions and limitations. Ethereum changed from proof of work to proof of ... Bitcoin will be around for many years and examining its white paper origins is a great exercise in understanding why. Satoshi Nakamoto's blueprint describes ... Bitcoin is a new currency that was created in 2009 by an unknown person using the alias Satoshi Nakamoto. Transactions are made with no middle men – meaning, no ... Missing: Langchain | Must include:Langchain. By comparison, Bitcoin transaction speeds are tremendously lower. ... learn about its history and its role in the emergence of the Bitcoin ... LangChain is a powerful framework that simplifies the process of ... tasks like document retrieval, clustering, and similarity comparisons. Key terms: Bitcoin System, Blockchain Technology, ... Furthermore, the research paper will discuss and compare the five payment. Blockchain first appeared in Nakamoto's Bitcoin white paper that describes a new decentralized cryptocurrency [1]. Bitcoin takes the blockchain technology ... Missing: stories | Must include:stories. A score of 0 means there were not enough data for this term. Google trends was accessed on 5 November 2018 with searches for bitcoin, euro, gold ... Contracts, transactions, and records of them provide critical structure in our economic system, but they haven't kept up with the world's digital ... Missing: Langchain | Must include:Langchain. Of course, traders try to make a profit on their portfolio in this way.The difference between investing and trading is the regularity with which ... After all these giant leaps forward in the LLM space, OpenAI released ChatGPT — thrusting LLMs into the spotlight. LangChain appeared around the same time. Its creator, Harrison Chase, made the first commit in late October 2022. Leaving a short couple of months of development before getting caught in the LLM wave.
https://python.langchain.com/en/latest/modules/chains/examples/flare.html
39fb24e40cf6-19
At its core, LangChain is a framework built around LLMs. We can use it for chatbots, Generative Question-Answering (GQA), summarization, and much more. The core idea of the library is that we can “chain” together different components to create more advanced use cases around LLMs. >>> USER INPUT: how are the origin stories of langchain and bitcoin similar or different? >>> RESPONSE: > Finished chain. > Finished chain. ' The origin stories of LangChain and Bitcoin are quite different. Bitcoin was created in 2009 by an unknown person using the alias Satoshi Nakamoto. LangChain was created in late October 2022 by Harrison Chase. Bitcoin is a decentralized cryptocurrency, while LangChain is a framework built around LLMs. ' previous Self-Critique Chain with Constitutional AI next GraphCypherQAChain Contents Imports Retriever FLARE Chain By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/chains/examples/flare.html
e36ebc2db1a2-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 LLMMathChain chain... What is 13 raised to the .3432 power? ```text 13 ** .3432 ``` ...numexpr.evaluate("13 ** .3432")... Answer: 2.4116004626599237 > Finished chain. 'Answer: 2.4116004626599237' previous LLMCheckerChain next LLMRequestsChain By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/chains/examples/llm_math.html
d6cb37d1256e-0
.ipynb .pdf Router Chains: Selecting from multiple prompts with MultiRetrievalQAChain Router Chains: Selecting from multiple prompts with MultiRetrievalQAChain# This notebook demonstrates how to use the RouterChain paradigm to create a chain that dynamically selects which Retrieval system to use. Specifically we show how to use the MultiRetrievalQAChain to create a question-answering chain that selects the retrieval QA chain which is most relevant for a given question, and then answers the question using it. from langchain.chains.router import MultiRetrievalQAChain from langchain.llms import OpenAI from langchain.embeddings import OpenAIEmbeddings from langchain.document_loaders import TextLoader from langchain.vectorstores import FAISS sou_docs = TextLoader('../../state_of_the_union.txt').load_and_split() sou_retriever = FAISS.from_documents(sou_docs, OpenAIEmbeddings()).as_retriever() pg_docs = TextLoader('../../paul_graham_essay.txt').load_and_split() pg_retriever = FAISS.from_documents(pg_docs, OpenAIEmbeddings()).as_retriever() personal_texts = [ "I love apple pie", "My favorite color is fuchsia", "My dream is to become a professional dancer", "I broke my arm when I was 12", "My parents are from Peru", ] personal_retriever = FAISS.from_texts(personal_texts, OpenAIEmbeddings()).as_retriever() retriever_infos = [ { "name": "state of the union", "description": "Good for answering questions about the 2023 State of the Union address", "retriever": sou_retriever }, {
https://python.langchain.com/en/latest/modules/chains/examples/multi_retrieval_qa_router.html
d6cb37d1256e-1
"retriever": sou_retriever }, { "name": "pg essay", "description": "Good for answer quesitons about Paul Graham's essay on his career", "retriever": pg_retriever }, { "name": "personal", "description": "Good for answering questions about me", "retriever": personal_retriever } ] chain = MultiRetrievalQAChain.from_retrievers(OpenAI(), retriever_infos, verbose=True) print(chain.run("What did the president say about the economy?")) > Entering new MultiRetrievalQAChain chain... state of the union: {'query': 'What did the president say about the economy in the 2023 State of the Union address?'} > Finished chain. The president said that the economy was stronger than it had been a year prior, and that the American Rescue Plan helped create record job growth and fuel economic relief for millions of Americans. He also proposed a plan to fight inflation and lower costs for families, including cutting the cost of prescription drugs and energy, providing investments and tax credits for energy efficiency, and increasing access to child care and Pre-K. print(chain.run("What is something Paul Graham regrets about his work?")) > Entering new MultiRetrievalQAChain chain... pg essay: {'query': 'What is something Paul Graham regrets about his work?'} > Finished chain. Paul Graham regrets that he did not take a vacation after selling his company, instead of immediately starting to paint. print(chain.run("What is my background?")) > Entering new MultiRetrievalQAChain chain... personal: {'query': 'What is my background?'} > Finished chain. Your background is Peruvian.
https://python.langchain.com/en/latest/modules/chains/examples/multi_retrieval_qa_router.html
d6cb37d1256e-2
> Finished chain. Your background is Peruvian. print(chain.run("What year was the Internet created in?")) > Entering new MultiRetrievalQAChain chain... None: {'query': 'What year was the Internet created in?'} > Finished chain. The Internet was created in 1969 through a project called ARPANET, which was funded by the United States Department of Defense. However, the World Wide Web, which is often confused with the Internet, was created in 1989 by British computer scientist Tim Berners-Lee. previous Router Chains: Selecting from multiple prompts with MultiPromptChain next OpenAPI Chain By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/chains/examples/multi_retrieval_qa_router.html
1869bf03b621-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 instance. One option is to create a free Neo4j database instance in their Aura cloud service. You can also run the database locally using the Neo4j Desktop application, or running a docker container. You can run a local docker container by running the executing the following script: docker run \ --name neo4j \ -p 7474:7474 -p 7687:7687 \ -d \ -e NEO4J_AUTH=neo4j/pleaseletmein \ -e NEO4J_PLUGINS=\[\"apoc\"\] \ neo4j:latest If you are using the docker container, you need to wait a couple of second for the database to start. from langchain.chat_models import ChatOpenAI from langchain.chains import GraphCypherQAChain from langchain.graphs import Neo4jGraph graph = Neo4jGraph( url="bolt://localhost:7687", username="neo4j", password="pleaseletmein" ) Seeding the database# Assuming your database is empty, you can populate it using Cypher query language. The following Cypher statement is idempotent, which means the database information will be the same if you run it one or multiple times. graph.query( """ MERGE (m:Movie {name:"Top Gun"}) WITH m
https://python.langchain.com/en/latest/modules/chains/examples/graph_cypher_qa.html
1869bf03b621-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 statements. graph.refresh_schema() print(graph.get_schema) Node properties are the following: [{'properties': [{'property': 'name', 'type': 'STRING'}], 'labels': 'Movie'}, {'properties': [{'property': 'name', 'type': 'STRING'}], 'labels': 'Actor'}] Relationship properties are the following: [] The relationships are the following: ['(:Actor)-[:ACTED_IN]->(:Movie)'] Querying the graph# We can now use the graph cypher QA chain to ask question of the graph chain = GraphCypherQAChain.from_llm( ChatOpenAI(temperature=0), graph=graph, verbose=True ) chain.run("Who played in Top Gun?") > Entering new GraphCypherQAChain chain... Generated Cypher: MATCH (a:Actor)-[:ACTED_IN]->(m:Movie {name: 'Top Gun'}) RETURN a.name Full Context: [{'a.name': 'Tom Cruise'}, {'a.name': 'Val Kilmer'}, {'a.name': 'Anthony Edwards'}, {'a.name': 'Meg Ryan'}] > Finished chain. 'Tom Cruise, Val Kilmer, Anthony Edwards, and Meg Ryan played in Top Gun.' previous FLARE next BashChain Contents Seeding the database Refresh graph schema information
https://python.langchain.com/en/latest/modules/chains/examples/graph_cypher_qa.html
1869bf03b621-2
next BashChain Contents Seeding the database Refresh graph schema information Querying the graph By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/chains/examples/graph_cypher_qa.html
417ee3372fc4-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_prompt(llm, verbose=True) question = "Jan has three times the number of pets as Marcia. Marcia has two more pets than Cindy. If Cindy has four pets, how many total pets do the three have?" pal_chain.run(question) > Entering new PALChain chain... def solution(): """Jan has three times the number of pets as Marcia. Marcia has two more pets than Cindy. If Cindy has four pets, how many total pets do the three have?""" cindy_pets = 4 marcia_pets = cindy_pets + 2 jan_pets = marcia_pets * 3 total_pets = cindy_pets + marcia_pets + jan_pets result = total_pets return result > Finished chain. '28' Colored Objects# pal_chain = PALChain.from_colored_object_prompt(llm, verbose=True) question = "On the desk, you see two blue booklets, two purple booklets, and two yellow pairs of sunglasses. If I remove all the pairs of sunglasses from the desk, how many purple items remain on it?" pal_chain.run(question) > Entering new PALChain chain... # Put objects into a list to record ordering objects = [] objects += [('booklet', 'blue')] * 2 objects += [('booklet', 'purple')] * 2
https://python.langchain.com/en/latest/modules/chains/examples/pal.html
417ee3372fc4-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 > Finished PALChain chain. '2' Intermediate Steps# You can also use the intermediate steps flag to return the code executed that generates the answer. pal_chain = PALChain.from_colored_object_prompt(llm, verbose=True, return_intermediate_steps=True) question = "On the desk, you see two blue booklets, two purple booklets, and two yellow pairs of sunglasses. If I remove all the pairs of sunglasses from the desk, how many purple items remain on it?" result = pal_chain({"question": question}) > Entering new PALChain chain... # Put objects into a list to record ordering objects = [] objects += [('booklet', 'blue')] * 2 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 > Finished chain. result['intermediate_steps']
https://python.langchain.com/en/latest/modules/chains/examples/pal.html
417ee3372fc4-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 objects if object[0] != 'sunglasses']\n\n# Count number of purple objects\nnum_purple = len([object for object in objects if object[1] == 'purple'])\nanswer = num_purple" previous OpenAPI Chain next SQL Chain example Contents Math Prompt Colored Objects Intermediate Steps By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/chains/examples/pal.html
69efe64ae3d7-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 import PromptTemplate from langchain.llms import OpenAI llm = OpenAI(temperature=0) OpenMeteo Example# from langchain.chains.api import open_meteo_docs chain_new = APIChain.from_llm_and_api_docs(llm, open_meteo_docs.OPEN_METEO_DOCS, verbose=True) chain_new.run('What is the weather like right now in Munich, Germany in degrees Fahrenheit?') > Entering new APIChain chain... https://api.open-meteo.com/v1/forecast?latitude=48.1351&longitude=11.5820&temperature_unit=fahrenheit&current_weather=true {"latitude":48.14,"longitude":11.58,"generationtime_ms":0.33104419708251953,"utc_offset_seconds":0,"timezone":"GMT","timezone_abbreviation":"GMT","elevation":521.0,"current_weather":{"temperature":33.4,"windspeed":6.8,"winddirection":198.0,"weathercode":2,"time":"2023-01-16T01:00"}} > Finished chain. ' The current temperature in Munich, Germany is 33.4 degrees Fahrenheit with a windspeed of 6.8 km/h and a wind direction of 198 degrees. The weathercode is 2.' TMDB Example# import os os.environ['TMDB_BEARER_TOKEN'] = "" from langchain.chains.api import tmdb_docs
https://python.langchain.com/en/latest/modules/chains/examples/api.html
69efe64ae3d7-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?query=Avatar&language=en-US
https://python.langchain.com/en/latest/modules/chains/examples/api.html
69efe64ae3d7-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 orders and protecting an alien civilization.","popularity":2041.691,"poster_path":"/jRXYjXNq0Cs2TcJjLkki24MLp7u.jpg","release_date":"2009-12-15","title":"Avatar","video":false,"vote_average":7.6,"vote_count":27777},{"adult":false,"backdrop_path":"/s16H6tpK2utvwDtzZ8Qy4qm5Emw.jpg","genre_ids":[878,12,28],"id":76600,"original_language":"en","original_title":"Avatar: The Way of Water","overview":"Set more than a decade after the events of the first film, learn the story of the Sully family (Jake, Neytiri, and their kids), the trouble that follows them, the lengths they go to keep each other safe, the battles they fight to stay alive, and the tragedies they
https://python.langchain.com/en/latest/modules/chains/examples/api.html
69efe64ae3d7-3
they fight to stay alive, and the tragedies they endure.","popularity":3948.296,"poster_path":"/t6HIqrRAclMCA60NsSmeqe9RmNV.jpg","release_date":"2022-12-14","title":"Avatar: 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 parts of the work on the set.","popularity":541.809,"poster_path":"/sjf3xjuofCtDhZghJRzXlTiEjJe.jpg","release_date":"2010-02-07","title":"Avatar: Creating the World of Pandora","video":false,"vote_average":7.3,"vote_count":35},{"adult":false,"backdrop_path":null,"genre_ids":[99],"id":287003,"original_language":"en","original_title":"Avatar: Scene Deconstruction","overview":"The deconstruction of the Avatar scenes and sets","popularity":394.941,"poster_path":"/uCreCQFReeF0RiIXkQypRYHwikx.jpg","release_date":"2009-12-18","title":"Avatar: Scene
https://python.langchain.com/en/latest/modules/chains/examples/api.html