id stringlengths 14 16 | source stringlengths 49 117 | text stringlengths 16 2.73k |
|---|---|---|
4adc05761a2a-3 | https://python.langchain.com/en/latest/modules/models/llms/integrations/replicate.html | > Entering new SimpleSequentialChain chain...
novelty socks
todd & co.
https://replicate.delivery/pbxt/BedAP1PPBwXFfkmeD7xDygXO4BcvApp1uvWOwUdHM4tcQfvCB/out-0.png
> Finished chain.
https://replicate.delivery/pbxt/BedAP1PPBwXFfkmeD7xDygXO4BcvApp1uvWOwUdHM4tcQfvCB/out-0.png
response = requests.get("https://replicate.deli... |
5fe0a496e1c7-0 | https://python.langchain.com/en/latest/modules/models/llms/integrations/google_vertex_ai_palm.html | .ipynb
.pdf
Google Cloud Platform Vertex AI PaLM
Google Cloud Platform 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, su... |
5fe0a496e1c7-1 | https://python.langchain.com/en/latest/modules/models/llms/integrations/google_vertex_ai_palm.html | llm_chain = LLMChain(prompt=prompt, llm=llm)
question = "What NFL team won the Super Bowl in the year Justin Beiber was born?"
llm_chain.run(question)
'Justin Bieber was born on March 1, 1994. The Super Bowl in 1994 was won by the San Francisco 49ers.\nThe final answer: San Francisco 49ers.'
previous
ForefrontAI
next
G... |
e8fa7a5a526b-0 | https://python.langchain.com/en/latest/modules/models/llms/examples/async_llm.html | .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... |
e8fa7a5a526b-1 | https://python.langchain.com/en/latest/modules/models/llms/examples/async_llm.html | I'm doing well, thank you. How about you?
I'm doing well, thank you. How about you?
I'm doing well, how about you?
I'm doing well, thank you. How about you?
I'm doing well, thank you. How about you?
I'm doing well, thank you. How about yourself?
I'm doing well, thank you! How about you?
I'm doing well, thank you. How a... |
f8b4b718c04e-0 | https://python.langchain.com/en/latest/modules/models/llms/examples/human_input_llm.html | .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... |
f8b4b718c04e-1 | https://python.langchain.com/en/latest/modules/models/llms/examples/human_input_llm.html | Observation: the result of the action
... (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:
=====END OF PROMPT======
I need to use a tool.
Action: Wiki... |
f8b4b718c04e-2 | https://python.langchain.com/en/latest/modules/models/llms/examples/human_input_llm.html | Summary: Manga Time Kirara Max (まんがタイムきららMAX) is a Japanese four-panel seinen manga magazine published by Houbunsha. It is the third magazine of the "Kirara" series, after "Manga Time Kirara" and "Manga Time Kirara Carat". The first issue was released on September 29, 2004. Currently the magazine is released on the 19t... |
f8b4b718c04e-3 | https://python.langchain.com/en/latest/modules/models/llms/examples/human_input_llm.html | Summary: Bocchi the Rock! (ぼっち・ざ・ろっく!, Bocchi Za Rokku!) is a Japanese four-panel manga series written and illustrated by Aki Hamaji. It has been serialized in Houbunsha's seinen manga magazine Manga Time Kirara Max since December 2017. Its chapters have been collected in five tankōbon volumes as of November 2022.
An a... |
f8b4b718c04e-4 | https://python.langchain.com/en/latest/modules/models/llms/examples/human_input_llm.html | Observation: Page: Bocchi the Rock!
Summary: Bocchi the Rock! (ぼっち・ざ・ろっく!, Bocchi Za Rokku!) is a Japanese four-panel manga series written and illustrated by Aki Hamaji. It has been serialized in Houbunsha's seinen manga magazine Manga Time Kirara Max since December 2017. Its chapters have been collected in five tankōb... |
f8b4b718c04e-5 | https://python.langchain.com/en/latest/modules/models/llms/examples/human_input_llm.html | Summary: Bocchi the Rock! (ぼっち・ざ・ろっく!, Bocchi Za Rokku!) is a Japanese four-panel manga series written and illustrated by Aki Hamaji. It has been serialized in Houbunsha's seinen manga magazine Manga Time Kirara Max since December 2017. Its chapters have been collected in five tankōbon volumes as of November 2022.
An a... |
f8b4b718c04e-6 | https://python.langchain.com/en/latest/modules/models/llms/examples/human_input_llm.html | Summary: Bocchi the Rock! (ぼっち・ざ・ろっく!, Bocchi Za Rokku!) is a Japanese four-panel manga series written and illustrated by Aki Hamaji. It has been serialized in Houbunsha's seinen manga magazine Manga Time Kirara Max since December 2017. Its chapters have been collected in five tankōbon volumes as of November 2022.
An a... |
b53e71009bd8-0 | https://python.langchain.com/en/latest/modules/models/llms/examples/custom_llm.html | .ipynb
.pdf
How to write a custom LLM wrapper
How to write a custom LLM wrapper#
This notebook goes over how to create a custom LLM wrapper, in case you want to use your own LLM or a different wrapper than one that is supported in LangChain.
There is only one required thing that a custom LLM needs to implement:
A _call... |
b53e71009bd8-1 | https://python.langchain.com/en/latest/modules/models/llms/examples/custom_llm.html | print(llm)
CustomLLM
Params: {'n': 10}
previous
How to use the async API for LLMs
next
How (and why) to use the fake LLM
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
13bf5cb633da-0 | https://python.langchain.com/en/latest/modules/models/llms/examples/streaming_llm.html | .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... |
13bf5cb633da-1 | https://python.langchain.com/en/latest/modules/models/llms/examples/streaming_llm.html | It's the best way to stay hydrated,
It's so crisp and so clean,
It's the perfect way to stay refreshed.
We still have access to the end LLMResult if using generate. However, token_usage is not currently supported for streaming.
llm.generate(["Tell me a joke."])
Q: What did the fish say when it hit the wall?
A: Dam!
LLM... |
13bf5cb633da-2 | https://python.langchain.com/en/latest/modules/models/llms/examples/streaming_llm.html | You make me feel so light
I'll never give you up, you're my true love
Sparkling water, you're sent from above
Chorus:
Sparkling water, oh how you shine
A taste so clean, it's simply divine
You quench my thirst, you make me feel alive
Sparkling water, you're my favorite vibe
Outro:
Sparkling water, you're the one for me... |
3a15eb45a168-0 | https://python.langchain.com/en/latest/modules/models/llms/examples/llm_serialization.html | .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... |
3a15eb45a168-1 | https://python.langchain.com/en/latest/modules/models/llms/examples/llm_serialization.html | llm.save("llm.yaml")
previous
How to cache LLM calls
next
How to stream LLM and Chat Model responses
Contents
Loading
Saving
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
c0dddb2a004c-0 | https://python.langchain.com/en/latest/modules/models/llms/examples/fake_llm.html | .ipynb
.pdf
How (and why) to use the fake LLM
How (and why) to use the fake LLM#
We expose a fake LLM class that can be used for testing. This allows you to mock out calls to the LLM and simulate what would happen if the LLM responded in a certain way.
In this notebook we go over how to use this.
We start this with usi... |
f2b8694d4c82-0 | https://python.langchain.com/en/latest/modules/models/llms/examples/llm_caching.html | .ipynb
.pdf
How to cache LLM calls
Contents
In Memory Cache
SQLite Cache
Redis Cache
Standard Cache
Semantic Cache
GPTCache
Momento Cache
SQLAlchemy Cache
Custom SQLAlchemy Schemas
Optional Caching
Optional Caching in Chains
How to cache LLM calls#
This notebook covers how to cache results of individual LLM calls.
im... |
f2b8694d4c82-1 | https://python.langchain.com/en/latest/modules/models/llms/examples/llm_caching.html | CPU times: user 17 ms, sys: 9.76 ms, total: 26.7 ms
Wall time: 825 ms
'\n\nWhy did the chicken cross the road?\n\nTo get to the other side.'
%%time
# The second time it is, so it goes faster
llm("Tell me a joke")
CPU times: user 2.46 ms, sys: 1.23 ms, total: 3.7 ms
Wall time: 2.67 ms
'\n\nWhy did the chicken cross the ... |
f2b8694d4c82-2 | https://python.langchain.com/en/latest/modules/models/llms/examples/llm_caching.html | from langchain.cache import RedisSemanticCache
langchain.llm_cache = RedisSemanticCache(
redis_url="redis://localhost:6379",
embedding=OpenAIEmbeddings()
)
%%time
# The first time, it is not yet in cache, so it should take longer
llm("Tell me a joke")
CPU times: user 351 ms, sys: 156 ms, total: 507 ms
Wall time... |
f2b8694d4c82-3 | https://python.langchain.com/en/latest/modules/models/llms/examples/llm_caching.html | # The first time, it is not yet in cache, so it should take longer
llm("Tell me a joke")
CPU times: user 21.5 ms, sys: 21.3 ms, total: 42.8 ms
Wall time: 6.2 s
'\n\nWhy did the chicken cross the road?\n\nTo get to the other side!'
%%time
# The second time it is, so it goes faster
llm("Tell me a joke")
CPU times: user 5... |
f2b8694d4c82-4 | https://python.langchain.com/en/latest/modules/models/llms/examples/llm_caching.html | CPU times: user 866 ms, sys: 20 ms, total: 886 ms
Wall time: 226 ms
'\n\nWhy did the chicken cross the road?\n\nTo get to the other side.'
%%time
# This is not an exact match, but semantically within distance so it hits!
llm("Tell me joke")
CPU times: user 853 ms, sys: 14.8 ms, total: 868 ms
Wall time: 224 ms
'\n\nWhy ... |
f2b8694d4c82-5 | https://python.langchain.com/en/latest/modules/models/llms/examples/llm_caching.html | llm("Tell me a joke")
CPU times: user 3.16 ms, sys: 2.98 ms, total: 6.14 ms
Wall time: 57.9 ms
'\n\nWhy did the chicken cross the road?\n\nTo get to the other side!'
SQLAlchemy Cache#
# You can use SQLAlchemyCache to cache with any SQL database supported by SQLAlchemy.
# from langchain.cache import SQLAlchemyCache
# fr... |
f2b8694d4c82-6 | https://python.langchain.com/en/latest/modules/models/llms/examples/llm_caching.html | engine = create_engine("postgresql://postgres:postgres@localhost:5432/postgres")
langchain.llm_cache = SQLAlchemyCache(engine, FulltextLLMCache)
Optional Caching#
You can also turn off caching for specific LLMs should you choose. In the example below, even though global caching is enabled, we turn it off for a specific... |
f2b8694d4c82-7 | https://python.langchain.com/en/latest/modules/models/llms/examples/llm_caching.html | state_of_the_union = f.read()
texts = text_splitter.split_text(state_of_the_union)
from langchain.docstore.document import Document
docs = [Document(page_content=t) for t in texts[:3]]
from langchain.chains.summarize import load_summarize_chain
chain = load_summarize_chain(llm, chain_type="map_reduce", reduce_llm=no_ca... |
f2b8694d4c82-8 | https://python.langchain.com/en/latest/modules/models/llms/examples/llm_caching.html | !rm .langchain.db sqlite.db
previous
How (and why) to use the human input LLM
next
How to serialize LLM classes
Contents
In Memory Cache
SQLite Cache
Redis Cache
Standard Cache
Semantic Cache
GPTCache
Momento Cache
SQLAlchemy Cache
Custom SQLAlchemy Schemas
Optional Caching
Optional Caching in Chains
By Harrison Ch... |
741b4b8d2838-0 | https://python.langchain.com/en/latest/modules/models/llms/examples/token_usage_tracking.html | .ipynb
.pdf
How to track token usage
How to track token usage#
This notebook goes over how to track your token usage for specific calls. It is currently only implemented for the OpenAI API.
Let’s first look at an extremely simple example of tracking token usage for a single LLM call.
from langchain.llms import OpenAI
f... |
741b4b8d2838-1 | https://python.langchain.com/en/latest/modules/models/llms/examples/token_usage_tracking.html | print(f"Total Tokens: {cb.total_tokens}")
print(f"Prompt Tokens: {cb.prompt_tokens}")
print(f"Completion Tokens: {cb.completion_tokens}")
print(f"Total Cost (USD): ${cb.total_cost}")
> Entering new AgentExecutor chain...
I need to find out who Olivia Wilde's boyfriend is and then calculate his age raised t... |
dd7eea3b1aad-0 | https://python.langchain.com/en/latest/modules/prompts/example_selectors.html | .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... |
92dce86294aa-0 | https://python.langchain.com/en/latest/modules/prompts/getting_started.html | .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... |
92dce86294aa-1 | https://python.langchain.com/en/latest/modules/prompts/getting_started.html | 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', additional_kwargs={}, example=False)]
chat_prompt_value.to_messages()... |
b1a7c2b3c81a-0 | https://python.langchain.com/en/latest/modules/prompts/output_parsers.html | .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... |
b5c7d5a4f20f-0 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates.html | .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... |
6488d1e8adff-0 | https://python.langchain.com/en/latest/modules/prompts/chat_prompt_template.html | .ipynb
.pdf
Chat Prompt Templates
Contents
Format output
Different types of MessagePromptTemplate
Chat Prompt Templates#
Chat Models take 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 mess... |
6488d1e8adff-1 | https://python.langchain.com/en/latest/modules/prompts/chat_prompt_template.html | 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 – this returns a PromptValue, which you can convert to a str... |
6488d1e8adff-2 | https://python.langchain.com/en/latest/modules/prompts/chat_prompt_template.html | [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... |
6488d1e8adff-3 | https://python.langchain.com/en/latest/modules/prompts/chat_prompt_template.html | 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... |
6414e0cd8977-0 | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/similarity.html | .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... |
6414e0cd8977-1 | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/similarity.html | 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
print(similar_prompt.format(adjective="worried"))
Give the antonym of every input
I... |
f6de076af677-0 | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/mmr.html | .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... |
f6de076af677-1 | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/mmr.html | 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, so sh... |
f6de076af677-2 | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/mmr.html | previous
LengthBased ExampleSelector
next
NGram Overlap ExampleSelector
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
ac59e3b963f7-0 | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/length_based.html | .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 ... |
ac59e3b963f7-1 | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/length_based.html | # 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,
prefix="Give the antonym of every input",
suffix="Input: {adje... |
ac59e3b963f7-2 | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/length_based.html | How to create a custom example selector
next
Maximal Marginal Relevance ExampleSelector
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
cd9aabaea797-0 | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html | .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... |
cd9aabaea797-1 | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html | ]
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,
# This is the PromptTemplate being used to format the e... |
cd9aabaea797-2 | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html | # 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(sentence="Spot can run fast."))
Give the Spanish translation of every input
Input: Spot can run.
Output: Spo... |
cd9aabaea797-3 | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html | print(dynamic_prompt.format(sentence="Spot can play fetch."))
Give the Spanish translation of every input
Input: Spot can play fetch.
Output:
previous
Maximal Marginal Relevance ExampleSelector
next
Similarity ExampleSelector
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04... |
76215a7507f3-0 | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/custom_example_selector.html | .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... |
76215a7507f3-1 | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/custom_example_selector.html | # 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... |
8c94d43a011d-0 | https://python.langchain.com/en/latest/modules/prompts/output_parsers/getting_started.html | .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... |
8c94d43a011d-1 | https://python.langchain.com/en/latest/modules/prompts/output_parsers/getting_started.html | # 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
# Set up a parser + inject instructions into the prompt template.
parser = Py... |
78a01cea2cd1-0 | https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/retry.html | .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... |
78a01cea2cd1-1 | https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/retry.html | ---> 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/versions/3.9.1/envs/langchain/lib/python3.9/site-... |
78a01cea2cd1-2 | https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/retry.html | 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.from_llm(parser=parser, llm=OpenAI(temperature=0))
retry_parser.parse_wi... |
ea58e917356c-0 | https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/output_fixing_parser.html | .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... |
ea58e917356c-1 | https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/output_fixing_parser.html | 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 None and
345 parse_constant is None and obj... |
ea58e917356c-2 | https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/output_fixing_parser.html | 27 name = self.pydantic_object.__name__
28 msg = f"Failed to parse {name} from completion {text}. Got: {e}"
---> 29 raise OutputParserException(msg)
OutputParserException: Failed to parse Actor from completion {'name': 'Tom Hanks', 'film_names': ['Forrest Gump']}. Got: Expecting property name enclosed in double qu... |
3151264ea4eb-0 | https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/comma_separated.html | .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... |
c81dcf6a645f-0 | https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/structured.html | .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,... |
c81dcf6a645f-1 | https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/structured.html | 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(question="what's the capital of france?")
output = c... |
219ca9a4f432-0 | https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/enum.html | .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... |
219ca9a4f432-1 | https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/enum.html | 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 EnumOutputParser.parse(self, response)
25 return self.enum(response.strip... |
443c85ae001a-0 | https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/pydantic.html | .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... |
443c85ae001a-1 | https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/pydantic.html | 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(setup='Why did the chicken cr... |
11d8d7adb9a7-0 | https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/datetime.html | .ipynb
.pdf
Datetime
Datetime#
This OutputParser shows out to parse LLM output into datetime format.
from langchain.prompts import PromptTemplate
from langchain.output_parsers import DatetimeOutputParser
from langchain.chains import LLMChain
from langchain.llms import OpenAI
output_parser = DatetimeOutputParser()
templ... |
8966d4064b84-0 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/how_to_guides.html | .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... |
4728e6660c8d-0 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html | .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... |
4728e6660c8d-1 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html | # 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
multiple_input_prompt = PromptTemplate(
input... |
4728e6660c8d-2 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html | 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 checking whether the input_variables match ... |
4728e6660c8d-3 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html | 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... |
4728e6660c8d-4 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html | # 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: happy
# -> Antonym: sad
# ->
... |
4728e6660c8d-5 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html | # 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.
example_prompt=example_prompt,
# This is ... |
4728e6660c8d-6 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html | # ->
# -> 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 large and gigantic and tall and much much much much much bigger than everything else"
print(dynamic_prompt.forma... |
e662da381c19-0 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html | .ipynb
.pdf
How to serialize prompts
Contents
PromptTemplate
Loading from YAML
Loading from JSON
Loading Template from a File
FewShotPromptTemplate
Examples
Loading from YAML
Loading from JSON
Examples in the Config
Example Prompt from a File
PromptTempalte with OutputParser
How to serialize prompts#
It is often pref... |
e662da381c19-1 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html | print(prompt.format(adjective="funny", content="chickens"))
Tell me a funny joke about chickens.
Loading from JSON#
This shows an example of loading a PromptTemplate from JSON.
!cat simple_prompt.json
{
"_type": "prompt",
"input_variables": ["adjective", "content"],
"template": "Tell me a {adjective} joke a... |
e662da381c19-2 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html | This shows an example of loading a few shot example from YAML.
!cat few_shot_prompt.yaml
_type: few_shot
input_variables:
["adjective"]
prefix:
Write antonyms for the following words.
example_prompt:
_type: prompt
input_variables:
["input", "output"]
template:
"Input: {input}\nOutpu... |
e662da381c19-3 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html | "example_prompt": {
"_type": "prompt",
"input_variables": ["input", "output"],
"template": "Input: {input}\nOutput: {output}"
},
"examples": "examples.json",
"suffix": "Input: {adjective}\nOutput:"
}
prompt = load_prompt("few_shot_prompt.json")
print(prompt.format(adjective="funny... |
e662da381c19-4 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html | "_type": "prompt",
"input_variables": ["input", "output"],
"template": "Input: {input}\nOutput: {output}"
}
!cat few_shot_prompt_example_prompt.json
{
"_type": "few_shot",
"input_variables": ["adjective"],
"prefix": "Write antonyms for the following words.",
"example_prompt_path": "example_pro... |
e662da381c19-5 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html | prompt.output_parser.parse("George Washington was born in 1732 and died in 1799.\nScore: 1/2")
{'answer': 'George Washington was born in 1732 and died in 1799.',
'score': '1/2'}
previous
How to work with partial Prompt Templates
next
Prompts
Contents
PromptTemplate
Loading from YAML
Loading from JSON
Loading Templ... |
92ae0fc8f0bf-0 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/partial.html | .ipynb
.pdf
How to work with partial Prompt Templates
Contents
Partial With Strings
Partial With Functions
How to work with partial Prompt Templates#
A prompt template is a class with a .format method which takes in a key-value map and returns a string (a prompt) to pass to the language model. Like other methods, it ... |
92ae0fc8f0bf-1 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/partial.html | Partial With Functions#
The other common use is to partial with a function. The use case for this is when you have a variable you know that you always want to fetch in a common way. A prime example of this is with date or time. Imagine you have a prompt which you always want to have the current date. You can’t hard cod... |
92ae0fc8f0bf-2 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/partial.html | Last updated on Jun 04, 2023. |
368bc562f500-0 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html | .ipynb
.pdf
How to create a prompt template that uses few shot examples
Contents
Use Case
Using an example set
Create the example set
Create a formatter for the few shot examples
Feed examples and formatter to FewShotPromptTemplate
Using an example selector
Feed examples into ExampleSelector
Feed example selector int... |
368bc562f500-1 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html | Follow up: Who was the founder of craigslist?
Intermediate answer: Craigslist was founded by Craig Newmark.
Follow up: When was Craig Newmark born?
Intermediate answer: Craig Newmark was born on December 6, 1952.
So the final answer is: December 6, 1952
"""
},
{
"question": "Who was the maternal grandfather of ... |
368bc562f500-2 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html | Are follow up questions needed here: Yes.
Follow up: How old was Muhammad Ali when he died?
Intermediate answer: Muhammad Ali was 74 years old when he died.
Follow up: How old was Alan Turing when he died?
Intermediate answer: Alan Turing was 41 years old when he died.
So the final answer is: Muhammad Ali
Feed examples... |
368bc562f500-3 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html | Follow up: Who was the father of Mary Ball Washington?
Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
So the final answer is: Joseph Ball
Question: Are both the directors of Jaws and Casino Royale from the same country?
Are follow up questions needed here: Yes.
Follow up: Who is the director o... |
368bc562f500-4 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html | Chroma,
# This is the number of examples to produce.
k=1
)
# Select the most similar example to the input.
question = "Who was the father of Mary Ball Washington?"
selected_examples = example_selector.select_examples({"question": question})
print(f"Examples most similar to the input: {question}")
for example in... |
368bc562f500-5 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html | Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
So the final answer is: Joseph Ball
Question: Who was the father of Mary Ball Washington?
previous
How to create a custom prompt template
next
How to work with partial Prompt Templates
Contents
Use Case
Using an example set
Create the example ... |
052e6bff49a6-0 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html | .ipynb
.pdf
Connecting to a Feature Store
Contents
Feast
Load Feast Store
Prompts
Use in a chain
Tecton
Prerequisites
Define and Load Features
Prompts
Use in a chain
Featureform
Initialize Featureform
Prompts
Use in a chain
Connecting to a Feature Store#
Feature stores are a concept from traditional machine learning ... |
052e6bff49a6-1 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html | Note that the input to this prompt template is just driver_id, since that is the only user defined piece (all other variables are looked up inside the prompt template).
from langchain.prompts import PromptTemplate, StringPromptTemplate
template = """Given the driver's up to date stats, write them note relaying those st... |
052e6bff49a6-2 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html | Conversation rate: 0.4745151400566101
Acceptance rate: 0.055561766028404236
Average Daily Trips: 936
Your response:
Use in a chain#
We can now use this in a chain, successfully creating a chain that achieves personalization backed by a feature store
from langchain.chat_models import ChatOpenAI
from langchain.chains imp... |
052e6bff49a6-3 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html | name = "user_transaction_metrics",
features = [user_transaction_counts]
)
The above Feature Service is expected to be applied to a live workspace. For this example, we will be using the “prod” workspace.
import tecton
workspace = tecton.get_workspace("prod")
feature_service = workspace.get_feature_service("user_tra... |
052e6bff49a6-4 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html | kwargs["transaction_count_30d"] = feature_vector["user_transaction_counts.transaction_count_30d_1d"]
return prompt.format(**kwargs)
prompt_template = TectonPromptTemplate(input_variables=["user_id"])
print(prompt_template.format(user_id="user_469998441571"))
Given the vendor's up to date transaction stats, writ... |
052e6bff49a6-5 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html | Here we will set up a custom FeatureformPromptTemplate. This prompt template will take in the average amount a user pays per transactions.
Note that the input to this prompt template is just avg_transaction, since that is the only user defined piece (all other variables are looked up inside the prompt template).
from l... |
052e6bff49a6-6 | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html | © Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.