id stringlengths 14 16 | text stringlengths 29 2.73k | source stringlengths 49 115 |
|---|---|---|
d04b74d6fb51-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 |
d04b74d6fb51-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 |
d04b74d6fb51-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 |
d04b74d6fb51-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 |
d04b74d6fb51-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 |
d04b74d6fb51-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 |
d04b74d6fb51-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 |
d04b74d6fb51-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 |
d04b74d6fb51-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 |
d04b74d6fb51-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 |
d04b74d6fb51-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 |
d04b74d6fb51-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 |
d04b74d6fb51-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 |
d04b74d6fb51-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 |
d04b74d6fb51-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 |
f6eeb28299e2-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 |
dc9426ff804e-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 |
dc9426ff804e-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 |
dc9426ff804e-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 |
dc9426ff804e-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 |
ff41997a101e-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 |
31fff150ce99-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 |
c84832bd3861-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 |
c84832bd3861-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 |
c84832bd3861-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 |
c84832bd3861-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 |
304e21f517c2-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 |
304e21f517c2-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 |
8aac9e39d9a7-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 |
8aac9e39d9a7-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 |
e95f31c0cfa6-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 |
e95f31c0cfa6-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 |
3a26c33a6cb8-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 |
3a26c33a6cb8-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 |
3a26c33a6cb8-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 02, 2023. | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/length_based.html |
3a433e23c091-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 |
3a433e23c091-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 |
079c4f8c3b11-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 |
079c4f8c3b11-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 |
079c4f8c3b11-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 |
2a1ec8132a8e-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 |
2a1ec8132a8e-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 |
54ffb798db9b-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 |
a34ed0e1a97c-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 |
a34ed0e1a97c-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 |
a34ed0e1a97c-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 |
18997f7791df-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 |
18997f7791df-1 | ],
input_variables=["question"],
partial_variables={"format_instructions": format_instructions}
)
_input = prompt.format_prompt(question="what's the capital of france")
output = chat_model(_input.to_messages())
output_parser.parse(output.content)
{'answer': 'Paris', 'source': 'https://en.wikipedia.org/wiki/Pari... | https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/structured.html |
9ee42e59b0bf-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 |
2b08983d8f52-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 |
2b08983d8f52-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 |
2b08983d8f52-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 |
2b08983d8f52-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 |
2b08983d8f52-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\n",
)
# We can now generate a prompt using the `format` method.
print(few_shot_prompt.format(input="big"))
# -> Give the antonym of every input
# ->
# -> Wo... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html |
2b08983d8f52-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 |
2b08983d8f52-6 | 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.format(input=long_string))
# -> Give the antonym of every input
# -> Word: happy
# -> Antonym: sad
# ->
# -> Word: big and huge and massive and large and gigantic and ta... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html |
2b99ad28b27b-0 | .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
How to serialize prompts#
It is often preferrable to store prompts not as p... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html |
2b99ad28b27b-1 | prompt = load_prompt("simple_prompt.yaml")
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"],
... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html |
2b99ad28b27b-2 | output: sad
- input: tall
output: short
Loading from YAML#
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:
["i... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html |
2b99ad28b27b-3 | !cat few_shot_prompt.json
{
"_type": "few_shot",
"input_variables": ["adjective"],
"prefix": "Write antonyms for the following words.",
"example_prompt": {
"_type": "prompt",
"input_variables": ["input", "output"],
"template": "Input: {input}\nOutput: {output}"
},
"exampl... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html |
2b99ad28b27b-4 | Output: short
Input: funny
Output:
Example Prompt from a File#
This shows an example of loading the PromptTemplate that is used to format the examples from a separate file. Note that the key changes from example_prompt to example_prompt_path.
!cat example_prompt.json
{
"_type": "prompt",
"input_variables": ["in... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html |
3485a2ff58e6-0 | .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... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html |
3485a2ff58e6-1 | "answer":
"""
Are follow up questions needed here: Yes.
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
"""
},
... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html |
3485a2ff58e6-2 | print(example_prompt.format(**examples[0]))
Question: Who lived longer, Muhammad Ali or Alan Turing?
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 ... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html |
3485a2ff58e6-3 | Are follow up questions needed here: Yes.
Follow up: Who was the mother of George Washington?
Intermediate answer: The mother of George Washington was Mary Ball Washington.
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... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html |
3485a2ff58e6-4 | # This is the list of examples available to select from.
examples,
# This is the embedding class used to produce embeddings which are used to measure semantic similarity.
OpenAIEmbeddings(),
# This is the VectorStore class that is used to store the embeddings and do a similarity search over.
Chroma,... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html |
3485a2ff58e6-5 | suffix="Question: {input}",
input_variables=["input"]
)
print(prompt.format(input="Who was the father of Mary Ball Washington?"))
Question: Who was the maternal grandfather of George Washington?
Are follow up questions needed here: Yes.
Follow up: Who was the mother of George Washington?
Intermediate answer: The m... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html |
9c91d595996e-0 | .ipynb
.pdf
How to create a custom prompt template
Contents
Why are custom prompt templates needed?
Creating a Custom Prompt Template
Use the custom prompt template
How to create a custom prompt template#
Let’s suppose we want the LLM to generate English language explanations of a function given its name. To achieve ... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/custom_prompt_template.html |
9c91d595996e-1 | import inspect
def get_source_code(function_name):
# Get the source code of the function
return inspect.getsource(function_name)
Next, we’ll create a custom prompt template that takes in the function name as input, and formats the prompt template to provide the source code of the function.
from langchain.prompt... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/custom_prompt_template.html |
9c91d595996e-2 | prompt = fn_explainer.format(function_name=get_source_code)
print(prompt)
Given the function name and source code, generate an English language explanation of the function.
Function Name: get_source_code
Source Code:
def get_source_code(function_name):
# Get the source code of the fu... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/custom_prompt_template.html |
c2108b61632b-0 | .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
Connecting to a Feature Store#
Feature stores are a concept from traditional machine learning that make sure data fed into models is up-to-date and rele... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html |
c2108b61632b-1 | 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... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html |
c2108b61632b-2 | Here are the drivers stats:
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 ChatOpen... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html |
c2108b61632b-3 | user_transaction_metrics = FeatureService(
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_se... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html |
c2108b61632b-4 | 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... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html |
3912e98fae8c-0 | .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 ... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/partial.html |
3912e98fae8c-1 | print(prompt.format(bar="baz"))
foobaz
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 ha... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/partial.html |
3912e98fae8c-2 | Contents
Partial With Strings
Partial With Functions
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 02, 2023. | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/partial.html |
ee3ac3982958-0 | .rst
.pdf
Tools
Tools#
Note
Conceptual Guide
Tools are ways that an agent can use to interact with the outside world.
For an overview of what a tool is, how to use them, and a full list of examples, please see the getting started documentation
Getting Started
Next, we have some examples of customizing and generically w... | https://python.langchain.com/en/latest/modules/agents/tools.html |
93a37c5475e6-0 | .rst
.pdf
Agents
Agents#
Note
Conceptual Guide
In this part of the documentation we cover the different types of agents, disregarding which specific tools they are used with.
For a high level overview of the different types of agents, see the below documentation.
Agent Types
For documentation on how to create a custom ... | https://python.langchain.com/en/latest/modules/agents/agents.html |
7c32757e871e-0 | .ipynb
.pdf
Getting Started
Getting Started#
Agents use an LLM to determine which actions to take and in what order.
An action can either be using a tool and observing its output, or returning to the user.
When used correctly agents can be extremely powerful. The purpose of this notebook is to show you how to easily us... | https://python.langchain.com/en/latest/modules/agents/getting_started.html |
7c32757e871e-1 | agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
Now let’s test it out!
agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?")
> Entering new AgentExecutor chain...
I need to find out who Leo DiCaprio's girlfriend is and then calc... | https://python.langchain.com/en/latest/modules/agents/getting_started.html |
2fa46af0bc04-0 | .rst
.pdf
Agent Executors
Agent Executors#
Note
Conceptual Guide
Agent executors take an agent and tools and use the agent to decide which tools to call and in what order.
In this part of the documentation we cover other related functionality to agent executors
How to combine agents and vectorstores
How to use the asyn... | https://python.langchain.com/en/latest/modules/agents/agent_executors.html |
8935da72aedd-0 | .rst
.pdf
Toolkits
Toolkits#
Note
Conceptual Guide
This section of documentation covers agents with toolkits - eg an agent applied to a particular use case.
See below for a full list of agent toolkits
CSV Agent
Jira
JSON Agent
OpenAPI agents
Natural Language APIs
Pandas Dataframe Agent
PlayWright Browser Toolkit
PowerB... | https://python.langchain.com/en/latest/modules/agents/toolkits.html |
8a44e1bded58-0 | .ipynb
.pdf
Pandas Dataframe Agent
Pandas Dataframe Agent#
This notebook shows how to use agents to interact with a pandas dataframe. It is mostly optimized for question answering.
NOTE: this agent calls the Python agent under the hood, which executes LLM generated Python code - this can be bad if the LLM generated Pyt... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/pandas.html |
8a44e1bded58-1 | Action: python_repl_ast
Action Input: df['Age'].mean()
Observation: 29.69911764705882
Thought: I can now calculate the square root
Action: python_repl_ast
Action Input: math.sqrt(df['Age'].mean())
Observation: name 'math' is not defined
Thought: I need to import the math library
Action: python_repl_ast
Action Input: im... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/pandas.html |
739ea815c5c2-0 | .ipynb
.pdf
OpenAPI agents
Contents
1st example: hierarchical planning agent
To start, let’s collect some OpenAPI specs.
How big is this spec?
Let’s see some examples!
Try another API.
2nd example: “json explorer” agent
OpenAPI agents#
We can construct agents to consume arbitrary APIs, here APIs conformant to the Ope... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
739ea815c5c2-1 | !mv openapi.yaml spotify_openapi.yaml
--2023-03-31 15:45:56-- https://raw.githubusercontent.com/openai/openai-openapi/master/openapi.yaml
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.110.133, 185.199.109.133, 185.199.111.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercont... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
739ea815c5c2-2 | --2023-03-31 15:45:57-- https://raw.githubusercontent.com/APIs-guru/openapi-directory/main/APIs/spotify.com/1.0.0/openapi.yaml
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.110.133, 185.199.109.133, 185.199.111.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|18... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
739ea815c5c2-3 | You’ll have to set up an application in the Spotify developer console, documented here, to get credentials: CLIENT_ID, CLIENT_SECRET, and REDIRECT_URI.
To get an access tokens (and keep them fresh), you can implement the oauth flows, or you can use spotipy. If you’ve set your Spotify creedentials as environment variabl... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
739ea815c5c2-4 | from langchain.agents.agent_toolkits.openapi import planner
llm = OpenAI(model_name="gpt-4", temperature=0.0)
/Users/jeremywelborn/src/langchain/langchain/llms/openai.py:169: UserWarning: You are trying to use a chat model. This way of initializing it is no longer supported. Instead, please use: `from langchain.chat_mo... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
739ea815c5c2-5 | Thought:I have the plan, now I need to execute the API calls.
Action: api_controller
Action Input: 1. GET /search to search for the album "Kind of Blue"
2. GET /albums/{id}/tracks to get the tracks from the "Kind of Blue" album
3. GET /me to get the current user's information
4. POST /users/{user_id}/playlists to creat... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
739ea815c5c2-6 | Thought:Action: requests_post
Action Input: {"url": "https://api.spotify.com/v1/users/22rhrz4m4kvpxlsb5hezokzwi/playlists", "data": {"name": "Machine Blues"}, "output_instructions": "Extract the id of the created playlist"}
Observation: 7lzoEi44WOISnFYlrAIqyX
Thought:Action: requests_post
Action Input: {"url": "https:/... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
739ea815c5c2-7 | user_query = "give me a song I'd like, make it blues-ey"
spotify_agent.run(user_query)
> Entering new AgentExecutor chain...
Action: api_planner
Action Input: I need to find the right API calls to get a blues song recommendation for the user
Observation: 1. GET /me to get the current user's information
2. GET /recommen... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
739ea815c5c2-8 | Observation: acoustic, afrobeat, alt-rock, alternative, ambient, anime, black-metal, bluegrass, blues, bossanova, brazil, breakbeat, british, cantopop, chicago-house, children, chill, classical, club, comedy, country, dance, dancehall, death-metal, deep-house, detroit-techno, disco, disney, drum-and-bass, dub, dubstep,... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
739ea815c5c2-9 | Observation: [
{
id: '03lXHmokj9qsXspNsPoirR',
name: 'Get Away Jordan'
}
]
Thought:I am finished executing the plan.
Final Answer: The recommended blues song for user Jeremy Welborn (ID: 22rhrz4m4kvpxlsb5hezokzwi) is "Get Away Jordan" with the track ID: 03lXHmokj9qsXspNsPoirR.
> Finished chain.
Observation:... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
739ea815c5c2-10 | > Entering new AgentExecutor chain...
Action: api_planner
Action Input: I need to find the right API calls to generate a short piece of advice
Observation: 1. GET /engines to retrieve the list of available engines
2. POST /completions with the selected engine and a prompt for generating a short piece of advice
Thought:... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
739ea815c5c2-11 | Action: requests_post
Action Input: {"url": "https://api.openai.com/v1/completions", "data": {"engine": "davinci", "prompt": "Give me a short piece of advice on how to be more productive."}, "output_instructions": "Extract the text from the first choice"}
Observation: "you must provide a model parameter"
Thought:!! Cou... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
739ea815c5c2-12 | Observation: babbage, davinci, text-davinci-edit-001, babbage-code-search-code, text-similarity-babbage-001, code-davinci-edit-001, text-davinci-edit-001, ada
Thought:Action: requests_post
Action Input: {"url": "https://api.openai.com/v1/completions", "data": {"model": "davinci", "prompt": "Give me a short piece of adv... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
739ea815c5c2-13 | Action: api_controller
Action Input: 1. GET /models to retrieve the list of available models
2. Choose a suitable model for generating text (e.g., text-davinci-002)
3. POST /completions with the chosen model and a prompt related to improving communication skills to generate a short piece of advice
> Entering new AgentE... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.