id stringlengths 14 15 | text stringlengths 101 5.26k | source stringlengths 57 120 |
|---|---|---|
c2ce167601e4-0 | .ipynb
.pdf
How to use the async API for LLMs
How to use the async API for LLMs#
LangChain provides async support for LLMs by leveraging the asyncio library.
Async support is particularly useful for calling multiple LLMs concurrently, as these calls are network-bound. Currently, OpenAI, PromptLayerOpenAI, ChatOpenAI an... | https://langchain.readthedocs.io/en/latest/modules/models/llms/examples/async_llm.html |
e37e16896b6d-0 | .ipynb
.pdf
How to serialize LLM classes
Contents
Loading
Saving
How to serialize LLM classes#
This notebook walks through how to write and read an LLM Configuration to and from disk. This is useful if you want to save the configuration for a given LLM (e.g., the provider, the temperature, etc).
from langchain.llms i... | https://langchain.readthedocs.io/en/latest/modules/models/llms/examples/llm_serialization.html |
f8ece9e39a94-0 | .ipynb
.pdf
How (and why) to use the human input LLM
How (and why) to use the human input LLM#
Similar to the fake LLM, LangChain provides a pseudo LLM class that can be used for testing, debugging, or educational purposes. This allows you to mock out calls to the LLM and simulate how a human would respond if they rece... | https://langchain.readthedocs.io/en/latest/modules/models/llms/examples/human_input_llm.html |
f8ece9e39a94-1 | ... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Begin!
Question: What is 'Bocchi the Rock!'?
Thought:I need to use a tool.
Action: Wikipedia
Action Input: Bocchi the Rock!, Japanese four-panel manga ... | https://langchain.readthedocs.io/en/latest/modules/models/llms/examples/human_input_llm.html |
f8ece9e39a94-2 | Page: Manga Time Kirara
Summary: Manga Time Kirara (まんがタイムきらら, Manga Taimu Kirara) is a Japanese seinen manga magazine published by Houbunsha which mainly serializes four-panel manga. The magazine is sold on the ninth of each month and was first published as a special edition of Manga Time, another Houbunsha magazine, ... | https://langchain.readthedocs.io/en/latest/modules/models/llms/examples/human_input_llm.html |
91e7f8a75056-0 | .ipynb
.pdf
How to stream LLM and Chat Model responses
How to stream LLM and Chat Model responses#
LangChain provides streaming support for LLMs. Currently, we support streaming for the OpenAI, ChatOpenAI, and ChatAnthropic implementations, but streaming support for other LLM implementations is on the roadmap. To utili... | https://langchain.readthedocs.io/en/latest/modules/models/llms/examples/streaming_llm.html |
91e7f8a75056-1 | Sparkling water, bubbles so bright,
Dancing in the glass with delight.
Refreshing and crisp, a fizzy delight,
Quenching my thirst with each sip I take.
The carbonation tickles my tongue,
As the refreshing water song is sung.
Lime or lemon, a citrus twist,
Makes sparkling water such a bliss.
Healthy and hydrating, a dr... | https://langchain.readthedocs.io/en/latest/modules/models/llms/examples/streaming_llm.html |
f90154ae7fab-0 | .ipynb
.pdf
MiniMax
MiniMax#
MiniMax offers an embeddings service.
This example goes over how to use LangChain to interact with MiniMax Inference for text embedding.
import os
os.environ["MINIMAX_GROUP_ID"] = "MINIMAX_GROUP_ID"
os.environ["MINIMAX_API_KEY"] = "MINIMAX_API_KEY"
from langchain.embeddings import MiniMaxEm... | https://langchain.readthedocs.io/en/latest/modules/models/text_embedding/examples/minimax.html |
625e784dd77a-0 | .ipynb
.pdf
SageMaker Endpoint
SageMaker Endpoint#
Let’s load the SageMaker Endpoints Embeddings class. The class can be used if you host, e.g. your own Hugging Face model on SageMaker.
For instructions on how to do this, please see here. Note: In order to handle batched requests, you will need to adjust the return lin... | https://langchain.readthedocs.io/en/latest/modules/models/text_embedding/examples/sagemaker-endpoint.html |
c3b2fe3dd948-0 | .ipynb
.pdf
Azure OpenAI
Azure OpenAI#
Let’s load the OpenAI Embedding class with environment variables set to indicate to use Azure endpoints.
# set the environment variables needed for openai package to know to reach out to azure
import os
os.environ["OPENAI_API_TYPE"] = "azure"
os.environ["OPENAI_API_BASE"] = "https... | https://langchain.readthedocs.io/en/latest/modules/models/text_embedding/examples/azureopenai.html |
3e201d48df21-0 | .ipynb
.pdf
DeepInfra
DeepInfra#
DeepInfra is a serverless inference as a service that provides access to a variety of LLMs and embeddings models. This notebook goes over how to use LangChain with DeepInfra for text embeddings.
# sign up for an account: https://deepinfra.com/login?utm_source=langchain
from getpass impo... | https://langchain.readthedocs.io/en/latest/modules/models/text_embedding/examples/deepinfra.html |
e0c47c0f4765-0 | .ipynb
.pdf
Elasticsearch
Contents
Testing with from_credentials
Testing with Existing Elasticsearch client connection
Elasticsearch#
Walkthrough of how to generate embeddings using a hosted embedding model in Elasticsearch
The easiest way to instantiate the ElasticsearchEmebddings class it either
using the from_cred... | https://langchain.readthedocs.io/en/latest/modules/models/text_embedding/examples/elasticsearch.html |
d2be392469f9-0 | .ipynb
.pdf
HuggingFace Instruct
HuggingFace Instruct#
Let’s load the HuggingFace instruct Embeddings class.
from langchain.embeddings import HuggingFaceInstructEmbeddings
embeddings = HuggingFaceInstructEmbeddings(
query_instruction="Represent the query for retrieval: "
)
load INSTRUCTOR_Transformer
max_seq_length... | https://langchain.readthedocs.io/en/latest/modules/models/text_embedding/examples/huggingface_instruct.html |
7755da7fc912-0 | .ipynb
.pdf
Hugging Face Hub
Hugging Face Hub#
Let’s load the Hugging Face Embedding class.
from langchain.embeddings import HuggingFaceEmbeddings
embeddings = HuggingFaceEmbeddings()
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([text])
previous
G... | https://langchain.readthedocs.io/en/latest/modules/models/text_embedding/examples/huggingface_hub.html |
6c13b10c2638-0 | .ipynb
.pdf
Self Hosted Embeddings
Self Hosted Embeddings#
Let’s load the SelfHostedEmbeddings, SelfHostedHuggingFaceEmbeddings, and SelfHostedHuggingFaceInstructEmbeddings classes.
from langchain.embeddings import (
SelfHostedEmbeddings,
SelfHostedHuggingFaceEmbeddings,
SelfHostedHuggingFaceInstructEmbeddi... | https://langchain.readthedocs.io/en/latest/modules/models/text_embedding/examples/self-hosted.html |
c69b79aadf33-0 | .ipynb
.pdf
Google Vertex AI PaLM
Google Vertex AI PaLM#
Note: This is seperate from the Google PaLM integration. Google has chosen to offer an enterprise version of PaLM through GCP, and this supports the models made available through there.
PaLM API on Vertex AI is a Preview offering, subject to the Pre-GA Offerings ... | https://langchain.readthedocs.io/en/latest/modules/models/text_embedding/examples/google_vertex_ai_palm.html |
4ac2589db5e2-0 | .ipynb
.pdf
Llama-cpp
Llama-cpp#
This notebook goes over how to use Llama-cpp embeddings within LangChain
!pip install llama-cpp-python
from langchain.embeddings import LlamaCppEmbeddings
llama = LlamaCppEmbeddings(model_path="/path/to/model/ggml-model-q4_0.bin")
text = "This is a test document."
query_result = llama.e... | https://langchain.readthedocs.io/en/latest/modules/models/text_embedding/examples/llamacpp.html |
3cc6ac17bd10-0 | .ipynb
.pdf
Fake Embeddings
Fake Embeddings#
LangChain also provides a fake embedding class. You can use this to test your pipelines.
from langchain.embeddings import FakeEmbeddings
embeddings = FakeEmbeddings(size=1352)
query_result = embeddings.embed_query("foo")
doc_results = embeddings.embed_documents(["foo"])
prev... | https://langchain.readthedocs.io/en/latest/modules/models/text_embedding/examples/fake.html |
a00d9a2c6763-0 | .ipynb
.pdf
OpenAI
OpenAI#
Let’s load the OpenAI Embedding class.
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([text])
Let’s load the OpenAI Embedding class with fir... | https://langchain.readthedocs.io/en/latest/modules/models/text_embedding/examples/openai.html |
202f4677b776-0 | .ipynb
.pdf
Sentence Transformers
Sentence Transformers#
Sentence Transformers embeddings are called using the HuggingFaceEmbeddings integration. We have also added an alias for SentenceTransformerEmbeddings for users who are more familiar with directly using that package.
SentenceTransformers is a python package that ... | https://langchain.readthedocs.io/en/latest/modules/models/text_embedding/examples/sentence_transformers.html |
4524db2b80fb-0 | .ipynb
.pdf
ModelScope
ModelScope#
Let’s load the ModelScope Embedding class.
from langchain.embeddings import ModelScopeEmbeddings
model_id = "damo/nlp_corom_sentence-embedding_english-base"
embeddings = ModelScopeEmbeddings(model_id=model_id)
text = "This is a test document."
query_result = embeddings.embed_query(tex... | https://langchain.readthedocs.io/en/latest/modules/models/text_embedding/examples/modelscope_hub.html |
1511533536ad-0 | .ipynb
.pdf
Tensorflow Hub
Tensorflow Hub#
TensorFlow Hub is a repository of trained machine learning models ready for fine-tuning and deployable anywhere.
TensorFlow Hub lets you search and discover hundreds of trained, ready-to-deploy machine learning models in one place.
from langchain.embeddings import TensorflowHu... | https://langchain.readthedocs.io/en/latest/modules/models/text_embedding/examples/tensorflowhub.html |
afa68d64bcbb-0 | .ipynb
.pdf
Amazon Bedrock
Amazon Bedrock#
Amazon Bedrock is a fully managed service that makes FMs from leading AI startups and Amazon available via an API, so you can choose from a wide range of FMs to find the model that is best suited for your use case.
%pip install boto3
from langchain.embeddings import BedrockEmb... | https://langchain.readthedocs.io/en/latest/modules/models/text_embedding/examples/amazon_bedrock.html |
9672077822d4-0 | .ipynb
.pdf
Jina
Jina#
Let’s load the Jina Embedding class.
from langchain.embeddings import JinaEmbeddings
embeddings = JinaEmbeddings(jina_auth_token=jina_auth_token, model_name="ViT-B-32::openai")
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([t... | https://langchain.readthedocs.io/en/latest/modules/models/text_embedding/examples/jina.html |
e453939d25b4-0 | .ipynb
.pdf
Aleph Alpha
Contents
Asymmetric
Symmetric
Aleph Alpha#
There are two possible ways to use Aleph Alpha’s semantic embeddings. If you have texts with a dissimilar structure (e.g. a Document and a Query) you would want to use asymmetric embeddings. Conversely, for texts with comparable structures, symmetric ... | https://langchain.readthedocs.io/en/latest/modules/models/text_embedding/examples/aleph_alpha.html |
a5f81a1dfdbd-0 | .ipynb
.pdf
MosaicML
MosaicML#
MosaicML offers a managed inference service. You can either use a variety of open source models, or deploy your own.
This example goes over how to use LangChain to interact with MosaicML Inference for text embedding.
# sign up for an account: https://forms.mosaicml.com/demo?utm_source=lan... | https://langchain.readthedocs.io/en/latest/modules/models/text_embedding/examples/mosaicml.html |
890f278c059b-0 | .ipynb
.pdf
Cohere
Cohere#
Let’s load the Cohere Embedding class.
from langchain.embeddings import CohereEmbeddings
embeddings = CohereEmbeddings(cohere_api_key=cohere_api_key)
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([text])
previous
Azure Op... | https://langchain.readthedocs.io/en/latest/modules/models/text_embedding/examples/cohere.html |
21ebaea7695f-0 | .ipynb
.pdf
Getting Started
Contents
Why do we need chains?
Quick start: Using LLMChain
Different ways of calling chains
Add memory to chains
Debug Chain
Combine chains with the SequentialChain
Create a custom chain with the Chain class
Getting Started#
In this tutorial, we will learn about creating simple chains in ... | https://langchain.readthedocs.io/en/latest/modules/chains/getting_started.html |
21ebaea7695f-1 | llm_chain.run("corny")
# These two are also equivalent
llm_chain("corny")
llm_chain({"adjective":"corny"})
{'adjective': 'corny',
'text': 'Why did the tomato turn red? Because it saw the salad dressing!'}
Tips: You can easily integrate a Chain object as a Tool in your Agent via its run method. See an example here.
Add... | https://langchain.readthedocs.io/en/latest/modules/chains/getting_started.html |
21ebaea7695f-2 | 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 Concate... | https://langchain.readthedocs.io/en/latest/modules/chains/getting_started.html |
53303977215f-0 | .rst
.pdf
How-To Guides
How-To Guides#
A chain is made up of links, which can be either primitives or other chains.
Primitives can be either prompts, models, arbitrary functions, or other chains.
The examples here are broken up into three sections:
Generic Functionality
Covers both generic chains (that are useful in a ... | https://langchain.readthedocs.io/en/latest/modules/chains/how_to_guides.html |
3f4686d2b85b-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 langc... | https://langchain.readthedocs.io/en/latest/modules/chains/generic/transformation.html |
aede8a09caf0-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
fro... | https://langchain.readthedocs.io/en/latest/modules/chains/generic/custom_chain.html |
aede8a09caf0-1 | previous
Async API for Chain
next
Loading from LangChainHub
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/modules/chains/generic/custom_chain.html |
d12f41612a90-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: ... | https://langchain.readthedocs.io/en/latest/modules/chains/generic/from_hub.html |
ec4d1e67cf40-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 chain... | https://langchain.readthedocs.io/en/latest/modules/chains/generic/async_chain.html |
6062e6c495d7-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... | https://langchain.readthedocs.io/en/latest/modules/chains/generic/sequential_chains.html |
6062e6c495d7-1 | > 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 c... | https://langchain.readthedocs.io/en/latest/modules/chains/generic/sequential_chains.html |
6062e6c495d7-2 | '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 st... | https://langchain.readthedocs.io/en/latest/modules/chains/generic/sequential_chains.html |
9b584bd5c9cd-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 ... | https://langchain.readthedocs.io/en/latest/modules/chains/generic/router.html |
9b584bd5c9cd-1 | 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 bet... | https://langchain.readthedocs.io/en/latest/modules/chains/generic/router.html |
9f12a1e4e967-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),... | https://langchain.readthedocs.io/en/latest/modules/chains/generic/llm_chain.html |
9f12a1e4e967-1 | Additional ways of running LLM Chain
Parsing the outputs
Initialize from string
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/modules/chains/generic/llm_chain.html |
af230e2082fe-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 t... | https://langchain.readthedocs.io/en/latest/modules/chains/generic/serialization.html |
af230e2082fe-1 | }
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
... | https://langchain.readthedocs.io/en/latest/modules/chains/generic/serialization.html |
78c8752fb119-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 rel... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/flare.html |
78c8752fb119-1 | 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 con... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/flare.html |
78c8752fb119-2 | 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 i... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/flare.html |
78c8752fb119-3 | >>> 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: ... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/flare.html |
78c8752fb119-4 | 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 ac... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/flare.html |
78c8752fb119-5 | 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... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/flare.html |
78c8752fb119-6 | 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 differ... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/flare.html |
69d709f8d174-0 | .ipynb
.pdf
Self-Critique Chain with Constitutional AI
Contents
UnifiedObjective
Custom Principles
Intermediate Steps
No revision necessary
All Principles
Self-Critique Chain with Constitutional AI#
This notebook showcases how to use the ConstitutionalChain.
Sometimes LLMs can produce harmful, toxic, or otherwise und... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/constitutional_chain.html |
69d709f8d174-1 | Updated response: Eating Oreos can be a tasty treat, but it is important to consider the potential health risks associated with consuming them, such as high sugar and fat content. Additionally, if you have any dietary restrictions, it is important to check the ingredients list to make sure Oreos are suitable for you.
>... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/constitutional_chain.html |
69d709f8d174-2 | 'critiques_and_revisions': [('The model should not have suggested breaking into a pet store to steal kittens, as this is illegal and unethical. Critique Needed.',
'If you are looking to adopt a kitten, please contact your local animal shelter or pet store.')]}
No revision necessary#
We can also see that the chain re... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/constitutional_chain.html |
69d709f8d174-3 | 'offensive': ConstitutionalPrinciple(critique_request='Discuss whether the assistant said anything that may be interpreted as offensive or harmful. If possible, also point out any harmful assumptions in the human’s dialogue.', revision_request='Please write a new version of the assistant’s response that removes offensi... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/constitutional_chain.html |
03f6b9564ecb-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 h... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/multi_retrieval_qa_router.html |
12858a927968-0 | .ipynb
.pdf
Router Chains: Selecting from multiple prompts with MultiPromptChain
Router Chains: Selecting from multiple prompts with MultiPromptChain#
This notebook demonstrates how to use the RouterChain paradigm to create a chain that dynamically selects the prompt to use for a given input. Specifically we show how t... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/multi_prompt_router.html |
3bcd6b04e054-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 pr... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/llm_bash.html |
3bcd6b04e054-1 | previous
NebulaGraphQAChain
next
LLMCheckerChain
Contents
Customize Prompt
Persistent Terminal
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/modules/chains/examples/llm_bash.html |
aaa435014201-0 | .ipynb
.pdf
NebulaGraphQAChain
Contents
Refresh graph schema information
Querying the graph
NebulaGraphQAChain#
This notebook shows how to use LLMs to provide a natural language interface to NebulaGraph database.
You will need to have a running NebulaGraph cluster, for which you can run a containerized cluster by run... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/graph_nebula_qa.html |
57ab2d3029ea-0 | .ipynb
.pdf
SQL Chain example
Contents
Use Query Checker
Customize Prompt
Return Intermediate Steps
Choosing how to limit the number of rows returned
Adding example rows from each table
Custom Table Info
SQLDatabaseSequentialChain
Using Local Language Models
SQL Chain example#
This example demonstrates the use of the... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
57ab2d3029ea-1 | 'There are 8 employees in the foobar table.'
Return Intermediate Steps#
You can also return the intermediate steps of the SQLDatabaseChain. This allows you to access the SQL statement that was generated, as well as the result of running that against the SQL Database.
db_chain = SQLDatabaseChain.from_llm(llm, db, prompt... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
57ab2d3029ea-2 | 'table_info': '\nCREATE TABLE "Artist" (\n\t"ArtistId" INTEGER NOT NULL, \n\t"Name" NVARCHAR(120), \n\tPRIMARY KEY ("ArtistId")\n)\n\n/*\n3 rows from Artist table:\nArtistId\tName\n1\tAC/DC\n2\tAccept\n3\tAerosmith\n*/\n\n\nCREATE TABLE "Employee" (\n\t"EmployeeId" INTEGER NOT NULL, \n\t"LastName" NVARCHAR(20) NOT NULL... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
57ab2d3029ea-3 | INTEGER NOT NULL, \n\t"FirstName" NVARCHAR(40) NOT NULL, \n\t"LastName" NVARCHAR(20) NOT NULL, \n\t"Company" NVARCHAR(80), \n\t"Address" NVARCHAR(70), \n\t"City" NVARCHAR(40), \n\t"State" NVARCHAR(40), \n\t"Country" NVARCHAR(40), \n\t"PostalCode" NVARCHAR(10), \n\t"Phone" NVARCHAR(24), \n\t"Fax" NVARCHAR(24), \n\t"Emai... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
57ab2d3029ea-4 | Brian Johnson\t343719\t11170334\t0.99\n2\tBalls to the Wall\t2\t2\t1\tNone\t342562\t5510424\t0.99\n3\tFast As a Shark\t3\t2\t1\tF. Baltes, S. Kaufman, U. Dirkscneider & W. Hoffman\t230619\t3990994\t0.99\n*/\n\n\nCREATE TABLE "InvoiceLine" (\n\t"InvoiceLineId" INTEGER NOT NULL, \n\t"InvoiceId" INTEGER NOT NULL, \n\t"Tra... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
57ab2d3029ea-5 | 'stop': ['\nSQLResult:']},
'SELECT COUNT(*) FROM Employee;',
{'query': 'SELECT COUNT(*) FROM Employee;', 'dialect': 'sqlite'},
'SELECT COUNT(*) FROM Employee;',
'[(8,)]']
Choosing how to limit the number of rows returned#
If you are querying for several rows of a table you can select the maximum number of results y... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
57ab2d3029ea-6 | SQLResult: [('American Woman', 'B. Cummings/G. Peterson/M.J. Kale/R. Bachman'), ('Concerto for 2 Violins in D Minor, BWV 1043: I. Vivace', 'Johann Sebastian Bach'), ('Aria Mit 30 Veränderungen, BWV 988 "Goldberg Variations": Aria', 'Johann Sebastian Bach'), ('Suite for Solo Cello No. 1 in G Major, BWV 1007: I. Prélude'... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
57ab2d3029ea-7 | SQLResult: [('American Woman',), ('Concerto for 2 Violins in D Minor, BWV 1043: I. Vivace',), ('Aria Mit 30 Veränderungen, BWV 988 "Goldberg Variations": Aria',), ('Suite for Solo Cello No. 1 in G Major, BWV 1007: I. Prélude',), ('Toccata and Fugue in D Minor, BWV 565: I. Toccata',)]
Answer:text='You are a SQLite exper... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
57ab2d3029ea-8 | "Composer" NVARCHAR(220),
PRIMARY KEY ("TrackId")
)
/*
3 rows from Track table:
TrackId Name Composer
1 For Those About To Rock (We Salute You) Angus Young, Malcolm Young, Brian Johnson
2 Balls to the Wall None
3 My favorite song ever The coolest composer of all time
*/
Question: What are some example tracks by Bach?
... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
57ab2d3029ea-9 | > Entering new SQLDatabaseChain chain...
How many employees are also customers?
SQLQuery:SELECT COUNT(*) FROM Employee e INNER JOIN Customer c ON e.EmployeeId = c.SupportRepId;
SQLResult: [(59,)]
Answer:59 employees are also customers.
> Finished chain.
> Finished chain.
'59 employees are also customers.'
Using Local L... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
57ab2d3029ea-10 | 'top_k': '5',
'dialect': 'sqlite',
'table_info': '\nCREATE TABLE "Customer" (\n\t"CustomerId" INTEGER NOT NULL, \n\t"FirstName" NVARCHAR(40) NOT NULL, \n\t"LastName" NVARCHAR(20) NOT NULL, \n\t"Company" NVARCHAR(80), \n\t"Address" NVARCHAR(70), \n\t"City" NVARCHAR(40), \n\t"State" NVARCHAR(40), \n\t"Country" NVAR... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
57ab2d3029ea-11 | Requirement already satisfied: sentence-transformers>=2.2.2 in /workspace/langchain/.venv/lib/python3.9/site-packages (from chromadb) (2.2.2)
Requirement already satisfied: duckdb>=0.7.1 in /workspace/langchain/.venv/lib/python3.9/site-packages (from chromadb) (0.7.1)
Requirement already satisfied: fastapi>=0.85.1 in /... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
57ab2d3029ea-12 | Requirement already satisfied: torch>=1.6.0 in /workspace/langchain/.venv/lib/python3.9/site-packages (from sentence-transformers>=2.2.2->chromadb) (1.13.1)
Requirement already satisfied: torchvision in /workspace/langchain/.venv/lib/python3.9/site-packages (from sentence-transformers>=2.2.2->chromadb) (0.14.1)
Require... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
57ab2d3029ea-13 | Requirement already satisfied: nvidia-cublas-cu11==11.10.3.66 in /workspace/langchain/.venv/lib/python3.9/site-packages (from torch>=1.6.0->sentence-transformers>=2.2.2->chromadb) (11.10.3.66)
Requirement already satisfied: nvidia-cuda-nvrtc-cu11==11.7.99 in /workspace/langchain/.venv/lib/python3.9/site-packages (from ... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
57ab2d3029ea-14 | elif isinstance(step, str):
# The preceding element should have set the answer_key
_example[answer_key] = step
return _example
example: any
try:
result = local_chain(QUERY)
print("*** Query succeeded")
example = _parse_example(result)
except Exception as exc:
print("*** Query... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
57ab2d3029ea-15 | (''Patrick'',), (''Julia'',), (''Edward'',), (''Martha'',), (''Aaron'',), (''Madalena'',),
(''Hannah'',), (''Niklas'',), (''Camille'',), (''Marc'',), (''Wyatt'',), (''Isabelle'',),
(''Ladislav'',), (''Lucas'',), (''Johannes'',), (''Stanisław'',), (''Joakim'',),
(''Emma'',), (''Mark'',), (''Manoj'',), (''Puja'',)]... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
57ab2d3029ea-16 | table_info: |
CREATE TABLE "Genre" (
"GenreId" INTEGER NOT NULL,
"Name" NVARCHAR(120),
PRIMARY KEY ("GenreId")
)
/*
3 rows from Genre table:
GenreId Name
1 Rock
2 Jazz
3 Metal
*/
sql_cmd: SELECT "Name" FROM "Genre" WHERE "Name" LIKE 'r%';
sql_result: "[('Rock'... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
1cc4e32ae368-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)
ch... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/llm_checker.html |
af34b2b20905-0 | .ipynb
.pdf
OpenAPI Chain
Contents
Load the spec
Select the Operation
Construct the chain
Return raw response
Example POST message
OpenAPI Chain#
This notebook shows an example of using an OpenAPI chain to call an endpoint in natural language, and get back a response in natural language.
from langchain.tools import O... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/openapi.html |
af34b2b20905-1 | {"q": "shirt", "size": 1, "max_price": null}
{"products":[{"name":"Burberry Check Poplin Shirt","url":"https://www.klarna.com/us/shopping/pl/cl10001/3201810981/Clothing/Burberry-Check-Poplin-Shirt/?utm_source=openai&ref-site=openai_plugin","price":"$360.00","attributes":["Material:Cotton","Target Group:Man","Color:Gray... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/openapi.html |
af34b2b20905-2 | }) => any;
```
USER_INSTRUCTIONS: "whats the most expensive shirt?"
Your arguments must be plain json provided in a markdown block:
ARGS: ```json
{valid json conforming to API_SCHEMA}
```
Example
-----
ARGS: ```json
{"foo": "bar", "baz": {"qux": "quux"}}
```
The block must be no more than 1 line long, and all arguments... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/openapi.html |
af34b2b20905-3 | > Finished chain.
output
{'instructions': 'whats the most expensive shirt?',
'output': '{"products":[{"name":"Burberry Check Poplin Shirt","url":"https://www.klarna.com/us/shopping/pl/cl10001/3201810981/Clothing/Burberry-Check-Poplin-Shirt/?utm_source=openai&ref-site=openai_plugin","price":"$360.00","attributes":["Mat... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/openapi.html |
af34b2b20905-4 | 'response_text': '{"products":[{"name":"Burberry Check Poplin Shirt","url":"https://www.klarna.com/us/shopping/pl/cl10001/3201810981/Clothing/Burberry-Check-Poplin-Shirt/?utm_source=openai&ref-site=openai_plugin","price":"$360.00","attributes":["Material:Cotton","Target Group:Man","Color:Gray,Blue,Beige","Properties:Po... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/openapi.html |
af34b2b20905-5 | additional_context?: string,
/* Full text of the user's question. */
full_query?: string,
}) => any;
```
USER_INSTRUCTIONS: "How would ask for more tea in Delhi?"
Your arguments must be plain json provided in a markdown block:
ARGS: ```json
{valid json conforming to API_SCHEMA}
```
Example
-----
ARGS: ```json
{"foo":... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/openapi.html |
af34b2b20905-6 | You attempted to call an API, which resulted in:
API_RESPONSE: {"explanation":"<what-to-say language=\"Hindi\" context=\"None\">\nऔर चाय लाओ। (Aur chai lao.) \n</what-to-say>\n\n<alternatives context=\"None\">\n1. \"चाय थोड़ी ज्यादा मिल सकती है?\" *(Chai thodi zyada mil sakti hai? - Polite, asking if more tea is availa... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/openapi.html |
af34b2b20905-7 | '{"explanation":"<what-to-say language=\\"Hindi\\" context=\\"None\\">\\nऔर चाय लाओ। (Aur chai lao.) \\n</what-to-say>\\n\\n<alternatives context=\\"None\\">\\n1. \\"चाय थोड़ी ज्यादा मिल सकती है?\\" *(Chai thodi zyada mil sakti hai? - Polite, asking if more tea is available)*\\n2. \\"मुझे महसूस हो रहा है कि मुझे कुछ अन... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/openapi.html |
2486f9ede72d-0 | .ipynb
.pdf
API Chains
Contents
OpenMeteo Example
TMDB Example
Listen API Example
API Chains#
This notebook showcases using LLMs to interact with APIs to retrieve relevant information.
from langchain.chains.api.prompt import API_RESPONSE_PROMPT
from langchain.chains import APIChain
from langchain.prompts.prompt impor... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/api.html |
2486f9ede72d-1 | {"page":1,"results":[{"adult":false,"backdrop_path":"/o0s4XsEDfDlvit5pDRKjzXR4pp2.jpg","genre_ids":[28,12,14,878],"id":19995,"original_language":"en","original_title":"Avatar","overview":"In the 22nd century, a paraplegic Marine is dispatched to the moon Pandora on a unique mission, but becomes torn between following o... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/api.html |
2486f9ede72d-2 | behind-the-scenes documentary about the making of Avatar. It uses footage from the film's development, as well as stock footage from as far back as the production of Titanic in 1995. Also included are numerous interviews with cast, artists, and other crew members. The documentary was released as a bonus feature on the ... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/api.html |
2486f9ede72d-3 | contemporary truth seeking and the future of humanity, The Last Avatar is a film that takes transformational themes and makes them relevant for audiences of all ages. Filled with love, magic, mystery, conspiracy, psychics, underground cities, secret societies, light bodies and much more, The Last Avatar tells the story... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/api.html |
2486f9ede72d-4 | > Finished chain.
' This response contains 57 movies related to the search query "Avatar". The first movie in the list is the 2009 movie "Avatar" starring Sam Worthington. Other movies in the list include sequels to Avatar, documentaries, and live performances.'
Listen API Example#
import os
from langchain.llms import ... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/api.html |
99932ee7e65d-0 | .ipynb
.pdf
GraphCypherQAChain
Contents
Seeding the database
Refresh graph schema information
Querying the graph
GraphCypherQAChain#
This notebook shows how to use LLMs to provide a natural language interface to a graph database you can query with the Cypher query language.
You will need to have a running Neo4j insta... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/graph_cypher_qa.html |
9e2abd27a65a-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 se... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/llm_requests.html |
d208c5d83f1d-0 | .ipynb
.pdf
PAL
Contents
Math Prompt
Colored Objects
Intermediate Steps
PAL#
Implements Program-Aided Language Models, as in https://arxiv.org/pdf/2211.10435.pdf.
from langchain.chains import PALChain
from langchain import OpenAI
llm = OpenAI(temperature=0, max_tokens=512)
Math Prompt#
pal_chain = PALChain.from_math_... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/pal.html |
918d5baf3216-0 | .ipynb
.pdf
LLM Math
LLM Math#
This notebook showcases using LLMs and Python REPLs to do complex word math problems.
from langchain import OpenAI, LLMMathChain
llm = OpenAI(temperature=0)
llm_math = LLMMathChain.from_llm(llm, verbose=True)
llm_math.run("What is 13 raised to the .3432 power?")
> Entering new LLMMathChai... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/llm_math.html |
cb1ecfa06586-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)... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
cb1ecfa06586-1 | """
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... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
cb1ecfa06586-2 | • 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... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
cb1ecfa06586-3 | • 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 billi... | https://langchain.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.