.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 import PromptTemplate, ChatPromptTemplate, HumanMessagePromptTemplate
from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAI
from langchain.output_parsers import PydanticOutputParser, OutputFixingParser, RetryOutputParser
from pydantic import BaseModel, Field, validator
from typing import List
template = """Based on the user question, provide an Action and Action Input for what step should be taken.
{format_instructions}
Question: {query}
Response:"""
class Action(BaseModel):
    action: str = Field(description="action to take")
    action_input: str = Field(description="input to the action")

parser = PydanticOutputParser(pydantic_object=Action)
prompt = PromptTemplate(
    template="Answer the user query.\n{format_instructions}\n{query}\n",
    input_variables=["query"],
    partial_variables={"format_instructions": parser.get_format_instructions()}
)
prompt_value = prompt.format_prompt(query="who is leo di caprios gf?")
bad_response = '{"action": "search"}'
If we try to parse this response as is, we will get an error
parser.parse(bad_response)
---------------------------------------------------------------------------
ValidationError                           Traceback (most recent call last)
File ~/workplace/langchain/langchain/output_parsers/pydantic.py:24, in PydanticOutputParser.parse(self, text)
     23     json_object = json.loads(json_str)


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/versions/3.9.1/envs/langchain/lib/python3.9/site-packages/pydantic/main.py:342, in pydantic.main.BaseModel.__init__()
ValidationError: 1 validation error for Action
action_input
  field required (type=value_error.missing)
During handling of the above exception, another exception occurred:
OutputParserException                     Traceback (most recent call last)
Cell In[6], line 1
----> 1 parser.parse(bad_response)
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(msg)
OutputParserException: Failed to parse Action from completion {"action": "search"}. Got: 1 validation error for Action
action_input
  field required (type=value_error.missing)
If we try to use the OutputFixingParser to fix this error, it will be confused - namely, it doesn’t know what to actually put for action input.
fix_parser = OutputFixingParser.from_llm(parser=parser, llm=ChatOpenAI())
fix_parser.parse(bad_response)
Action(action='search', action_input='')


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.from_llm(parser=parser, llm=OpenAI(temperature=0))
retry_parser.parse_with_prompt(bad_response, prompt_value)
Action(action='search', action_input='who is leo di caprios gf?')
previous
PydanticOutputParser
next
Structured Output Parser
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.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, HumanMessagePromptTemplate
from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAI
Here we define the response schema we want to receive.
response_schemas = [
    ResponseSchema(name="answer", description="answer to the user's question"),
    ResponseSchema(name="source", description="source used to answer the user's question, should be a website.")
]
output_parser = StructuredOutputParser.from_response_schemas(response_schemas)
We now get a string that contains instructions for how the response should be formatted, and we then insert that into our prompt.
format_instructions = output_parser.get_format_instructions()
prompt = PromptTemplate(
    template="answer the users question as best as possible.\n{format_instructions}\n{question}",
    input_variables=["question"],
    partial_variables={"format_instructions": format_instructions}
)
We can now use this to format a prompt to send to the language model, and then parse the returned result.
model = OpenAI(temperature=0)
_input = prompt.format_prompt(question="what's the capital of france")
output = model(_input.to_string())
output_parser.parse(output)
{'answer': 'Paris', 'source': 'https://en.wikipedia.org/wiki/Paris'}
And here’s an example of using this in a chat model
chat_model = ChatOpenAI(temperature=0)
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(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/Paris'}
previous
RetryOutputParser
next
Indexes
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.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-formed JSON. In the OpenAI family, DaVinci can do reliably but Curie’s ability already drops off dramatically.
Use Pydantic to declare your data model. Pydantic’s BaseModel like a Python dataclass, but with actual type checking + coercion.
from langchain.prompts import PromptTemplate, ChatPromptTemplate, HumanMessagePromptTemplate
from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAI
from langchain.output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field, validator
from typing import List
model_name = 'text-davinci-003'
temperature = 0.0
model = OpenAI(model_name=model_name, temperature=temperature)
# Define your desired data structure.
class Joke(BaseModel):
    setup: str = Field(description="question to set up a joke")
    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
# And a query intented to prompt a language model to populate the data structure.
joke_query = "Tell me a joke."
# Set up a parser + inject instructions into the prompt template.
parser = PydanticOutputParser(pydantic_object=Joke)
prompt = PromptTemplate(


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(setup='Why did the chicken cross the road?', punchline='To get to the other side!')
# Here's another example, but with a compound typed field.
class Actor(BaseModel):
    name: str = Field(description="name of an actor")
    film_names: List[str] = Field(description="list of names of films they starred in")

actor_query = "Generate the filmography for a random actor."
parser = PydanticOutputParser(pydantic_object=Actor)
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=actor_query)
output = model(_input.to_string())
parser.parse(output)
Actor(name='Tom Hanks', film_names=['Forrest Gump', 'Saving Private Ryan', 'The Green Mile', 'Cast Away', 'Toy Story'])
previous
OutputFixingParser
next
RetryOutputParser
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.ipynb
.pdf
OutputFixingParser
OutputFixingParser#
This output parser wraps another output parser and tries to fix any mmistakes
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 misformatted output, along with the formatted instructions, to the model and ask it to fix it.
For this example, we’ll use the above OutputParser. Here’s what happens if we pass it a result that does not comply with the schema:
from langchain.prompts import PromptTemplate, ChatPromptTemplate, HumanMessagePromptTemplate
from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAI
from langchain.output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field, validator
from typing import List
class Actor(BaseModel):
    name: str = Field(description="name of an actor")
    film_names: List[str] = Field(description="list of names of films they starred in")

actor_query = "Generate the filmography for a random actor."
parser = PydanticOutputParser(pydantic_object=Actor)
misformatted = "{'name': 'Tom Hanks', 'film_names': ['Forrest Gump']}"
parser.parse(misformatted)
---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
File ~/workplace/langchain/langchain/output_parsers/pydantic.py:23, in PydanticOutputParser.parse(self, text)
     22     json_str = match.group()
---> 23 json_object = json.loads(json_str)
     24 return self.pydantic_object.parse_obj(json_object)


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 None and
    345         parse_constant is None and object_pairs_hook is None and not kw):
--> 346     return _default_decoder.decode(s)
    347 if cls is None:
File ~/.pyenv/versions/3.9.1/lib/python3.9/json/decoder.py:337, in JSONDecoder.decode(self, s, _w)
    333 """Return the Python representation of ``s`` (a ``str`` instance
    334 containing a JSON document).
    335
    336 """
--> 337 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    338 end = _w(s, end).end()
File ~/.pyenv/versions/3.9.1/lib/python3.9/json/decoder.py:353, in JSONDecoder.raw_decode(self, s, idx)
    352 try:
--> 353     obj, end = self.scan_once(s, idx)
    354 except StopIteration as err:
JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
During handling of the above exception, another exception occurred:
OutputParserException                     Traceback (most recent call last)
Cell In[6], line 1
----> 1 parser.parse(misformatted)


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(msg)
OutputParserException: Failed to parse Actor from completion {'name': 'Tom Hanks', 'film_names': ['Forrest Gump']}. Got: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
Now we can construct and use a OutputFixingParser. This output parser takes as an argument another output parser but also an LLM with which to try to correct any formatting mistakes.
from langchain.output_parsers import OutputFixingParser
new_parser = OutputFixingParser.from_llm(parser=parser, llm=ChatOpenAI())
new_parser.parse(misformatted)
Actor(name='Tom Hanks', film_names=['Forrest Gump'])
previous
CommaSeparatedListOutputParser
next
PydanticOutputParser
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.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 langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAI
output_parser = CommaSeparatedListOutputParser()
format_instructions = output_parser.get_format_instructions()
prompt = PromptTemplate(
    template="List five {subject}.\n{format_instructions}",
    input_variables=["subject"],
    partial_variables={"format_instructions": format_instructions}
)
model = OpenAI(temperature=0)
_input = prompt.format(subject="ice cream flavors")
output = model(_input)
output_parser.parse(output)
['Vanilla',
 'Chocolate',
 'Strawberry',
 'Mint Chocolate Chip',
 'Cookies and Cream']
previous
Output Parsers
next
OutputFixingParser
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.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 implement two methods:
An add_example method which takes in an example and adds it into the ExampleSelector
A select_examples method which takes in input variables (which are meant to be user input) and returns a list of examples to use in the few shot prompt.
Let’s implement a custom ExampleSelector that just selects two examples at random.
Note
Take a look at the current set of example selector implementations supported in LangChain here.
Implement custom example selector#
from langchain.prompts.example_selector.base import BaseExampleSelector
from typing import Dict, List
import numpy as np
class CustomExampleSelector(BaseExampleSelector):

    def __init__(self, examples: List[Dict[str, str]]):
        self.examples = examples

    def add_example(self, example: Dict[str, str]) -> None:
        """Add new example to store for a key."""
        self.examples.append(example)
    def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:
        """Select which examples to use based on the inputs."""
        return np.random.choice(self.examples, size=2, replace=False)
Use custom example selector#
examples = [
    {"foo": "1"},
    {"foo": "2"},
    {"foo": "3"}
]
# Initialize example selector.
example_selector = CustomExampleSelector(examples)
# Select examples
example_selector.select_examples({"foo": "foo"})
# -> array([{'foo': '2'}, {'foo': '3'}], dtype=object)


# 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
next
LengthBased ExampleSelector
 Contents

Implement custom example selector
Use custom example selector
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.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.example_selector import SemanticSimilarityExampleSelector
from langchain.vectorstores import Chroma
from langchain.embeddings import OpenAIEmbeddings
from langchain.prompts import FewShotPromptTemplate, PromptTemplate
example_prompt = PromptTemplate(
    input_variables=["input", "output"],
    template="Input: {input}\nOutput: {output}",
)
# These are a lot of examples of a pretend task of creating antonyms.
examples = [
    {"input": "happy", "output": "sad"},
    {"input": "tall", "output": "short"},
    {"input": "energetic", "output": "lethargic"},
    {"input": "sunny", "output": "gloomy"},
    {"input": "windy", "output": "calm"},
]
example_selector = SemanticSimilarityExampleSelector.from_examples(
    # 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,
    # This is the number of examples to produce.
    k=1
)
similar_prompt = FewShotPromptTemplate(
    # We provide an ExampleSelector instead of examples.
    example_selector=example_selector,
    example_prompt=example_prompt,
    prefix="Give the antonym of every input",


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
print(similar_prompt.format(adjective="worried"))
Give the antonym of every input
Input: happy
Output: sad
Input: worried
Output:
# Input is a measurement, so should select the tall/short example
print(similar_prompt.format(adjective="fat"))
Give the antonym of every input
Input: happy
Output: sad
Input: fat
Output:
# You can add new examples to the SemanticSimilarityExampleSelector as well
similar_prompt.example_selector.add_example({"input": "enthusiastic", "output": "apathetic"})
print(similar_prompt.format(adjective="joyful"))
Give the antonym of every input
Input: happy
Output: sad
Input: joyful
Output:
previous
NGram Overlap ExampleSelector
next
Output Parsers
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.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 threshold score to be set. Examples with an ngram overlap score less than or equal to the threshold are excluded. The threshold is set to -1.0, by default, so will not exclude any examples, only reorder them. Setting the threshold to 0.0 will exclude examples that have no ngram overlaps with the input.
from langchain.prompts import PromptTemplate
from langchain.prompts.example_selector.ngram_overlap import NGramOverlapExampleSelector
from langchain.prompts import FewShotPromptTemplate, PromptTemplate
example_prompt = PromptTemplate(
    input_variables=["input", "output"],
    template="Input: {input}\nOutput: {output}",
)
# These are a lot of examples of a pretend task of creating antonyms.
examples = [
    {"input": "happy", "output": "sad"},
    {"input": "tall", "output": "short"},
    {"input": "energetic", "output": "lethargic"},
    {"input": "sunny", "output": "gloomy"},
    {"input": "windy", "output": "calm"},
]
# These are examples of a fictional translation task.
examples = [
    {"input": "See Spot run.", "output": "Ver correr a Spot."},
    {"input": "My dog barks.", "output": "Mi perro ladra."},
    {"input": "Spot can run.", "output": "Spot puede correr."},


{"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,
    # This is the PromptTemplate being used to format the examples.
    example_prompt=example_prompt,
    # This is the threshold, at which selector stops.
    # It is set to -1.0 by default.
    threshold=-1.0,
    # For negative threshold:
    # Selector sorts examples by ngram overlap score, and excludes none.
    # For threshold greater than 1.0:
    # Selector excludes all examples, and returns an empty list.
    # For threshold equal to 0.0:
    # Selector sorts examples by ngram overlap score,
    # and excludes those with no ngram overlap with input.
)
dynamic_prompt = FewShotPromptTemplate(
    # We provide an ExampleSelector instead of examples.
    example_selector=example_selector,
    example_prompt=example_prompt,
    prefix="Give the Spanish translation of every input",
    suffix="Input: {sentence}\nOutput:",
    input_variables=["sentence"],
)
# An example input with large ngram overlap with "Spot can run."
# and no overlap with "My dog barks."
print(dynamic_prompt.format(sentence="Spot can run fast."))
Give the Spanish translation of every input
Input: Spot can run.
Output: Spot puede correr.
Input: See Spot run.
Output: Ver correr a Spot.
Input: My dog barks.


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(sentence="Spot can run fast."))
Give the Spanish translation of every input
Input: Spot can run.
Output: Spot puede correr.
Input: See Spot run.
Output: Ver correr a Spot.
Input: Spot plays fetch.
Output: Spot juega a buscar.
Input: My dog barks.
Output: Mi perro ladra.
Input: Spot can run fast.
Output:
# You can set a threshold at which examples are excluded.
# For example, setting threshold equal to 0.0
# excludes examples with no ngram overlaps with input.
# Since "My dog barks." has no ngram overlaps with "Spot can run fast."
# it is excluded.
example_selector.threshold=0.0
print(dynamic_prompt.format(sentence="Spot can run fast."))
Give the Spanish translation of every input
Input: Spot can run.
Output: Spot puede correr.
Input: See Spot run.
Output: Ver correr a Spot.
Input: Spot plays fetch.
Output: Spot juega a buscar.
Input: Spot can run fast.
Output:
# Setting small nonzero threshold
example_selector.threshold=0.09
print(dynamic_prompt.format(sentence="Spot can play fetch."))
Give the Spanish translation of every input
Input: Spot can run.
Output: Spot puede correr.
Input: Spot plays fetch.
Output: Spot juega a buscar.


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
Maximal Marginal Relevance ExampleSelector
next
Similarity ExampleSelector
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.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 for shorter inputs it will select more.
from langchain.prompts import PromptTemplate
from langchain.prompts import FewShotPromptTemplate
from langchain.prompts.example_selector import LengthBasedExampleSelector
# These are a lot of examples of a pretend task of creating antonyms.
examples = [
    {"input": "happy", "output": "sad"},
    {"input": "tall", "output": "short"},
    {"input": "energetic", "output": "lethargic"},
    {"input": "sunny", "output": "gloomy"},
    {"input": "windy", "output": "calm"},
]
example_prompt = PromptTemplate(
    input_variables=["input", "output"],
    template="Input: {input}\nOutput: {output}",
)
example_selector = LengthBasedExampleSelector(
    # These are the examples it has available to choose from.
    examples=examples,
    # This is the PromptTemplate being used to format the examples.
    example_prompt=example_prompt,
    # This is the maximum length that the formatted examples should be.
    # Length is measured by the get_text_length function below.
    max_length=25,
    # This is the function used to get the length of a string, which is used
    # to determine which examples to include. It is commented out because
    # it is provided as a default value if none is specified.


# 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,
    prefix="Give the antonym of every input",
    suffix="Input: {adjective}\nOutput:",
    input_variables=["adjective"],
)
# An example with small input, so it selects all examples.
print(dynamic_prompt.format(adjective="big"))
Give the antonym of every input
Input: happy
Output: sad
Input: tall
Output: short
Input: energetic
Output: lethargic
Input: sunny
Output: gloomy
Input: windy
Output: calm
Input: big
Output:
# An example with long input, so it selects only one example.
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(adjective=long_string))
Give the antonym of every input
Input: happy
Output: sad
Input: big and huge and massive and large and gigantic and tall and much much much much much bigger than everything else
Output:
# You can add an example to an example selector as well.
new_example = {"input": "big", "output": "small"}
dynamic_prompt.example_selector.add_example(new_example)
print(dynamic_prompt.format(adjective="enthusiastic"))
Give the antonym of every input
Input: happy
Output: sad
Input: tall
Output: short
Input: energetic
Output: lethargic
Input: sunny
Output: gloomy
Input: windy
Output: calm


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 Apr 06, 2023.


.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 embeddings that have the greatest cosine similarity with the inputs, and then iteratively adding them while penalizing them for closeness to already selected examples.
from langchain.prompts.example_selector import MaxMarginalRelevanceExampleSelector
from langchain.vectorstores import FAISS
from langchain.embeddings import OpenAIEmbeddings
from langchain.prompts import FewShotPromptTemplate, PromptTemplate
example_prompt = PromptTemplate(
    input_variables=["input", "output"],
    template="Input: {input}\nOutput: {output}",
)
# These are a lot of examples of a pretend task of creating antonyms.
examples = [
    {"input": "happy", "output": "sad"},
    {"input": "tall", "output": "short"},
    {"input": "energetic", "output": "lethargic"},
    {"input": "sunny", "output": "gloomy"},
    {"input": "windy", "output": "calm"},
]
example_selector = MaxMarginalRelevanceExampleSelector.from_examples(
    # 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.
    FAISS,
    # This is the number of examples to produce.
    k=2
)
mmr_prompt = FewShotPromptTemplate(


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, so should select the happy/sad example as the first one
print(mmr_prompt.format(adjective="worried"))
Give the antonym of every input
Input: happy
Output: sad
Input: windy
Output: calm
Input: worried
Output:
# Let's compare this to what we would just get if we went solely off of similarity
similar_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"],
)
similar_prompt.example_selector.k = 2
print(similar_prompt.format(adjective="worried"))
Give the antonym of every input
Input: happy
Output: sad
Input: windy
Output: calm
Input: worried
Output:
previous
LengthBased ExampleSelector
next
NGram Overlap ExampleSelector
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
GPT4All
 Contents
Installation and Setup
Usage
GPT4All
Model File
GPT4All#
This page covers how to use the GPT4All wrapper within LangChain.
It is broken into two parts: installation and setup, and then usage with an example.
Installation and Setup#
Install the Python package with pip install pyllamacpp
Download a GPT4All model and place it in your desired directory
Usage#
GPT4All#
To use the GPT4All wrapper, you need to provide the path to the pre-trained model file and the model’s configuration.
from langchain.llms import GPT4All
# Instantiate the model
model = GPT4All(model="./models/gpt4all-model.bin", n_ctx=512, n_threads=8)
# Generate text
response = model("Once upon a time, ")
You can also customize the generation parameters, such as n_predict, temp, top_p, top_k, and others.
Example:
model = GPT4All(model="./models/gpt4all-model.bin", n_predict=55, temp=0)
response = model("Once upon a time, ")
Model File#
You can find links to model file downloads at the GPT4all repository. They will need to be converted to ggml format to work, as specified in the pyllamacpp repository.
For a more detailed walkthrough of this, see this notebook
previous
GooseAI
next
Graphsignal
 Contents

Installation and Setup
Usage
GPT4All
Model File
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
Pinecone
 Contents
Installation and Setup
Wrappers
VectorStore
Pinecone#
This page covers how to use the Pinecone ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific Pinecone wrappers.
Installation and Setup#
Install the Python SDK with pip install pinecone-client
Wrappers#
VectorStore#
There exists a wrapper around Pinecone indexes, allowing you to use it as a vectorstore,
whether for semantic search or example selection.
To import this vectorstore:
from langchain.vectorstores import Pinecone
For a more detailed walkthrough of the Pinecone wrapper, see this notebook
previous
PGVector
next
PromptLayer
 Contents

Installation and Setup
Wrappers
VectorStore
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
Banana
 Contents
Installation and Setup
Define your Banana Template
Build the Banana app
Wrappers
LLM
Banana#
This page covers how to use the Banana ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific Banana wrappers.
Installation and Setup#
Install with pip install banana-dev
Get an Banana api key and set it as an environment variable (BANANA_API_KEY)
Define your Banana Template#
If you want to use an available language model template you can find one here.
This template uses the Palmyra-Base model by Writer.
You can check out an example Banana repository here.
Build the Banana app#
Banana Apps must include the “output” key in the return json.
There is a rigid response structure.
# Return the results as a dictionary
result = {'output': result}
An example inference function would be:
def inference(model_inputs:dict) -> dict:
    global model
    global tokenizer
    # Parse out your arguments
    prompt = model_inputs.get('prompt', None)
    if prompt == None:
        return {'message': "No prompt provided"}
    # Run the model
    input_ids = tokenizer.encode(prompt, return_tensors='pt').cuda()
    output = model.generate(
        input_ids,
        max_length=100,
        do_sample=True,
        top_k=50,
        top_p=0.95,
        num_return_sequences=1,
        temperature=0.9,
        early_stopping=True,
        no_repeat_ngram_size=3,
        num_beams=5,
        length_penalty=1.5,
        repetition_penalty=1.5,
        bad_words_ids=[[tokenizer.encode(' ', add_prefix_space=True)[0]]]
        )


bad_words_ids=[[tokenizer.encode(' ', add_prefix_space=True)[0]]]
        )
    result = tokenizer.decode(output[0], skip_special_tokens=True)
    # Return the results as a dictionary
    result = {'output': result}
    return result
You can find a full example of a Banana app here.
Wrappers#
LLM#
There exists an Banana LLM wrapper, which you can access with
from langchain.llms import Banana
You need to provide a model key located in the dashboard:
llm = Banana(model_key="YOUR_MODEL_KEY")
previous
AtlasDB
next
CerebriumAI
 Contents

Installation and Setup
Define your Banana Template
Build the Banana app
Wrappers
LLM
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
GooseAI
 Contents
Installation and Setup
Wrappers
LLM
GooseAI#
This page covers how to use the GooseAI ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific GooseAI wrappers.
Installation and Setup#
Install the Python SDK with pip install openai
Get your GooseAI api key from this link here.
Set the environment variable (GOOSEAI_API_KEY).
import os
os.environ["GOOSEAI_API_KEY"] = "YOUR_API_KEY"
Wrappers#
LLM#
There exists an GooseAI LLM wrapper, which you can access with:
from langchain.llms import GooseAI
previous
Google Serper Wrapper
next
GPT4All
 Contents

Installation and Setup
Wrappers
LLM
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
PGVector
 Contents
Installation
Setup
Wrappers
VectorStore
Usage
PGVector#
This page covers how to use the Postgres PGVector ecosystem within LangChain
It is broken into two parts: installation and setup, and then references to specific PGVector wrappers.
Installation#
Install the Python package with pip install pgvector
Setup#
The first step is to create a database with the pgvector extension installed.
Follow the steps at PGVector Installation Steps to install the database and the extension. The docker image is the easiest way to get started.
Wrappers#
VectorStore#
There exists a wrapper around Postgres vector databases, allowing you to use it as a vectorstore,
whether for semantic search or example selection.
To import this vectorstore:
from langchain.vectorstores.pgvector import PGVector
Usage#
For a more detailed walkthrough of the PGVector Wrapper, see this notebook
previous
Petals
next
Pinecone
 Contents

Installation
Setup
Wrappers
VectorStore
Usage
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
Modal
 Contents
Installation and Setup
Define your Modal Functions and Webhooks
Wrappers
LLM
Modal#
This page covers how to use the Modal ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific Modal wrappers.
Installation and Setup#
Install with pip install modal-client
Run modal token new
Define your Modal Functions and Webhooks#
You must include a prompt. There is a rigid response structure.
class Item(BaseModel):
    prompt: str
@stub.webhook(method="POST")
def my_webhook(item: Item):
    return {"prompt": my_function.call(item.prompt)}
An example with GPT2:
from pydantic import BaseModel
import modal
stub = modal.Stub("example-get-started")
volume = modal.SharedVolume().persist("gpt2_model_vol")
CACHE_PATH = "/root/model_cache"
@stub.function(
    gpu="any",
    image=modal.Image.debian_slim().pip_install(
        "tokenizers", "transformers", "torch", "accelerate"
    ),
    shared_volumes={CACHE_PATH: volume},
    retries=3,
)
def run_gpt2(text: str):
    from transformers import GPT2Tokenizer, GPT2LMHeadModel
    tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
    model = GPT2LMHeadModel.from_pretrained('gpt2')
    encoded_input = tokenizer(text, return_tensors='pt').input_ids
    output = model.generate(encoded_input, max_length=50, do_sample=True)
    return tokenizer.decode(output[0], skip_special_tokens=True)
class Item(BaseModel):
    prompt: str
@stub.webhook(method="POST")
def get_text(item: Item):


@stub.webhook(method="POST")
def get_text(item: Item):
    return {"prompt": run_gpt2.call(item.prompt)}
Wrappers#
LLM#
There exists an Modal LLM wrapper, which you can access with
from langchain.llms import Modal
previous
Milvus
next
NLPCloud
 Contents

Installation and Setup
Define your Modal Functions and Webhooks
Wrappers
LLM
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
StochasticAI
 Contents
Installation and Setup
Wrappers
LLM
StochasticAI#
This page covers how to use the StochasticAI ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific StochasticAI wrappers.
Installation and Setup#
Install with pip install stochasticx
Get an StochasticAI api key and set it as an environment variable (STOCHASTICAI_API_KEY)
Wrappers#
LLM#
There exists an StochasticAI LLM wrapper, which you can access with
from langchain.llms import StochasticAI
previous
SerpAPI
next
Unstructured
 Contents

Installation and Setup
Wrappers
LLM
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
Runhouse
 Contents
Installation and Setup
Self-hosted LLMs
Self-hosted Embeddings
Runhouse#
This page covers how to use the Runhouse ecosystem within LangChain.
It is broken into three parts: installation and setup, LLMs, and Embeddings.
Installation and Setup#
Install the Python SDK with pip install runhouse
If you’d like to use on-demand cluster, check your cloud credentials with sky check
Self-hosted LLMs#
For a basic self-hosted LLM, you can use the SelfHostedHuggingFaceLLM class. For more
custom LLMs, you can use the SelfHostedPipeline parent class.
from langchain.llms import SelfHostedPipeline, SelfHostedHuggingFaceLLM
For a more detailed walkthrough of the Self-hosted LLMs, see this notebook
Self-hosted Embeddings#
There are several ways to use self-hosted embeddings with LangChain via Runhouse.
For a basic self-hosted embedding from a Hugging Face Transformers model, you can use
the SelfHostedEmbedding class.
from langchain.llms import SelfHostedPipeline, SelfHostedHuggingFaceLLM
For a more detailed walkthrough of the Self-hosted Embeddings, see this notebook
previous
Replicate
next
RWKV-4
 Contents

Installation and Setup
Self-hosted LLMs
Self-hosted Embeddings
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
Apify
 Contents
Overview
Installation and Setup
Wrappers
Utility
Loader
Apify#
This page covers how to use Apify within LangChain.
Overview#
Apify is a cloud platform for web scraping and data extraction,
which provides an ecosystem of more than a thousand
ready-made apps called Actors for various scraping, crawling, and extraction use cases.
This integration enables you run Actors on the Apify platform and load their results into LangChain to feed your vector
indexes with documents and data from the web, e.g. to generate answers from websites with documentation,
blogs, or knowledge bases.
Installation and Setup#
Install the Apify API client for Python with pip install apify-client
Get your Apify API token and either set it as
an environment variable (APIFY_API_TOKEN) or pass it to the ApifyWrapper as apify_api_token in the constructor.
Wrappers#
Utility#
You can use the ApifyWrapper to run Actors on the Apify platform.
from langchain.utilities import ApifyWrapper
For a more detailed walkthrough of this wrapper, see this notebook.
Loader#
You can also use our ApifyDatasetLoader to get data from Apify dataset.
from langchain.document_loaders import ApifyDatasetLoader
For a more detailed walkthrough of this loader, see this notebook.
previous
Aim
next
AtlasDB
 Contents

Overview
Installation and Setup
Wrappers
Utility
Loader
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
SearxNG Search API
 Contents
Installation and Setup
Self Hosted Instance:
Wrappers
Utility
Tool
SearxNG Search API#
This page covers how to use the SearxNG search API within LangChain.
It is broken into two parts: installation and setup, and then references to the specific SearxNG API wrapper.
Installation and Setup#
While it is possible to utilize the wrapper in conjunction with  public searx
instances these instances frequently do not permit API
access (see note on output format below) and have limitations on the frequency
of requests. It is recommended to opt for a self-hosted instance instead.
Self Hosted Instance:#
See this page for installation instructions.
When you install SearxNG, the only active output format by default is the HTML format.
You need to activate the json format to use the API. This can be done by adding the following line to the settings.yml file:
search:
    formats:
        - html
        - json
You can make sure that the API is working by issuing a curl request to the API endpoint:
curl -kLX GET --data-urlencode q='langchain' -d format=json http://localhost:8888
This should return a JSON object with the results.
Wrappers#
Utility#
To use the wrapper we need to pass the host of the SearxNG instance to the wrapper with:
1. the named parameter searx_host when creating the instance.
2. exporting the environment variable SEARXNG_HOST.
You can use the wrapper to get results from a SearxNG instance.
from langchain.utilities import SearxSearchWrapper
s = SearxSearchWrapper(searx_host="http://localhost:8888")
s.run("what is a large language model?")


s.run("what is a large language model?")
Tool#
You can also load this wrapper as a Tool (to use with an Agent).
You can do this with:
from langchain.agents import load_tools
tools = load_tools(["searx-search"],
                    searx_host="http://localhost:8888",
                    engines=["github"])
Note that we could optionally pass custom engines to use.
If you want to obtain results with metadata as json you can use:
tools = load_tools(["searx-search-results-json"],
                    searx_host="http://localhost:8888",
                    num_results=5)
For more information on tools, see this page
previous
RWKV-4
next
SerpAPI
 Contents

Installation and Setup
Self Hosted Instance:
Wrappers
Utility
Tool
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
Milvus
 Contents
Installation and Setup
Wrappers
VectorStore
Milvus#
This page covers how to use the Milvus ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific Milvus wrappers.
Installation and Setup#
Install the Python SDK with pip install pymilvus
Wrappers#
VectorStore#
There exists a wrapper around Milvus indexes, allowing you to use it as a vectorstore,
whether for semantic search or example selection.
To import this vectorstore:
from langchain.vectorstores import Milvus
For a more detailed walkthrough of the Miluvs wrapper, see this notebook
previous
Llama.cpp
next
Modal
 Contents

Installation and Setup
Wrappers
VectorStore
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
Llama.cpp
 Contents
Installation and Setup
Wrappers
LLM
Embeddings
Llama.cpp#
This page covers how to use llama.cpp within LangChain.
It is broken into two parts: installation and setup, and then references to specific Llama-cpp wrappers.
Installation and Setup#
Install the Python package with pip install llama-cpp-python
Download one of the supported models and convert them to the llama.cpp format per the instructions
Wrappers#
LLM#
There exists a LlamaCpp LLM wrapper, which you can access with
from langchain.llms import LlamaCpp
For a more detailed walkthrough of this, see this notebook
Embeddings#
There exists a LlamaCpp Embeddings wrapper, which you can access with
from langchain.embeddings import LlamaCppEmbeddings
For a more detailed walkthrough of this, see this notebook
previous
Jina
next
Milvus
 Contents

Installation and Setup
Wrappers
LLM
Embeddings
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
Cohere
 Contents
Installation and Setup
Wrappers
LLM
Embeddings
Cohere#
This page covers how to use the Cohere ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific Cohere wrappers.
Installation and Setup#
Install the Python SDK with pip install cohere
Get an Cohere api key and set it as an environment variable (COHERE_API_KEY)
Wrappers#
LLM#
There exists an Cohere LLM wrapper, which you can access with
from langchain.llms import Cohere
Embeddings#
There exists an Cohere Embeddings wrapper, which you can access with
from langchain.embeddings import CohereEmbeddings
For a more detailed walkthrough of this, see this notebook
previous
ClearML Integration
next
DeepInfra
 Contents

Installation and Setup
Wrappers
LLM
Embeddings
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
Replicate
 Contents
Installation and Setup
Calling a model
Replicate#
This page covers how to run models on Replicate within LangChain.
Installation and Setup#
Create a Replicate account. Get your API key and set it as an environment variable (REPLICATE_API_TOKEN)
Install the Replicate python client with pip install replicate
Calling a model#
Find a model on the Replicate explore page, and then paste in the model name and version in this format: owner-name/model-name:version
For example, for this flan-t5 model, click on the API tab. The model name/version would be: daanelson/flan-t5:04e422a9b85baed86a4f24981d7f9953e20c5fd82f6103b74ebc431588e1cec8
Only the model param is required, but any other model parameters can also be passed in with the format input={model_param: value, ...}
For example, if we were running stable diffusion and wanted to change the image dimensions:
Replicate(model="stability-ai/stable-diffusion:db21e45d3f7023abc2a46ee38a23973f6dce16bb082a930b0c49861f96d1e5bf", input={'image_dimensions': '512x512'})
Note that only the first output of a model will be returned.
From here, we can initialize our model:
llm = Replicate(model="daanelson/flan-t5:04e422a9b85baed86a4f24981d7f9953e20c5fd82f6103b74ebc431588e1cec8")
And run it:
prompt = """
Answer the following yes/no question by reasoning step by step.


prompt = """
Answer the following yes/no question by reasoning step by step.
Can a dog drive a car?
"""
llm(prompt)
We can call any Replicate model (not just LLMs) using this syntax. For example, we can call Stable Diffusion:
text2image = Replicate(model="stability-ai/stable-diffusion:db21e45d3f7023abc2a46ee38a23973f6dce16bb082a930b0c49861f96d1e5bf",
                       input={'image_dimensions'='512x512'}
image_output = text2image("A cat riding a motorcycle by Picasso")
previous
Qdrant
next
Runhouse
 Contents

Installation and Setup
Calling a model
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
ForefrontAI
 Contents
Installation and Setup
Wrappers
LLM
ForefrontAI#
This page covers how to use the ForefrontAI ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific ForefrontAI wrappers.
Installation and Setup#
Get an ForefrontAI api key and set it as an environment variable (FOREFRONTAI_API_KEY)
Wrappers#
LLM#
There exists an ForefrontAI LLM wrapper, which you can access with
from langchain.llms import ForefrontAI
previous
Deep Lake
next
Google Search Wrapper
 Contents

Installation and Setup
Wrappers
LLM
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
Weaviate
 Contents
Installation and Setup
Wrappers
VectorStore
Weaviate#
This page covers how to use the Weaviate ecosystem within LangChain.
What is Weaviate?
Weaviate in a nutshell:
Weaviate is an open-source database of the type vector search engine.
Weaviate allows you to store JSON documents in a class property-like fashion while attaching machine learning vectors to these documents to represent them in vector space.
Weaviate can be used stand-alone (aka bring your vectors) or with a variety of modules that can do the vectorization for you and extend the core capabilities.
Weaviate has a GraphQL-API to access your data easily.
We aim to bring your vector search set up to production to query in mere milliseconds (check our open source benchmarks to see if Weaviate fits your use case).
Get to know Weaviate in the basics getting started guide in under five minutes.
Weaviate in detail:
Weaviate is a low-latency vector search engine with out-of-the-box support for different media types (text, images, etc.). It offers Semantic Search, Question-Answer Extraction, Classification, Customizable Models (PyTorch/TensorFlow/Keras), etc. Built from scratch in Go, Weaviate stores both objects and vectors, allowing for combining vector search with structured filtering and the fault tolerance of a cloud-native database. It is all accessible through GraphQL, REST, and various client-side programming languages.
Installation and Setup#
Install the Python SDK with pip install weaviate-client
Wrappers#
VectorStore#
There exists a wrapper around Weaviate indexes, allowing you to use it as a vectorstore,
whether for semantic search or example selection.
To import this vectorstore:
from langchain.vectorstores import Weaviate


To import this vectorstore:
from langchain.vectorstores import Weaviate
For a more detailed walkthrough of the Weaviate wrapper, see this notebook
previous
Weights & Biases
next
Wolfram Alpha Wrapper
 Contents

Installation and Setup
Wrappers
VectorStore
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
OpenSearch
 Contents
Installation and Setup
Wrappers
VectorStore
OpenSearch#
This page covers how to use the OpenSearch ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific OpenSearch wrappers.
Installation and Setup#
Install the Python package with pip install opensearch-py
Wrappers#
VectorStore#
There exists a wrapper around OpenSearch vector databases, allowing you to use it as a vectorstore
for semantic search using approximate vector search powered by lucene, nmslib and faiss engines
or using painless scripting and script scoring functions for bruteforce vector search.
To import this vectorstore:
from langchain.vectorstores import OpenSearchVectorSearch
For a more detailed walkthrough of the OpenSearch wrapper, see this notebook
previous
OpenAI
next
Petals
 Contents

Installation and Setup
Wrappers
VectorStore
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
PromptLayer
 Contents
Installation and Setup
Wrappers
LLM
PromptLayer#
This page covers how to use PromptLayer within LangChain.
It is broken into two parts: installation and setup, and then references to specific PromptLayer wrappers.
Installation and Setup#
If you want to work with PromptLayer:
Install the promptlayer python library pip install promptlayer
Create a PromptLayer account
Create an api token and set it as an environment variable (PROMPTLAYER_API_KEY)
Wrappers#
LLM#
There exists an PromptLayer OpenAI LLM wrapper, which you can access with
from langchain.llms import PromptLayerOpenAI
To tag your requests, use the argument pl_tags when instanializing the LLM
from langchain.llms import PromptLayerOpenAI
llm = PromptLayerOpenAI(pl_tags=["langchain-requests", "chatbot"])
To get the PromptLayer request id, use the argument return_pl_id when instanializing the LLM
from langchain.llms import PromptLayerOpenAI
llm = PromptLayerOpenAI(return_pl_id=True)
This will add the PromptLayer request ID in the generation_info field of the Generation returned when using .generate or .agenerate
For example:
llm_results = llm.generate(["hello world"])
for res in llm_results.generations:
    print("pl request id: ", res[0].generation_info["pl_request_id"])
You can use the PromptLayer request ID to add a prompt, score, or other metadata to your request. Read more about it here.
This LLM is identical to the OpenAI LLM, except that
all your requests will be logged to your PromptLayer account
you can add pl_tags when instantializing to tag your requests on PromptLayer


you can add pl_tags when instantializing to tag your requests on PromptLayer
you can add return_pl_id when instantializing to return a PromptLayer request id to use while tracking requests.
PromptLayer also provides native wrappers for PromptLayerChatOpenAI and PromptLayerOpenAIChat
previous
Pinecone
next
Qdrant
 Contents

Installation and Setup
Wrappers
LLM
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
AI21 Labs
 Contents
Installation and Setup
Wrappers
LLM
AI21 Labs#
This page covers how to use the AI21 ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific AI21 wrappers.
Installation and Setup#
Get an AI21 api key and set it as an environment variable (AI21_API_KEY)
Wrappers#
LLM#
There exists an AI21 LLM wrapper, which you can access with
from langchain.llms import AI21
previous
LangChain Ecosystem
next
Aim
 Contents

Installation and Setup
Wrappers
LLM
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
Hazy Research
 Contents
Installation and Setup
Wrappers
LLM
Hazy Research#
This page covers how to use the Hazy Research ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific Hazy Research wrappers.
Installation and Setup#
To use the manifest, install it with pip install manifest-ml
Wrappers#
LLM#
There exists an LLM wrapper around Hazy Research’s manifest library.
manifest is a python library which is itself a wrapper around many model providers, and adds in caching, history, and more.
To use this wrapper:
from langchain.llms.manifest import ManifestWrapper
previous
Graphsignal
next
Helicone
 Contents

Installation and Setup
Wrappers
LLM
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
DeepInfra
 Contents
Installation and Setup
Wrappers
LLM
DeepInfra#
This page covers how to use the DeepInfra ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific DeepInfra wrappers.
Installation and Setup#
Get your DeepInfra api key from this link here.
Get an DeepInfra api key and set it as an environment variable (DEEPINFRA_API_TOKEN)
Wrappers#
LLM#
There exists an DeepInfra LLM wrapper, which you can access with
from langchain.llms import DeepInfra
previous
Cohere
next
Deep Lake
 Contents

Installation and Setup
Wrappers
LLM
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
Qdrant
 Contents
Installation and Setup
Wrappers
VectorStore
Qdrant#
This page covers how to use the Qdrant ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific Qdrant wrappers.
Installation and Setup#
Install the Python SDK with pip install qdrant-client
Wrappers#
VectorStore#
There exists a wrapper around Qdrant indexes, allowing you to use it as a vectorstore,
whether for semantic search or example selection.
To import this vectorstore:
from langchain.vectorstores import Qdrant
For a more detailed walkthrough of the Qdrant wrapper, see this notebook
previous
PromptLayer
next
Replicate
 Contents

Installation and Setup
Wrappers
VectorStore
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
OpenAI
 Contents
Installation and Setup
Wrappers
LLM
Embeddings
Tokenizer
Moderation
OpenAI#
This page covers how to use the OpenAI ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific OpenAI wrappers.
Installation and Setup#
Install the Python SDK with pip install openai
Get an OpenAI api key and set it as an environment variable (OPENAI_API_KEY)
If you want to use OpenAI’s tokenizer (only available for Python 3.9+), install it with pip install tiktoken
Wrappers#
LLM#
There exists an OpenAI LLM wrapper, which you can access with
from langchain.llms import OpenAI
If you are using a model hosted on Azure, you should use different wrapper for that:
from langchain.llms import AzureOpenAI
For a more detailed walkthrough of the Azure wrapper, see this notebook
Embeddings#
There exists an OpenAI Embeddings wrapper, which you can access with
from langchain.embeddings import OpenAIEmbeddings
For a more detailed walkthrough of this, see this notebook
Tokenizer#
There are several places you can use the tiktoken tokenizer. By default, it is used to count tokens
for OpenAI LLMs.
You can also use it to count tokens when splitting documents with
from langchain.text_splitter import CharacterTextSplitter
CharacterTextSplitter.from_tiktoken_encoder(...)
For a more detailed walkthrough of this, see this notebook
Moderation#
You can also access the OpenAI content moderation endpoint with
from langchain.chains import OpenAIModerationChain
For a more detailed walkthrough of this, see this notebook
previous
NLPCloud
next
OpenSearch
 Contents

Installation and Setup
Wrappers
LLM
Embeddings
Tokenizer


Contents

Installation and Setup
Wrappers
LLM
Embeddings
Tokenizer
Moderation
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
Chroma
 Contents
Installation and Setup
Wrappers
VectorStore
Chroma#
This page covers how to use the Chroma ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific Chroma wrappers.
Installation and Setup#
Install the Python package with pip install chromadb
Wrappers#
VectorStore#
There exists a wrapper around Chroma vector databases, allowing you to use it as a vectorstore,
whether for semantic search or example selection.
To import this vectorstore:
from langchain.vectorstores import Chroma
For a more detailed walkthrough of the Chroma wrapper, see this notebook
previous
CerebriumAI
next
ClearML Integration
 Contents

Installation and Setup
Wrappers
VectorStore
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
AtlasDB
 Contents
Installation and Setup
Wrappers
VectorStore
AtlasDB#
This page covers how to use Nomic’s Atlas ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific Atlas wrappers.
Installation and Setup#
Install the Python package with pip install nomic
Nomic is also included in langchains poetry extras poetry install -E all
Wrappers#
VectorStore#
There exists a wrapper around the Atlas neural database, allowing you to use it as a vectorstore.
This vectorstore also gives you full access to the underlying AtlasProject object, which will allow you to use the full range of Atlas map interactions, such as bulk tagging and automatic topic modeling.
Please see the Atlas docs for more detailed information.
To import this vectorstore:
from langchain.vectorstores import AtlasDB
For a more detailed walkthrough of the AtlasDB wrapper, see this notebook
previous
Apify
next
Banana
 Contents

Installation and Setup
Wrappers
VectorStore
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
Graphsignal
 Contents
Installation and Setup
Tracing and Monitoring
Graphsignal#
This page covers how to use the Graphsignal ecosystem to trace and monitor LangChain.
Installation and Setup#
Install the Python library with pip install graphsignal
Create free Graphsignal account here
Get an API key and set it as an environment variable (GRAPHSIGNAL_API_KEY)
Tracing and Monitoring#
Graphsignal automatically instruments and starts tracing and monitoring chains. Traces, metrics and errors are then available in your Graphsignal dashboard. No prompts or other sensitive data are sent to Graphsignal cloud, only statistics and metadata.
Initialize the tracer by providing a deployment name:
import graphsignal
graphsignal.configure(deployment='my-langchain-app-prod')
In order to trace full runs and see a breakdown by chains and tools, you can wrap the calling routine or use a decorator:
with graphsignal.start_trace('my-chain'):
    chain.run("some initial text")
Optionally, enable profiling to record function-level statistics for each trace.
with graphsignal.start_trace(
        'my-chain', options=graphsignal.TraceOptions(enable_profiling=True)):
    chain.run("some initial text")
See the Quick Start guide for complete setup instructions.
previous
GPT4All
next
Hazy Research
 Contents

Installation and Setup
Tracing and Monitoring
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
NLPCloud
 Contents
Installation and Setup
Wrappers
LLM
NLPCloud#
This page covers how to use the NLPCloud ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific NLPCloud wrappers.
Installation and Setup#
Install the Python SDK with pip install nlpcloud
Get an NLPCloud api key and set it as an environment variable (NLPCLOUD_API_KEY)
Wrappers#
LLM#
There exists an NLPCloud LLM wrapper, which you can access with
from langchain.llms import NLPCloud
previous
Modal
next
OpenAI
 Contents

Installation and Setup
Wrappers
LLM
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
Google Search Wrapper
 Contents
Installation and Setup
Wrappers
Utility
Tool
Google Search Wrapper#
This page covers how to use the Google Search API within LangChain.
It is broken into two parts: installation and setup, and then references to the specific Google Search wrapper.
Installation and Setup#
Install requirements with pip install google-api-python-client
Set up a Custom Search Engine, following these instructions
Get an API Key and Custom Search Engine ID from the previous step, and set them as environment variables GOOGLE_API_KEY and GOOGLE_CSE_ID respectively
Wrappers#
Utility#
There exists a GoogleSearchAPIWrapper utility which wraps this API. To import this utility:
from langchain.utilities import GoogleSearchAPIWrapper
For a more detailed walkthrough of this wrapper, see this notebook.
Tool#
You can also easily load this wrapper as a Tool (to use with an Agent).
You can do this with:
from langchain.agents import load_tools
tools = load_tools(["google-search"])
For more information on this, see this page
previous
ForefrontAI
next
Google Serper Wrapper
 Contents

Installation and Setup
Wrappers
Utility
Tool
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.md
.pdf
Deep Lake
 Contents
Why Deep Lake?
More Resources
Installation and Setup
Wrappers
VectorStore
Deep Lake#
This page covers how to use the Deep Lake ecosystem within LangChain.
Why Deep Lake?#
More than just a (multi-modal) vector store. You can later use the dataset to fine-tune your own LLM models.
Not only stores embeddings, but also the original data with automatic version control.
Truly serverless. Doesn’t require another service and can be used with major cloud providers (AWS S3, GCS, etc.)
More Resources#
Ultimate Guide to LangChain & Deep Lake: Build ChatGPT to Answer Questions on Your Financial Data
Here is whitepaper and academic paper for Deep Lake
Here is a set of additional resources available for review: Deep Lake, Getting Started and Tutorials
Installation and Setup#
Install the Python package with pip install deeplake
Wrappers#
VectorStore#
There exists a wrapper around Deep Lake, a data lake for Deep Learning applications, allowing you to use it as a vector store (for now), whether for semantic search or example selection.
To import this vectorstore:
from langchain.vectorstores import DeepLake
For a more detailed walkthrough of the Deep Lake wrapper, see this notebook
previous
DeepInfra
next
ForefrontAI
 Contents

Why Deep Lake?
More Resources
Installation and Setup
Wrappers
VectorStore
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.ipynb
.pdf
ClearML Integration
 Contents
ClearML Integration
Getting API Credentials
Setting Up
Scenario 1: Just an LLM
Scenario 2: Creating a agent with tools
Tips and Next Steps
ClearML Integration#
In order to properly keep track of your langchain experiments and their results, you can enable the ClearML integration. ClearML is an experiment manager that neatly tracks and organizes all your experiment runs.
Getting API Credentials#
We’ll be using quite some APIs in this notebook, here is a list and where to get them:
ClearML: https://app.clear.ml/settings/workspace-configuration
OpenAI: https://platform.openai.com/account/api-keys
SerpAPI (google search): https://serpapi.com/dashboard
import os
os.environ["CLEARML_API_ACCESS_KEY"] = ""
os.environ["CLEARML_API_SECRET_KEY"] = ""
os.environ["OPENAI_API_KEY"] = ""
os.environ["SERPAPI_API_KEY"] = ""
Setting Up#
!pip install clearml
!pip install pandas
!pip install textstat
!pip install spacy
!python -m spacy download en_core_web_sm
from datetime import datetime
from langchain.callbacks import ClearMLCallbackHandler, StdOutCallbackHandler
from langchain.callbacks.base import CallbackManager
from langchain.llms import OpenAI
# Setup and use the ClearML Callback
clearml_callback = ClearMLCallbackHandler(
    task_type="inference",
    project_name="langchain_callback_demo",
    task_name="llm",
    tags=["test"],
    # Change the following parameters based on the amount of detail you want tracked
    visualize=True,
    complexity_metrics=True,
    stream_logs=True
)
manager = CallbackManager([StdOutCallbackHandler(), clearml_callback])
# Get the OpenAI model ready to go


# Get the OpenAI model ready to go
llm = OpenAI(temperature=0, callback_manager=manager, verbose=True)
The clearml callback is currently in beta and is subject to change based on updates to `langchain`. Please report any issues to https://github.com/allegroai/clearml/issues with the tag `langchain`.
Scenario 1: Just an LLM#
First, let’s just run a single LLM a few times and capture the resulting prompt-answer conversation in ClearML
# SCENARIO 1 - LLM
llm_result = llm.generate(["Tell me a joke", "Tell me a poem"] * 3)
# After every generation run, use flush to make sure all the metrics
# prompts and other output are properly saved separately
clearml_callback.flush_tracker(langchain_asset=llm, name="simple_sequential")
{'action': 'on_llm_start', 'name': 'OpenAI', 'step': 3, 'starts': 2, 'ends': 1, 'errors': 0, 'text_ctr': 0, 'chain_starts': 0, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 1, 'llm_streams': 0, 'tool_starts': 0, 'tool_ends': 0, 'agent_ends': 0, 'prompts': 'Tell me a joke'}


{'action': 'on_llm_start', 'name': 'OpenAI', 'step': 3, 'starts': 2, 'ends': 1, 'errors': 0, 'text_ctr': 0, 'chain_starts': 0, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 1, 'llm_streams': 0, 'tool_starts': 0, 'tool_ends': 0, 'agent_ends': 0, 'prompts': 'Tell me a poem'}
{'action': 'on_llm_start', 'name': 'OpenAI', 'step': 3, 'starts': 2, 'ends': 1, 'errors': 0, 'text_ctr': 0, 'chain_starts': 0, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 1, 'llm_streams': 0, 'tool_starts': 0, 'tool_ends': 0, 'agent_ends': 0, 'prompts': 'Tell me a joke'}
{'action': 'on_llm_start', 'name': 'OpenAI', 'step': 3, 'starts': 2, 'ends': 1, 'errors': 0, 'text_ctr': 0, 'chain_starts': 0, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 1, 'llm_streams': 0, 'tool_starts': 0, 'tool_ends': 0, 'agent_ends': 0, 'prompts': 'Tell me a poem'}


{'action': 'on_llm_start', 'name': 'OpenAI', 'step': 3, 'starts': 2, 'ends': 1, 'errors': 0, 'text_ctr': 0, 'chain_starts': 0, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 1, 'llm_streams': 0, 'tool_starts': 0, 'tool_ends': 0, 'agent_ends': 0, 'prompts': 'Tell me a joke'}
{'action': 'on_llm_start', 'name': 'OpenAI', 'step': 3, 'starts': 2, 'ends': 1, 'errors': 0, 'text_ctr': 0, 'chain_starts': 0, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 1, 'llm_streams': 0, 'tool_starts': 0, 'tool_ends': 0, 'agent_ends': 0, 'prompts': 'Tell me a poem'}


{'action': 'on_llm_end', 'token_usage_prompt_tokens': 24, 'token_usage_completion_tokens': 138, 'token_usage_total_tokens': 162, 'model_name': 'text-davinci-003', 'step': 4, 'starts': 2, 'ends': 2, 'errors': 0, 'text_ctr': 0, 'chain_starts': 0, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 2, 'llm_streams': 0, 'tool_starts': 0, 'tool_ends': 0, 'agent_ends': 0, 'text': '\n\nQ: What did the fish say when it hit the wall?\nA: Dam!', 'generation_info_finish_reason': 'stop', 'generation_info_logprobs': None, 'flesch_reading_ease': 109.04, 'flesch_kincaid_grade': 1.3, 'smog_index': 0.0, 'coleman_liau_index': -1.24, 'automated_readability_index': 0.3, 'dale_chall_readability_score': 5.5, 'difficult_words': 0, 'linsear_write_formula': 5.5, 'gunning_fog': 5.2, 'text_standard': '5th and 6th grade', 'fernandez_huerta': 133.58, 'szigriszt_pazos': 131.54, 'gutierrez_polini': 62.3, 'crawford': -0.2, 'gulpease_index': 79.8, 'osman': 116.91}


{'action': 'on_llm_end', 'token_usage_prompt_tokens': 24, 'token_usage_completion_tokens': 138, 'token_usage_total_tokens': 162, 'model_name': 'text-davinci-003', 'step': 4, 'starts': 2, 'ends': 2, 'errors': 0, 'text_ctr': 0, 'chain_starts': 0, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 2, 'llm_streams': 0, 'tool_starts': 0, 'tool_ends': 0, 'agent_ends': 0, 'text': '\n\nRoses are red,\nViolets are blue,\nSugar is sweet,\nAnd so are you.', 'generation_info_finish_reason': 'stop', 'generation_info_logprobs': None, 'flesch_reading_ease': 83.66, 'flesch_kincaid_grade': 4.8, 'smog_index': 0.0, 'coleman_liau_index': 3.23, 'automated_readability_index': 3.9, 'dale_chall_readability_score': 6.71, 'difficult_words': 2, 'linsear_write_formula': 6.5, 'gunning_fog': 8.28, 'text_standard': '6th and 7th grade', 'fernandez_huerta': 115.58, 'szigriszt_pazos': 112.37, 'gutierrez_polini': 54.83, 'crawford': 1.4, 'gulpease_index': 72.1, 'osman': 100.17}


{'action': 'on_llm_end', 'token_usage_prompt_tokens': 24, 'token_usage_completion_tokens': 138, 'token_usage_total_tokens': 162, 'model_name': 'text-davinci-003', 'step': 4, 'starts': 2, 'ends': 2, 'errors': 0, 'text_ctr': 0, 'chain_starts': 0, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 2, 'llm_streams': 0, 'tool_starts': 0, 'tool_ends': 0, 'agent_ends': 0, 'text': '\n\nRoses are red,\nViolets are blue,\nSugar is sweet,\nAnd so are you.', 'generation_info_finish_reason': 'stop', 'generation_info_logprobs': None, 'flesch_reading_ease': 83.66, 'flesch_kincaid_grade': 4.8, 'smog_index': 0.0, 'coleman_liau_index': 3.23, 'automated_readability_index': 3.9, 'dale_chall_readability_score': 6.71, 'difficult_words': 2, 'linsear_write_formula': 6.5, 'gunning_fog': 8.28, 'text_standard': '6th and 7th grade', 'fernandez_huerta': 115.58, 'szigriszt_pazos': 112.37, 'gutierrez_polini': 54.83, 'crawford': 1.4, 'gulpease_index': 72.1, 'osman': 100.17}
{'action_records':           action    name  step  starts  ends  errors  text_ctr  chain_starts  \


0   on_llm_start  OpenAI     1       1     0       0         0             0
1   on_llm_start  OpenAI     1       1     0       0         0             0
2   on_llm_start  OpenAI     1       1     0       0         0             0
3   on_llm_start  OpenAI     1       1     0       0         0             0
4   on_llm_start  OpenAI     1       1     0       0         0             0
5   on_llm_start  OpenAI     1       1     0       0         0             0
6     on_llm_end     NaN     2       1     1       0         0             0
7     on_llm_end     NaN     2       1     1       0         0             0
8     on_llm_end     NaN     2       1     1       0         0             0
9     on_llm_end     NaN     2       1     1       0         0             0
10    on_llm_end     NaN     2       1     1       0         0             0
11    on_llm_end     NaN     2       1     1       0         0             0
12  on_llm_start  OpenAI     3       2     1       0         0             0
13  on_llm_start  OpenAI     3       2     1       0         0             0


14  on_llm_start  OpenAI     3       2     1       0         0             0
15  on_llm_start  OpenAI     3       2     1       0         0             0
16  on_llm_start  OpenAI     3       2     1       0         0             0
17  on_llm_start  OpenAI     3       2     1       0         0             0
18    on_llm_end     NaN     4       2     2       0         0             0
19    on_llm_end     NaN     4       2     2       0         0             0
20    on_llm_end     NaN     4       2     2       0         0             0
21    on_llm_end     NaN     4       2     2       0         0             0
22    on_llm_end     NaN     4       2     2       0         0             0
23    on_llm_end     NaN     4       2     2       0         0             0
    chain_ends  llm_starts  ...  difficult_words  linsear_write_formula  \
0            0           1  ...              NaN                    NaN
1            0           1  ...              NaN                    NaN
2            0           1  ...              NaN                    NaN
3            0           1  ...              NaN                    NaN
4            0           1  ...              NaN                    NaN
5            0           1  ...              NaN                    NaN


5            0           1  ...              NaN                    NaN
6            0           1  ...              0.0                    5.5
7            0           1  ...              2.0                    6.5
8            0           1  ...              0.0                    5.5
9            0           1  ...              2.0                    6.5
10           0           1  ...              0.0                    5.5
11           0           1  ...              2.0                    6.5
12           0           2  ...              NaN                    NaN
13           0           2  ...              NaN                    NaN
14           0           2  ...              NaN                    NaN
15           0           2  ...              NaN                    NaN
16           0           2  ...              NaN                    NaN
17           0           2  ...              NaN                    NaN
18           0           2  ...              0.0                    5.5
19           0           2  ...              2.0                    6.5
20           0           2  ...              0.0                    5.5
21           0           2  ...              2.0                    6.5
22           0           2  ...              0.0                    5.5
23           0           2  ...              2.0                    6.5
    gunning_fog      text_standard  fernandez_huerta szigriszt_pazos  \
0           NaN                NaN               NaN             NaN


0           NaN                NaN               NaN             NaN
1           NaN                NaN               NaN             NaN
2           NaN                NaN               NaN             NaN
3           NaN                NaN               NaN             NaN
4           NaN                NaN               NaN             NaN
5           NaN                NaN               NaN             NaN
6          5.20  5th and 6th grade            133.58          131.54
7          8.28  6th and 7th grade            115.58          112.37
8          5.20  5th and 6th grade            133.58          131.54
9          8.28  6th and 7th grade            115.58          112.37
10         5.20  5th and 6th grade            133.58          131.54
11         8.28  6th and 7th grade            115.58          112.37
12          NaN                NaN               NaN             NaN
13          NaN                NaN               NaN             NaN
14          NaN                NaN               NaN             NaN
15          NaN                NaN               NaN             NaN
16          NaN                NaN               NaN             NaN
17          NaN                NaN               NaN             NaN
18         5.20  5th and 6th grade            133.58          131.54
19         8.28  6th and 7th grade            115.58          112.37
20         5.20  5th and 6th grade            133.58          131.54


21         8.28  6th and 7th grade            115.58          112.37
22         5.20  5th and 6th grade            133.58          131.54
23         8.28  6th and 7th grade            115.58          112.37
    gutierrez_polini  crawford  gulpease_index   osman
0                NaN       NaN             NaN     NaN
1                NaN       NaN             NaN     NaN
2                NaN       NaN             NaN     NaN
3                NaN       NaN             NaN     NaN
4                NaN       NaN             NaN     NaN
5                NaN       NaN             NaN     NaN
6              62.30      -0.2            79.8  116.91
7              54.83       1.4            72.1  100.17
8              62.30      -0.2            79.8  116.91
9              54.83       1.4            72.1  100.17
10             62.30      -0.2            79.8  116.91
11             54.83       1.4            72.1  100.17
12               NaN       NaN             NaN     NaN
13               NaN       NaN             NaN     NaN
14               NaN       NaN             NaN     NaN
15               NaN       NaN             NaN     NaN
16               NaN       NaN             NaN     NaN
17               NaN       NaN             NaN     NaN
18             62.30      -0.2            79.8  116.91


19             54.83       1.4            72.1  100.17
20             62.30      -0.2            79.8  116.91
21             54.83       1.4            72.1  100.17
22             62.30      -0.2            79.8  116.91
23             54.83       1.4            72.1  100.17
[24 rows x 39 columns], 'session_analysis':     prompt_step         prompts    name  output_step  \
0             1  Tell me a joke  OpenAI            2
1             1  Tell me a poem  OpenAI            2
2             1  Tell me a joke  OpenAI            2
3             1  Tell me a poem  OpenAI            2
4             1  Tell me a joke  OpenAI            2
5             1  Tell me a poem  OpenAI            2
6             3  Tell me a joke  OpenAI            4
7             3  Tell me a poem  OpenAI            4
8             3  Tell me a joke  OpenAI            4
9             3  Tell me a poem  OpenAI            4
10            3  Tell me a joke  OpenAI            4
11            3  Tell me a poem  OpenAI            4
                                               output  \
0   \n\nQ: What did the fish say when it hit the w...
1   \n\nRoses are red,\nViolets are blue,\nSugar i...


2   \n\nQ: What did the fish say when it hit the w...
3   \n\nRoses are red,\nViolets are blue,\nSugar i...
4   \n\nQ: What did the fish say when it hit the w...
5   \n\nRoses are red,\nViolets are blue,\nSugar i...
6   \n\nQ: What did the fish say when it hit the w...
7   \n\nRoses are red,\nViolets are blue,\nSugar i...
8   \n\nQ: What did the fish say when it hit the w...
9   \n\nRoses are red,\nViolets are blue,\nSugar i...
10  \n\nQ: What did the fish say when it hit the w...
11  \n\nRoses are red,\nViolets are blue,\nSugar i...
    token_usage_total_tokens  token_usage_prompt_tokens  \
0                        162                         24
1                        162                         24
2                        162                         24
3                        162                         24
4                        162                         24
5                        162                         24
6                        162                         24
7                        162                         24
8                        162                         24
9                        162                         24
10                       162                         24
11                       162                         24
    token_usage_completion_tokens  flesch_reading_ease  flesch_kincaid_grade  \
0                             138               109.04                   1.3
1                             138                83.66                   4.8


1                             138                83.66                   4.8
2                             138               109.04                   1.3
3                             138                83.66                   4.8
4                             138               109.04                   1.3
5                             138                83.66                   4.8
6                             138               109.04                   1.3
7                             138                83.66                   4.8
8                             138               109.04                   1.3
9                             138                83.66                   4.8
10                            138               109.04                   1.3
11                            138                83.66                   4.8
    ...  difficult_words  linsear_write_formula  gunning_fog  \
0   ...                0                    5.5         5.20
1   ...                2                    6.5         8.28
2   ...                0                    5.5         5.20
3   ...                2                    6.5         8.28
4   ...                0                    5.5         5.20
5   ...                2                    6.5         8.28
6   ...                0                    5.5         5.20
7   ...                2                    6.5         8.28
8   ...                0                    5.5         5.20
9   ...                2                    6.5         8.28
10  ...                0                    5.5         5.20


10  ...                0                    5.5         5.20
11  ...                2                    6.5         8.28
        text_standard  fernandez_huerta  szigriszt_pazos  gutierrez_polini  \
0   5th and 6th grade            133.58           131.54             62.30
1   6th and 7th grade            115.58           112.37             54.83
2   5th and 6th grade            133.58           131.54             62.30
3   6th and 7th grade            115.58           112.37             54.83
4   5th and 6th grade            133.58           131.54             62.30
5   6th and 7th grade            115.58           112.37             54.83
6   5th and 6th grade            133.58           131.54             62.30
7   6th and 7th grade            115.58           112.37             54.83
8   5th and 6th grade            133.58           131.54             62.30
9   6th and 7th grade            115.58           112.37             54.83
10  5th and 6th grade            133.58           131.54             62.30
11  6th and 7th grade            115.58           112.37             54.83
   crawford  gulpease_index   osman


crawford  gulpease_index   osman
0      -0.2            79.8  116.91
1       1.4            72.1  100.17
2      -0.2            79.8  116.91
3       1.4            72.1  100.17
4      -0.2            79.8  116.91
5       1.4            72.1  100.17
6      -0.2            79.8  116.91
7       1.4            72.1  100.17
8      -0.2            79.8  116.91
9       1.4            72.1  100.17
10     -0.2            79.8  116.91
11      1.4            72.1  100.17
[12 rows x 24 columns]}
2023-03-29 14:00:25,948 - clearml.Task - INFO - Completed model upload to https://files.clear.ml/langchain_callback_demo/llm.988bd727b0e94a29a3ac0ee526813545/models/simple_sequential
At this point you can already go to https://app.clear.ml and take a look at the resulting ClearML Task that was created.
Among others, you should see that this notebook is saved along with any git information. The model JSON that contains the used parameters is saved as an artifact, there are also console logs and under the plots section, you’ll find tables that represent the flow of the chain.
Finally, if you enabled visualizations, these are stored as HTML files under debug samples.


Finally, if you enabled visualizations, these are stored as HTML files under debug samples.
Scenario 2: Creating a agent with tools#
To show a more advanced workflow, let’s create an agent with access to tools. The way ClearML tracks the results is not different though, only the table will look slightly different as there are other types of actions taken when compared to the earlier, simpler example.
You can now also see the use of the finish=True keyword, which will fully close the ClearML Task, instead of just resetting the parameters and prompts for a new conversation.
from langchain.agents import initialize_agent, load_tools
from langchain.agents import AgentType
# SCENARIO 2 - Agent with Tools
tools = load_tools(["serpapi", "llm-math"], llm=llm, callback_manager=manager)
agent = initialize_agent(
    tools,
    llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    callback_manager=manager,
    verbose=True,
)
agent.run(
    "Who is the wife of the person who sang summer of 69?"
)
clearml_callback.flush_tracker(langchain_asset=agent, name="Agent with Tools", finish=True)
> Entering new AgentExecutor chain...
{'action': 'on_chain_start', 'name': 'AgentExecutor', 'step': 1, 'starts': 1, 'ends': 0, 'errors': 0, 'text_ctr': 0, 'chain_starts': 1, 'chain_ends': 0, 'llm_starts': 0, 'llm_ends': 0, 'llm_streams': 0, 'tool_starts': 0, 'tool_ends': 0, 'agent_ends': 0, 'input': 'Who is the wife of the person who sang summer of 69?'}


{'action': 'on_llm_start', 'name': 'OpenAI', 'step': 2, 'starts': 2, 'ends': 0, 'errors': 0, 'text_ctr': 0, 'chain_starts': 1, 'chain_ends': 0, 'llm_starts': 1, 'llm_ends': 0, 'llm_streams': 0, 'tool_starts': 0, 'tool_ends': 0, 'agent_ends': 0, 'prompts': 'Answer the following questions as best you can. You have access to the following tools:\n\nSearch: A search engine. Useful for when you need to answer questions about current events. Input should be a search query.\nCalculator: Useful for when you need to answer questions about math.\n\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [Search, Calculator]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nBegin!\n\nQuestion: Who is the wife of the person who sang summer of 69?\nThought:'}


{'action': 'on_llm_end', 'token_usage_prompt_tokens': 189, 'token_usage_completion_tokens': 34, 'token_usage_total_tokens': 223, 'model_name': 'text-davinci-003', 'step': 3, 'starts': 2, 'ends': 1, 'errors': 0, 'text_ctr': 0, 'chain_starts': 1, 'chain_ends': 0, 'llm_starts': 1, 'llm_ends': 1, 'llm_streams': 0, 'tool_starts': 0, 'tool_ends': 0, 'agent_ends': 0, 'text': ' I need to find out who sang summer of 69 and then find out who their wife is.\nAction: Search\nAction Input: "Who sang summer of 69"', 'generation_info_finish_reason': 'stop', 'generation_info_logprobs': None, 'flesch_reading_ease': 91.61, 'flesch_kincaid_grade': 3.8, 'smog_index': 0.0, 'coleman_liau_index': 3.41, 'automated_readability_index': 3.5, 'dale_chall_readability_score': 6.06, 'difficult_words': 2, 'linsear_write_formula': 5.75, 'gunning_fog': 5.4, 'text_standard': '3rd and 4th grade', 'fernandez_huerta': 121.07, 'szigriszt_pazos': 119.5, 'gutierrez_polini': 54.91, 'crawford': 0.9, 'gulpease_index': 72.7, 'osman': 92.16}


I need to find out who sang summer of 69 and then find out who their wife is.
Action: Search
Action Input: "Who sang summer of 69"{'action': 'on_agent_action', 'tool': 'Search', 'tool_input': 'Who sang summer of 69', 'log': ' I need to find out who sang summer of 69 and then find out who their wife is.\nAction: Search\nAction Input: "Who sang summer of 69"', 'step': 4, 'starts': 3, 'ends': 1, 'errors': 0, 'text_ctr': 0, 'chain_starts': 1, 'chain_ends': 0, 'llm_starts': 1, 'llm_ends': 1, 'llm_streams': 0, 'tool_starts': 1, 'tool_ends': 0, 'agent_ends': 0}
{'action': 'on_tool_start', 'input_str': 'Who sang summer of 69', 'name': 'Search', 'description': 'A search engine. Useful for when you need to answer questions about current events. Input should be a search query.', 'step': 5, 'starts': 4, 'ends': 1, 'errors': 0, 'text_ctr': 0, 'chain_starts': 1, 'chain_ends': 0, 'llm_starts': 1, 'llm_ends': 1, 'llm_streams': 0, 'tool_starts': 2, 'tool_ends': 0, 'agent_ends': 0}
Observation: Bryan Adams - Summer Of 69 (Official Music Video).


Observation: Bryan Adams - Summer Of 69 (Official Music Video).
Thought:{'action': 'on_tool_end', 'output': 'Bryan Adams - Summer Of 69 (Official Music Video).', 'step': 6, 'starts': 4, 'ends': 2, 'errors': 0, 'text_ctr': 0, 'chain_starts': 1, 'chain_ends': 0, 'llm_starts': 1, 'llm_ends': 1, 'llm_streams': 0, 'tool_starts': 2, 'tool_ends': 1, 'agent_ends': 0}


{'action': 'on_llm_start', 'name': 'OpenAI', 'step': 7, 'starts': 5, 'ends': 2, 'errors': 0, 'text_ctr': 0, 'chain_starts': 1, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 1, 'llm_streams': 0, 'tool_starts': 2, 'tool_ends': 1, 'agent_ends': 0, 'prompts': 'Answer the following questions as best you can. You have access to the following tools:\n\nSearch: A search engine. Useful for when you need to answer questions about current events. Input should be a search query.\nCalculator: Useful for when you need to answer questions about math.\n\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [Search, Calculator]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nBegin!\n\nQuestion: Who is the wife of the person who sang summer of 69?\nThought: I need to find out who sang summer of 69 and then find out who their wife is.\nAction: Search\nAction Input: "Who sang summer of 69"\nObservation: Bryan Adams - Summer Of 69 (Official Music Video).\nThought:'}


{'action': 'on_llm_end', 'token_usage_prompt_tokens': 242, 'token_usage_completion_tokens': 28, 'token_usage_total_tokens': 270, 'model_name': 'text-davinci-003', 'step': 8, 'starts': 5, 'ends': 3, 'errors': 0, 'text_ctr': 0, 'chain_starts': 1, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 2, 'llm_streams': 0, 'tool_starts': 2, 'tool_ends': 1, 'agent_ends': 0, 'text': ' I need to find out who Bryan Adams is married to.\nAction: Search\nAction Input: "Who is Bryan Adams married to"', 'generation_info_finish_reason': 'stop', 'generation_info_logprobs': None, 'flesch_reading_ease': 94.66, 'flesch_kincaid_grade': 2.7, 'smog_index': 0.0, 'coleman_liau_index': 4.73, 'automated_readability_index': 4.0, 'dale_chall_readability_score': 7.16, 'difficult_words': 2, 'linsear_write_formula': 4.25, 'gunning_fog': 4.2, 'text_standard': '4th and 5th grade', 'fernandez_huerta': 124.13, 'szigriszt_pazos': 119.2, 'gutierrez_polini': 52.26, 'crawford': 0.7, 'gulpease_index': 74.7, 'osman': 84.2}
 I need to find out who Bryan Adams is married to.
Action: Search


I need to find out who Bryan Adams is married to.
Action: Search
Action Input: "Who is Bryan Adams married to"{'action': 'on_agent_action', 'tool': 'Search', 'tool_input': 'Who is Bryan Adams married to', 'log': ' I need to find out who Bryan Adams is married to.\nAction: Search\nAction Input: "Who is Bryan Adams married to"', 'step': 9, 'starts': 6, 'ends': 3, 'errors': 0, 'text_ctr': 0, 'chain_starts': 1, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 2, 'llm_streams': 0, 'tool_starts': 3, 'tool_ends': 1, 'agent_ends': 0}
{'action': 'on_tool_start', 'input_str': 'Who is Bryan Adams married to', 'name': 'Search', 'description': 'A search engine. Useful for when you need to answer questions about current events. Input should be a search query.', 'step': 10, 'starts': 7, 'ends': 3, 'errors': 0, 'text_ctr': 0, 'chain_starts': 1, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 2, 'llm_streams': 0, 'tool_starts': 4, 'tool_ends': 1, 'agent_ends': 0}
Observation: Bryan Adams has never married. In the 1990s, he was in a relationship with Danish model Cecilie Thomsen. In 2011, Bryan and Alicia Grimaldi, his ...


Thought:{'action': 'on_tool_end', 'output': 'Bryan Adams has never married. In the 1990s, he was in a relationship with Danish model Cecilie Thomsen. In 2011, Bryan and Alicia Grimaldi, his ...', 'step': 11, 'starts': 7, 'ends': 4, 'errors': 0, 'text_ctr': 0, 'chain_starts': 1, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 2, 'llm_streams': 0, 'tool_starts': 4, 'tool_ends': 2, 'agent_ends': 0}


{'action': 'on_llm_start', 'name': 'OpenAI', 'step': 12, 'starts': 8, 'ends': 4, 'errors': 0, 'text_ctr': 0, 'chain_starts': 1, 'chain_ends': 0, 'llm_starts': 3, 'llm_ends': 2, 'llm_streams': 0, 'tool_starts': 4, 'tool_ends': 2, 'agent_ends': 0, 'prompts': 'Answer the following questions as best you can. You have access to the following tools:\n\nSearch: A search engine. Useful for when you need to answer questions about current events. Input should be a search query.\nCalculator: Useful for when you need to answer questions about math.\n\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [Search, Calculator]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nBegin!\n\nQuestion: Who


to the original input question\n\nBegin!\n\nQuestion: Who is the wife of the person who sang summer of 69?\nThought: I need to find out who sang summer of 69 and then find out who their wife is.\nAction: Search\nAction Input: "Who sang summer of 69"\nObservation: Bryan Adams - Summer Of 69 (Official Music Video).\nThought: I need to find out who Bryan Adams is married to.\nAction: Search\nAction Input: "Who is Bryan Adams married to"\nObservation: Bryan Adams has never married. In the 1990s, he was in a relationship with Danish model Cecilie Thomsen. In 2011, Bryan and Alicia Grimaldi, his ...\nThought:'}


{'action': 'on_llm_end', 'token_usage_prompt_tokens': 314, 'token_usage_completion_tokens': 18, 'token_usage_total_tokens': 332, 'model_name': 'text-davinci-003', 'step': 13, 'starts': 8, 'ends': 5, 'errors': 0, 'text_ctr': 0, 'chain_starts': 1, 'chain_ends': 0, 'llm_starts': 3, 'llm_ends': 3, 'llm_streams': 0, 'tool_starts': 4, 'tool_ends': 2, 'agent_ends': 0, 'text': ' I now know the final answer.\nFinal Answer: Bryan Adams has never been married.', 'generation_info_finish_reason': 'stop', 'generation_info_logprobs': None, 'flesch_reading_ease': 81.29, 'flesch_kincaid_grade': 3.7, 'smog_index': 0.0, 'coleman_liau_index': 5.75, 'automated_readability_index': 3.9, 'dale_chall_readability_score': 7.37, 'difficult_words': 1, 'linsear_write_formula': 2.5, 'gunning_fog': 2.8, 'text_standard': '3rd and 4th grade', 'fernandez_huerta': 115.7, 'szigriszt_pazos': 110.84, 'gutierrez_polini': 49.79, 'crawford': 0.7, 'gulpease_index': 85.4, 'osman': 83.14}
 I now know the final answer.
Final Answer: Bryan Adams has never been married.


I now know the final answer.
Final Answer: Bryan Adams has never been married.
{'action': 'on_agent_finish', 'output': 'Bryan Adams has never been married.', 'log': ' I now know the final answer.\nFinal Answer: Bryan Adams has never been married.', 'step': 14, 'starts': 8, 'ends': 6, 'errors': 0, 'text_ctr': 0, 'chain_starts': 1, 'chain_ends': 0, 'llm_starts': 3, 'llm_ends': 3, 'llm_streams': 0, 'tool_starts': 4, 'tool_ends': 2, 'agent_ends': 1}
> Finished chain.
{'action': 'on_chain_end', 'outputs': 'Bryan Adams has never been married.', 'step': 15, 'starts': 8, 'ends': 7, 'errors': 0, 'text_ctr': 0, 'chain_starts': 1, 'chain_ends': 1, 'llm_starts': 3, 'llm_ends': 3, 'llm_streams': 0, 'tool_starts': 4, 'tool_ends': 2, 'agent_ends': 1}
{'action_records':              action    name  step  starts  ends  errors  text_ctr  \
0      on_llm_start  OpenAI     1       1     0       0         0
1      on_llm_start  OpenAI     1       1     0       0         0
2      on_llm_start  OpenAI     1       1     0       0         0
3      on_llm_start  OpenAI     1       1     0       0         0