id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
8c37cb60ff4b-86
(langchain.llms.ForefrontAI attribute) (langchain.llms.GooglePalm attribute) (langchain.llms.GooseAI attribute) (langchain.llms.LlamaCpp attribute) (langchain.llms.NLPCloud attribute) (langchain.llms.OpenAI attribute) (langchain.llms.OpenLM attribute) (langchain.llms.Petals attribute) (langchain.llms.PredictionGuard at...
https://python.langchain.com/en/latest/genindex.html
8c37cb60ff4b-87
tokenizer (langchain.llms.Petals attribute) tokens (langchain.llms.AlephAlpha attribute) tokens_path (langchain.llms.RWKV attribute) TokenTextSplitter (class in langchain.text_splitter) ToMarkdownLoader (class in langchain.document_loaders) TomlLoader (class in langchain.document_loaders) tool() (in module langchain.ag...
https://python.langchain.com/en/latest/genindex.html
8c37cb60ff4b-88
(langchain.utilities.GooglePlacesAPIWrapper attribute) (langchain.utilities.WikipediaAPIWrapper attribute) top_n (langchain.retrievers.document_compressors.CohereRerank attribute) top_p (langchain.chat_models.ChatGooglePalm attribute) (langchain.llms.AlephAlpha attribute) (langchain.llms.Anthropic attribute) (langchain...
https://python.langchain.com/en/latest/genindex.html
8c37cb60ff4b-89
type (langchain.utilities.GoogleSerperAPIWrapper attribute) Typesense (class in langchain.vectorstores) U unsecure (langchain.utilities.searx_search.SearxSearchWrapper attribute) (langchain.utilities.SearxSearchWrapper attribute) UnstructuredAPIFileIOLoader (class in langchain.document_loaders) UnstructuredAPIFileLoade...
https://python.langchain.com/en/latest/genindex.html
8c37cb60ff4b-90
(langchain.llms.Cohere class method) (langchain.llms.CTransformers class method) (langchain.llms.Databricks class method) (langchain.llms.DeepInfra class method) (langchain.llms.FakeListLLM class method) (langchain.llms.ForefrontAI class method) (langchain.llms.GooglePalm class method) (langchain.llms.GooseAI class met...
https://python.langchain.com/en/latest/genindex.html
8c37cb60ff4b-91
(langchain.llms.VertexAI class method) (langchain.llms.Writer class method) upsert_messages() (langchain.memory.CosmosDBChatMessageHistory method) url (langchain.document_loaders.MathpixPDFLoader property) (langchain.llms.Beam attribute) (langchain.retrievers.ChatGPTPluginRetriever attribute) (langchain.retrievers.Remo...
https://python.langchain.com/en/latest/genindex.html
8c37cb60ff4b-92
(langchain.chains.VectorDBQAWithSourcesChain attribute) (langchain.prompts.example_selector.SemanticSimilarityExampleSelector attribute) (langchain.retrievers.SelfQueryRetriever attribute) (langchain.retrievers.TimeWeightedVectorStoreRetriever attribute) vectorstore_info (langchain.agents.agent_toolkits.VectorStoreTool...
https://python.langchain.com/en/latest/genindex.html
8c37cb60ff4b-93
(langchain.llms.OpenAIChat attribute) (langchain.llms.OpenLM attribute) (langchain.llms.Petals attribute) (langchain.llms.PipelineAI attribute) (langchain.llms.PredictionGuard attribute) (langchain.llms.Replicate attribute) (langchain.llms.RWKV attribute) (langchain.llms.SagemakerEndpoint attribute) (langchain.llms.Sel...
https://python.langchain.com/en/latest/genindex.html
8c37cb60ff4b-94
Wikipedia (class in langchain.docstore) WikipediaLoader (class in langchain.document_loaders) wolfram_alpha_appid (langchain.utilities.WolframAlphaAPIWrapper attribute) writer_api_key (langchain.llms.Writer attribute) writer_org_id (langchain.llms.Writer attribute) Y YoutubeLoader (class in langchain.document_loaders) ...
https://python.langchain.com/en/latest/genindex.html
279d856eed4b-0
.md .pdf Tutorials Contents Tutorials# This is a collection of LangChain tutorials mostly on YouTube. ⛓ icon marks a new video [last update 2023-05-15] # LangChain AI Handbook By James Briggs and Francisco Ingham # LangChain Tutorials by Edrick: ⛓ LangChain, Chroma DB, OpenAI Beginner Guide | ChatGPT with your PDF La...
https://python.langchain.com/en/latest/getting_started/tutorials.html
279d856eed4b-1
Question A 300 Page Book (w/ OpenAI + Pinecone) Workaround OpenAI's Token Limit With Chain Types Build Your Own OpenAI + LangChain Web App in 23 Minutes Working With The New ChatGPT API OpenAI + LangChain Wrote Me 100 Custom Sales Emails Structured Output From OpenAI (Clean Dirty Data) Connect OpenAI To +5,000 Tools (L...
https://python.langchain.com/en/latest/getting_started/tutorials.html
279d856eed4b-2
⛓ Using LangChain with DuckDuckGO Wikipedia & PythonREPL Tools ⛓ Building Custom Tools and Agents with LangChain (gpt-3.5-turbo) ⛓ LangChain Retrieval QA Over Multiple Files with ChromaDB ⛓ LangChain Retrieval QA with Instructor Embeddings & ChromaDB for PDFs ⛓ LangChain + Retrieval Local LLMs for Retrieval QA - No Ope...
https://python.langchain.com/en/latest/getting_started/tutorials.html
279d856eed4b-3
Analyze Custom CSV Data with GPT-4 using Langchain ⛓ Build ChatGPT Chatbots with LangChain Memory: Understanding and Implementing Memory in Conversations ⛓ icon marks a new video [last update 2023-05-15] previous Concepts next Models Contents By Harrison Chase © Copyright 2023, Harrison Chase. L...
https://python.langchain.com/en/latest/getting_started/tutorials.html
d2ac754d8ae4-0
.md .pdf Quickstart Guide Contents Installation Environment Setup Building a Language Model Application: LLMs LLMs: Get predictions from a language model Prompt Templates: Manage prompts for LLMs Chains: Combine LLMs and prompts in multi-step workflows Agents: Dynamically Call Chains Based on User Input Memory: Add S...
https://python.langchain.com/en/latest/getting_started/getting_started.html
d2ac754d8ae4-1
LangChain provides many modules that can be used to build language model applications. Modules can be combined to create more complex applications, or be used individually for simple applications. LLMs: Get predictions from a language model# The most basic building block of LangChain is calling an LLM on some input. Le...
https://python.langchain.com/en/latest/getting_started/getting_started.html
d2ac754d8ae4-2
This is easy to do with LangChain! First lets define the prompt template: from langchain.prompts import PromptTemplate prompt = PromptTemplate( input_variables=["product"], template="What is a good name for a company that makes {product}?", ) Let’s now see how this works! We can call the .format method to forma...
https://python.langchain.com/en/latest/getting_started/getting_started.html
d2ac754d8ae4-3
Now we can run that chain only specifying the product! chain.run("colorful socks") # -> '\n\nSocktastic!' There we go! There’s the first chain - an LLM Chain. This is one of the simpler types of chains, but understanding how it works will set you up well for working with more complex chains. For more details, check out...
https://python.langchain.com/en/latest/getting_started/getting_started.html
d2ac754d8ae4-4
pip install google-search-results And set the appropriate environment variables. import os os.environ["SERPAPI_API_KEY"] = "..." Now we can get started! from langchain.agents import load_tools from langchain.agents import initialize_agent from langchain.agents import AgentType from langchain.llms import OpenAI # First,...
https://python.langchain.com/en/latest/getting_started/getting_started.html
d2ac754d8ae4-5
Thought: I now know the final answer Final Answer: The high temperature in SF yesterday in Fahrenheit raised to the .023 power is 1.0974509573251117. > Finished chain. Memory: Add State to Chains and Agents# So far, all the chains and agents we’ve gone through have been stateless. But often, you may want a chain or age...
https://python.langchain.com/en/latest/getting_started/getting_started.html
d2ac754d8ae4-6
Current conversation: Human: Hi there! AI: > Finished chain. ' Hello! How are you today?' output = conversation.predict(input="I'm doing well! Just having a conversation with an AI.") print(output) > Entering new chain... Prompt after formatting: The following is a friendly conversation between a human and an AI. The A...
https://python.langchain.com/en/latest/getting_started/getting_started.html
d2ac754d8ae4-7
AIMessage, HumanMessage, SystemMessage ) chat = ChatOpenAI(temperature=0) You can get completions by passing in a single message. chat([HumanMessage(content="Translate this sentence from English to French. I love programming.")]) # -> AIMessage(content="J'aime programmer.", additional_kwargs={}) You can also pa...
https://python.langchain.com/en/latest/getting_started/getting_started.html
d2ac754d8ae4-8
You can recover things like token usage from this LLMResult: result.llm_output['token_usage'] # -> {'prompt_tokens': 57, 'completion_tokens': 20, 'total_tokens': 77} Chat Prompt Templates# Similar to LLMs, you can make use of templating by using a MessagePromptTemplate. You can build a ChatPromptTemplate from one or mo...
https://python.langchain.com/en/latest/getting_started/getting_started.html
d2ac754d8ae4-9
from langchain import LLMChain from langchain.prompts.chat import ( ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate, ) chat = ChatOpenAI(temperature=0) template = "You are a helpful assistant that translates {input_language} to {output_language}." system_message_prompt = SystemMe...
https://python.langchain.com/en/latest/getting_started/getting_started.html
d2ac754d8ae4-10
agent = initialize_agent(tools, chat, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True) # Now let's test it out! agent.run("Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?") > Entering new AgentExecutor chain... Thought: I need to use a search engine to find Olivia Wilde...
https://python.langchain.com/en/latest/getting_started/getting_started.html
d2ac754d8ae4-11
'2.169459462491557' Memory: Add State to Chains and Agents# You can use Memory with chains and agents initialized with chat models. The main difference between this and Memory for LLMs is that rather than trying to condense all previous messages into a string, we can keep them as their own unique memory object. from la...
https://python.langchain.com/en/latest/getting_started/getting_started.html
d2ac754d8ae4-12
conversation.predict(input="Tell me about yourself.") # -> "Sure! I am an AI language model created by OpenAI. I was trained on a large dataset of text from the internet, which allows me to understand and generate human-like language. I can answer questions, provide information, and even have conversations like this on...
https://python.langchain.com/en/latest/getting_started/getting_started.html
877b0880109d-0
.md .pdf Concepts Contents Chain of Thought Action Plan Generation ReAct Self-ask Prompt Chaining Memetic Proxy Self Consistency Inception MemPrompt Concepts# These are concepts and terminology commonly used when developing LLM applications. It contains reference to external papers or sources where the concept was fi...
https://python.langchain.com/en/latest/getting_started/concepts.html
877b0880109d-1
to respond in a certain way framing the discussion in a context that the model knows of and that will result in that type of response. For example, as a conversation between a student and a teacher. Paper Self Consistency# Self Consistency is a decoding strategy that samples a diverse set of reasoning paths and then se...
https://python.langchain.com/en/latest/getting_started/concepts.html
46bbc825a5f3-0
.rst .pdf Chains Chains# Note Conceptual Guide Using an LLM in isolation is fine for some simple applications, but many more complex ones require chaining LLMs - either with each other or with other experts. LangChain provides a standard interface for Chains, as well as some common implementations of chains for ease of...
https://python.langchain.com/en/latest/modules/chains.html
3cb2da61f482-0
.rst .pdf Agents Contents Action Agents Plan-and-Execute Agents Agents# Note Conceptual Guide Some applications will require not just a predetermined chain of calls to LLMs/other tools, but potentially an unknown chain that depends on the user’s input. In these types of chains, there is a “agent” which has access to ...
https://python.langchain.com/en/latest/modules/agents.html
3cb2da61f482-1
The different abstractions involved in agents are as follows: Agent: this is where the logic of the application lives. Agents expose an interface that takes in user input along with a list of previous steps the agent has taken, and returns either an AgentAction or AgentFinish AgentAction corresponds to the tool to use ...
https://python.langchain.com/en/latest/modules/agents.html
3cb2da61f482-2
Agents In this section we cover the different types of agents LangChain supports natively. We then cover how to modify and create your own agents. Toolkits In this section we go over the various toolkits that LangChain supports out of the box, and how to create an agent from them. Agent Executor In this section we go o...
https://python.langchain.com/en/latest/modules/agents.html
0ed87119978b-0
.rst .pdf Prompts Contents Getting Started Go Deeper Prompts# Note Conceptual Guide The new way of programming models is through prompts. A “prompt” refers to the input to the model. This input is rarely hard coded, but rather is often constructed from multiple components. A PromptTemplate is responsible for the cons...
https://python.langchain.com/en/latest/modules/prompts.html
ec7246c2d630-0
.rst .pdf Indexes Contents Go Deeper Indexes# Note Conceptual Guide Indexes refer to ways to structure documents so that LLMs can best interact with them. This module contains utility functions for working with documents, different types of indexes, and then examples for using those indexes in chains. The most common...
https://python.langchain.com/en/latest/modules/indexes.html
ec7246c2d630-1
previous Zep Memory next Getting Started Contents Go Deeper By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/indexes.html
1cd63d300b10-0
.rst .pdf Memory Memory# Note Conceptual Guide By default, Chains and Agents are stateless, meaning that they treat each incoming query independently (as are the underlying LLMs and chat models). In some applications (chatbots being a GREAT example) it is highly important to remember previous interactions, both at a sh...
https://python.langchain.com/en/latest/modules/memory.html
53ebaf2d85bc-0
.rst .pdf Models Contents Getting Started Go Deeper Models# Note Conceptual Guide This section of the documentation deals with different types of models that are used in LangChain. On this page we will go over the model types at a high level, but we have individual pages for each model type. The pages contain more de...
https://python.langchain.com/en/latest/modules/models.html
195c75fe17f5-0
.ipynb .pdf Callbacks Contents Callbacks How to use callbacks When do you want to use each of these? Using an existing handler Creating a custom handler Async Callbacks Using multiple handlers, passing in handlers Tracing and Token Counting Tracing Token Counting Callbacks# LangChain provides a callbacks system that ...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
195c75fe17f5-1
CallbackHandlers are objects that implement the CallbackHandler interface, which has a method for each event that can be subscribed to. The CallbackManager will call the appropriate method on each handler when the event is triggered. class BaseCallbackHandler: """Base callback handler that can be used to handle cal...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
195c75fe17f5-2
def on_tool_end(self, output: str, **kwargs: Any) -> Any: """Run when tool ends running.""" def on_tool_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> Any: """Run when tool errors.""" def on_text(self, text: str, **kwargs: Any) -> Any: """Run on a...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
195c75fe17f5-3
The verbose argument is available on most objects throughout the API (Chains, Models, Tools, Agents, etc.) as a constructor argument, eg. LLMChain(verbose=True), and it is equivalent to passing a ConsoleCallbackHandler to the callbacks argument of that object and all child objects. This is useful for debugging, as it w...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
195c75fe17f5-4
# First, let's explicitly set the StdOutCallbackHandler in `callbacks` chain = LLMChain(llm=llm, prompt=prompt, callbacks=[handler]) chain.run(number=2) # Then, let's use the `verbose` flag to achieve the same result chain = LLMChain(llm=llm, prompt=prompt, verbose=True) chain.run(number=2) # Finally, let's use the req...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
195c75fe17f5-5
chat([HumanMessage(content="Tell me a joke")]) My custom handler, token: My custom handler, token: Why My custom handler, token: did My custom handler, token: the My custom handler, token: tomato My custom handler, token: turn My custom handler, token: red My custom handler, token: ? My custom handler, token: Be...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
195c75fe17f5-6
self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any ) -> None: """Run when chain starts running.""" print("zzzz....") await asyncio.sleep(0.3) class_name = serialized["name"] print("Hi! I just woke up. Your llm is starting") async def on_llm_end(self, resp...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
195c75fe17f5-7
Sync handler being called in a `thread_pool_executor`: token: they Sync handler being called in a `thread_pool_executor`: token: make Sync handler being called in a `thread_pool_executor`: token: up Sync handler being called in a `thread_pool_executor`: token: everything Sync handler being called in a `thread_pool_...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
195c75fe17f5-8
from langchain.agents import AgentType, initialize_agent, load_tools from langchain.callbacks import tracing_enabled from langchain.llms import OpenAI # First, define custom callback handler implementations class MyCustomHandlerOne(BaseCallbackHandler): def on_llm_start( self, serialized: Dict[str, Any], pr...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
195c75fe17f5-9
handler1 = MyCustomHandlerOne() handler2 = MyCustomHandlerTwo() # Setup the agent. Only the `llm` will issue callbacks for handler2 llm = OpenAI(temperature=0, streaming=True, callbacks=[handler2]) tools = load_tools(["llm-math"], llm=llm) agent = initialize_agent( tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRI...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
195c75fe17f5-10
on_chain_start LLMChain on_llm_start OpenAI on_llm_start (I'm the second handler!!) OpenAI on_new_token on_new_token ```text on_new_token on_new_token 2 on_new_token ** on_new_token 0 on_new_token . on_new_token 235 on_new_token on_new_token ``` on_new_token ... on_new_token num on_new_token expr on_new_token . on_n...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
195c75fe17f5-11
Using a context manager with tracing_enabled() to trace a particular block of code. Note if the environment variable is set, all code will be traced, regardless of whether or not it’s within the context manager. import os from langchain.agents import AgentType, initialize_agent, load_tools from langchain.callbacks impo...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
195c75fe17f5-12
Action: Search Action Input: "US Open men's final 2019 winner" Observation: Rafael Nadal defeated Daniil Medvedev in the final, 7–5, 6–3, 5–7, 4–6, 6–4 to win the men's singles tennis title at the 2019 US Open. It was his fourth US ... Thought: I need to find out the age of the winner Action: Search Action Input: "Rafa...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
195c75fe17f5-13
Action: Calculator Action Input: 29^0.23 Observation: Answer: 2.169459462491557 Thought: I now know the final answer. Final Answer: Harry Styles is Olivia Wilde's boyfriend and his current age raised to the 0.23 power is 2.169459462491557. > Finished chain. # Now, we unset the environment variable and use a context man...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
195c75fe17f5-14
Thought: I now know the final answer Final Answer: Rafael Nadal, aged 36, won the US Open men's final in 2019 and his age raised to the 0.334 power is 3.3098250249682484. > Finished chain. > Entering new AgentExecutor chain... I need to find out who Olivia Wilde's boyfriend is and then calculate his age raised to the ...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
195c75fe17f5-15
task = asyncio.create_task(agent.arun(questions[0])) # this should not be traced with tracing_enabled() as session: assert session tasks = [agent.arun(q) for q in questions[1:3]] # these should be traced await asyncio.gather(*tasks) await task > Entering new AgentExecutor chain... > Entering new AgentExec...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
195c75fe17f5-16
Action: Search Action Input: "Rafael Nadal age"36 years I need to find out Harry Styles' age. Action: Search Action Input: "Harry Styles age" I need to find out Lewis Hamilton's age Action: Search Action Input: "Lewis Hamilton Age"29 years I need to calculate the age raised to the 0.334 power Action: Calculator Action ...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
195c75fe17f5-17
with get_openai_callback() as cb: await asyncio.gather( *[llm.agenerate(["What is the square root of 4?"]) for _ in range(3)] ) assert cb.total_tokens == total_tokens * 3 # The context manager is concurrency safe task = asyncio.create_task(llm.agenerate(["What is the square root of 4?"])) with get_opena...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
b228bae66839-0
.rst .pdf Prompt Templates Prompt Templates# Note Conceptual Guide Language models take text as input - that text is commonly referred to as a prompt. Typically this is not simply a hardcoded string but rather a combination of a template, some examples, and user input. LangChain provides several classes and functions t...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates.html
e15e9f11fa03-0
.rst .pdf Output Parsers Output Parsers# Note Conceptual Guide Language models output text. But many times you may want to get more structured information than just text back. This is where output parsers come in. Output parsers are classes that help structure language model responses. There are two main methods an out...
https://python.langchain.com/en/latest/modules/prompts/output_parsers.html
8ec1d4b7a66e-0
.ipynb .pdf Getting Started Contents PromptTemplates to_string to_messages Getting Started# This section contains everything related to prompts. A prompt is the value passed into the Language Model. This value can either be a string (for LLMs) or a list of messages (for Chat Models). The data types of these prompts a...
https://python.langchain.com/en/latest/modules/prompts/getting_started.html
8ec1d4b7a66e-1
string_prompt_value.to_string() 'tell me a joke about soccer' chat_prompt_value.to_string() 'Human: tell me a joke about soccer' to_messages# This is what is called when passing to ChatModel (which expects a list of messages) string_prompt_value.to_messages() [HumanMessage(content='tell me a joke about soccer', additio...
https://python.langchain.com/en/latest/modules/prompts/getting_started.html
135e245479f9-0
.rst .pdf Example Selectors Example Selectors# Note Conceptual Guide If you have a large number of examples, you may need to select which ones to include in the prompt. The ExampleSelector is the class responsible for doing so. The base interface is defined as below: class BaseExampleSelector(ABC): """Interface for...
https://python.langchain.com/en/latest/modules/prompts/example_selectors.html
f6246366ced8-0
.ipynb .pdf Chat Prompt Template Contents Format output Different types of MessagePromptTemplate Chat Prompt Template# Chat Models takes a list of chat messages as input - this list commonly referred to as a prompt. These chat messages differ from raw string (which you would pass into a LLM model) in that every messa...
https://python.langchain.com/en/latest/modules/prompts/chat_prompt_template.html
f6246366ced8-1
input_variables=["input_language", "output_language"], ) system_message_prompt_2 = SystemMessagePromptTemplate(prompt=prompt) assert system_message_prompt == system_message_prompt_2 After that, you can build a ChatPromptTemplate from one or more MessagePromptTemplates. You can use ChatPromptTemplate’s format_prompt – t...
https://python.langchain.com/en/latest/modules/prompts/chat_prompt_template.html
f6246366ced8-2
[SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}), HumanMessage(content='I love programming.', additional_kwargs={})] Different types of MessagePromptTemplate# LangChain provides different types of MessagePromptTemplate. The most commonly used are AIMessageP...
https://python.langchain.com/en/latest/modules/prompts/chat_prompt_template.html
f6246366ced8-3
3. Practice, practice, practice: The best way to learn programming is through hands-on experience\ """) chat_prompt.format_prompt(conversation=[human_message, ai_message], word_count="10").to_messages() [HumanMessage(content='What is the best way to learn programming?', additional_kwargs={}), AIMessage(content='1. Cho...
https://python.langchain.com/en/latest/modules/prompts/chat_prompt_template.html
8fc1f064cb75-0
.ipynb .pdf NGram Overlap ExampleSelector NGram Overlap ExampleSelector# The NGramOverlapExampleSelector selects and orders examples based on which examples are most similar to the input, according to an ngram overlap score. The ngram overlap score is a float between 0.0 and 1.0, inclusive. The selector allows for a th...
https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html
8fc1f064cb75-1
{"input": "Spot can run.", "output": "Spot puede correr."}, ] example_prompt = PromptTemplate( input_variables=["input", "output"], template="Input: {input}\nOutput: {output}", ) example_selector = NGramOverlapExampleSelector( # These are the examples it has available to choose from. examples=examples, ...
https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html
8fc1f064cb75-2
Output: Ver correr a Spot. Input: My dog barks. Output: Mi perro ladra. Input: Spot can run fast. Output: # You can add examples to NGramOverlapExampleSelector as well. new_example = {"input": "Spot plays fetch.", "output": "Spot juega a buscar."} example_selector.add_example(new_example) print(dynamic_prompt.format(se...
https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html
8fc1f064cb75-3
Input: Spot plays fetch. Output: Spot juega a buscar. Input: Spot can play fetch. Output: # Setting threshold greater than 1.0 example_selector.threshold=1.0+1e-9 print(dynamic_prompt.format(sentence="Spot can play fetch.")) Give the Spanish translation of every input Input: Spot can play fetch. Output: previous Maxima...
https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html
7adb456c2ba0-0
.ipynb .pdf Similarity ExampleSelector Similarity ExampleSelector# The SemanticSimilarityExampleSelector selects examples based on which examples are most similar to the inputs. It does this by finding the examples with the embeddings that have the greatest cosine similarity with the inputs. from langchain.prompts.exam...
https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/similarity.html
7adb456c2ba0-1
example_prompt=example_prompt, prefix="Give the antonym of every input", suffix="Input: {adjective}\nOutput:", input_variables=["adjective"], ) Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient. # Input is a feeling, so should select the happy/sad example pr...
https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/similarity.html
9b478ebba4d2-0
.ipynb .pdf Maximal Marginal Relevance ExampleSelector Maximal Marginal Relevance ExampleSelector# The MaxMarginalRelevanceExampleSelector selects examples based on a combination of which examples are most similar to the inputs, while also optimizing for diversity. It does this by finding the examples with the embeddin...
https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/mmr.html
9b478ebba4d2-1
k=2 ) mmr_prompt = FewShotPromptTemplate( # We provide an ExampleSelector instead of examples. example_selector=example_selector, example_prompt=example_prompt, prefix="Give the antonym of every input", suffix="Input: {adjective}\nOutput:", input_variables=["adjective"], ) # Input is a feeling,...
https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/mmr.html
a010594b30fa-0
.md .pdf How to create a custom example selector Contents Implement custom example selector Use custom example selector How to create a custom example selector# In this tutorial, we’ll create a custom example selector that selects every alternate example from a given list of examples. An ExampleSelector must implemen...
https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/custom_example_selector.html
a010594b30fa-1
# Add new example to the set of examples example_selector.add_example({"foo": "4"}) example_selector.examples # -> [{'foo': '1'}, {'foo': '2'}, {'foo': '3'}, {'foo': '4'}] # Select examples example_selector.select_examples({"foo": "foo"}) # -> array([{'foo': '1'}, {'foo': '4'}], dtype=object) previous Example Selectors...
https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/custom_example_selector.html
f2fc8cfb4838-0
.ipynb .pdf LengthBased ExampleSelector LengthBased ExampleSelector# This ExampleSelector selects which examples to use based on length. This is useful when you are worried about constructing a prompt that will go over the length of the context window. For longer inputs, it will select fewer examples to include, while ...
https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/length_based.html
f2fc8cfb4838-1
# it is provided as a default value if none is specified. # get_text_length: Callable[[str], int] = lambda x: len(re.split("\n| ", x)) ) dynamic_prompt = FewShotPromptTemplate( # We provide an ExampleSelector instead of examples. example_selector=example_selector, example_prompt=example_prompt, pref...
https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/length_based.html
f2fc8cfb4838-2
Input: sunny Output: gloomy Input: windy Output: calm Input: big Output: small Input: enthusiastic Output: previous How to create a custom example selector next Maximal Marginal Relevance ExampleSelector By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/length_based.html
300f1b6ae36d-0
.ipynb .pdf Output Parsers Output Parsers# Language models output text. But many times you may want to get more structured information than just text back. This is where output parsers come in. Output parsers are classes that help structure language model responses. There are two main methods an output parser must impl...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/getting_started.html
300f1b6ae36d-1
punchline: str = Field(description="answer to resolve the joke") # You can add custom validation logic easily with Pydantic. @validator('setup') def question_ends_with_question_mark(cls, field): if field[-1] != '?': raise ValueError("Badly formed question!") return field # S...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/getting_started.html
6b2d961036e5-0
.ipynb .pdf RetryOutputParser RetryOutputParser# While in some cases it is possible to fix any parsing mistakes by only looking at the output, in other cases it can’t. An example of this is when the output is not just in the incorrect format, but is partially complete. Consider the below example. from langchain.prompts...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/retry.html
6b2d961036e5-1
23 json_object = json.loads(json_str) ---> 24 return self.pydantic_object.parse_obj(json_object) 26 except (json.JSONDecodeError, ValidationError) as e: File ~/.pyenv/versions/3.9.1/envs/langchain/lib/python3.9/site-packages/pydantic/main.py:527, in pydantic.main.BaseModel.parse_obj() File ~/.pyenv/version...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/retry.html
6b2d961036e5-2
fix_parser.parse(bad_response) Action(action='search', action_input='') Instead, we can use the RetryOutputParser, which passes in the prompt (as well as the original output) to try again to get a better response. from langchain.output_parsers import RetryWithErrorOutputParser retry_parser = RetryWithErrorOutputParser....
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/retry.html
b79ff8b48782-0
.ipynb .pdf Enum Output Parser Enum Output Parser# This notebook shows how to use an Enum output parser from langchain.output_parsers.enum import EnumOutputParser from enum import Enum class Colors(Enum): RED = "red" GREEN = "green" BLUE = "blue" parser = EnumOutputParser(enum=Colors) parser.parse("red") <C...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/enum.html
b79ff8b48782-1
During handling of the above exception, another exception occurred: OutputParserException Traceback (most recent call last) Cell In[8], line 2 1 # And raises errors when appropriate ----> 2 parser.parse("yellow") File ~/workplace/langchain/langchain/output_parsers/enum.py:27, in EnumOutputPars...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/enum.html
cbbf4984b062-0
.ipynb .pdf PydanticOutputParser PydanticOutputParser# This output parser allows users to specify an arbitrary JSON schema and query LLMs for JSON outputs that conform to that schema. Keep in mind that large language models are leaky abstractions! You’ll have to use an LLM with sufficient capacity to generate well-form...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/pydantic.html
cbbf4984b062-1
prompt = PromptTemplate( template="Answer the user query.\n{format_instructions}\n{query}\n", input_variables=["query"], partial_variables={"format_instructions": parser.get_format_instructions()} ) _input = prompt.format_prompt(query=joke_query) output = model(_input.to_string()) parser.parse(output) Joke(...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/pydantic.html
248bc3127f30-0
.ipynb .pdf CommaSeparatedListOutputParser CommaSeparatedListOutputParser# Here’s another parser strictly less powerful than Pydantic/JSON parsing. from langchain.output_parsers import CommaSeparatedListOutputParser from langchain.prompts import PromptTemplate, ChatPromptTemplate, HumanMessagePromptTemplate from langch...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/comma_separated.html
9681b72bb033-0
.ipynb .pdf OutputFixingParser OutputFixingParser# This output parser wraps another output parser and tries to fix any mistakes The Pydantic guardrail simply tries to parse the LLM response. If it does not parse correctly, then it errors. But we can do other things besides throw errors. Specifically, we can pass the mi...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/output_fixing_parser.html
9681b72bb033-1
24 return self.pydantic_object.parse_obj(json_object) File ~/.pyenv/versions/3.9.1/lib/python3.9/json/__init__.py:346, in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw) 343 if (cls is None and object_hook is None and 344 parse_int is None and parse_float is N...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/output_fixing_parser.html
9681b72bb033-2
Cell In[6], line 1 ----> 1 parser.parse(misformatted) File ~/workplace/langchain/langchain/output_parsers/pydantic.py:29, in PydanticOutputParser.parse(self, text) 27 name = self.pydantic_object.__name__ 28 msg = f"Failed to parse {name} from completion {text}. Got: {e}" ---> 29 raise OutputParserException(ms...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/output_fixing_parser.html
a654157d280a-0
.ipynb .pdf Structured Output Parser Structured Output Parser# While the Pydantic/JSON parser is more powerful, we initially experimented data structures having text fields only. from langchain.output_parsers import StructuredOutputParser, ResponseSchema from langchain.prompts import PromptTemplate, ChatPromptTemplate,...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/structured.html
a654157d280a-1
prompt = ChatPromptTemplate( messages=[ HumanMessagePromptTemplate.from_template("answer the users question as best as possible.\n{format_instructions}\n{question}") ], input_variables=["question"], partial_variables={"format_instructions": format_instructions} ) _input = prompt.format_prompt(...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/structured.html
ee48a65caf0d-0
.md .pdf Getting Started Contents What is a prompt template? Create a prompt template Template formats Validate template Serialize prompt template Pass few shot examples to a prompt template Select examples for a prompt template Getting Started# In this tutorial, we will learn about: what a prompt template is, and wh...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html
ee48a65caf0d-1
no_input_prompt.format() # -> "Tell me a joke." # An example prompt with one input variable one_input_prompt = PromptTemplate(input_variables=["adjective"], template="Tell me a {adjective} joke.") one_input_prompt.format(adjective="funny") # -> "Tell me a funny joke." # An example prompt with multiple input variables m...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html
ee48a65caf0d-2
# -> Tell me a funny joke about chickens. Currently, PromptTemplate only supports jinja2 and f-string templating format. If there is any other templating format that you would like to use, feel free to open an issue in the Github page. Validate template# By default, PromptTemplate will validate the template string by c...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html
ee48a65caf0d-3
To generate a prompt with few shot examples, you can use the FewShotPromptTemplate. This class takes in a PromptTemplate and a list of few shot examples. It then formats the prompt template with the few shot examples. In this example, we’ll create a prompt to generate word antonyms. from langchain import PromptTemplate...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html
ee48a65caf0d-4
input_variables=["input"], # The example_separator is the string we will use to join the prefix, examples, and suffix together with. example_separator="\n", ) # We can now generate a prompt using the `format` method. print(few_shot_prompt.format(input="big")) # -> Give the antonym of every input # -> # -> Word...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html
ee48a65caf0d-5
{"word": "windy", "antonym": "calm"}, ] # We'll use the `LengthBasedExampleSelector` to select the examples. example_selector = LengthBasedExampleSelector( # These are the examples is has available to choose from. examples=examples, # This is the PromptTemplate being used to format the examples. exampl...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html
ee48a65caf0d-6
# -> Antonym: lethargic # -> # -> Word: sunny # -> Antonym: gloomy # -> # -> Word: windy # -> Antonym: calm # -> # -> Word: big # -> Antonym: In contrast, if we provide a very long input, the LengthBasedExampleSelector will select fewer examples to include in the prompt. long_string = "big and huge and massive and larg...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html
6d03c55b2dd4-0
.rst .pdf How-To Guides How-To Guides# If you’re new to the library, you may want to start with the Quickstart. The user guide here shows more advanced workflows and how to use the library in different ways. Connecting to a Feature Store How to create a custom prompt template How to create a prompt template that uses f...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/how_to_guides.html