id
stringlengths 14
15
| text
stringlengths 101
5.26k
| source
stringlengths 57
120
|
---|---|---|
79751d3f0f9f-0 | .ipynb
.pdf
Tracing Walkthrough
Tracing Walkthrough#
There are two recommended ways to trace your LangChains:
Setting the LANGCHAIN_WANDB_TRACING environment variable to “true”.
Using a context manager with tracing_enabled() to trace a particular block of code.
Note if the environment variable is set, all code will be traced, regardless of whether or not it’s within the context manager.
import os
os.environ["LANGCHAIN_WANDB_TRACING"] = "true"
# wandb documentation to configure wandb using env variables
# https://docs.wandb.ai/guides/track/advanced/environment-variables
# here we are configuring the wandb project name
os.environ["WANDB_PROJECT"] = "langchain-tracing"
from langchain.agents import initialize_agent, load_tools
from langchain.agents import AgentType
from langchain.llms import OpenAI
from langchain.callbacks import wandb_tracing_enabled
# Agent run with tracing. Ensure that OPENAI_API_KEY is set appropriately to run this example.
llm = OpenAI(temperature=0)
tools = load_tools(["llm-math"], llm=llm)
agent = initialize_agent(
tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
)
agent.run("What is 2 raised to .123243 power?") # this should be traced
# A url with for the trace sesion like the following should print in your console:
# https://wandb.ai/<wandb_entity>/<wandb_project>/runs/<run_id>
# The url can be used to view the trace session in wandb.
# Now, we unset the environment variable and use a context manager.
if "LANGCHAIN_WANDB_TRACING" in os.environ:
del os.environ["LANGCHAIN_WANDB_TRACING"]
# enable tracing using a context manager
with wandb_tracing_enabled():
agent.run("What is 5 raised to .123243 power?") # this should be traced
agent.run("What is 2 raised to .123243 power?") # this should not be traced
> Entering new AgentExecutor chain...
I need to use a calculator to solve this.
Action: Calculator
Action Input: 5^.123243
Observation: Answer: 1.2193914912400514
Thought: I now know the final answer.
Final Answer: 1.2193914912400514
> Finished chain.
> Entering new AgentExecutor chain...
I need to use a calculator to solve this.
Action: Calculator
Action Input: 2^.123243
Observation: Answer: 1.0891804557407723
Thought: I now know the final answer.
Final Answer: 1.0891804557407723
> Finished chain.
'1.0891804557407723'
Here’s a view of wandb dashboard for the above tracing session:
previous
Integrations
next
AI21 Labs
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/agent_with_wandb_tracing.html |
e4dbe90ab10d-0 | .md
.pdf
Airbyte
Contents
Installation and Setup
Document Loader
Airbyte#
Airbyte is a data integration platform for ELT pipelines from APIs,
databases & files to warehouses & lakes. It has the largest catalog of ELT connectors to data warehouses and databases.
Installation and Setup#
This instruction shows how to load any source from Airbyte into a local JSON file that can be read in as a document.
Prerequisites:
Have docker desktop installed.
Steps:
Clone Airbyte from GitHub - git clone https://github.com/airbytehq/airbyte.git.
Switch into Airbyte directory - cd airbyte.
Start Airbyte - docker compose up.
In your browser, just visit http://localhost:8000. You will be asked for a username and password. By default, that’s username airbyte and password password.
Setup any source you wish.
Set destination as Local JSON, with specified destination path - lets say /json_data. Set up a manual sync.
Run the connection.
To see what files are created, navigate to: file:///tmp/airbyte_local/.
Document Loader#
See a usage example.
from langchain.document_loaders import AirbyteJSONLoader
previous
Aim
next
Aleph Alpha
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/airbyte.html |
4e6ecf8083d7-0 | .md
.pdf
RWKV-4
Contents
Installation and Setup
Usage
RWKV
Model File
Rwkv-4 models -> recommended VRAM
RWKV-4#
This page covers how to use the RWKV-4 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 rwkv
Install the tokenizer Python package with pip install tokenizer
Download a RWKV model and place it in your desired directory
Download the tokens file
Usage#
RWKV#
To use the RWKV wrapper, you need to provide the path to the pre-trained model file and the tokenizer’s configuration.
from langchain.llms import RWKV
# Test the model
```python
def generate_prompt(instruction, input=None):
if input:
return f"""Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
# Instruction:
{instruction}
# Input:
{input}
# Response:
"""
else:
return f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
# Instruction:
{instruction}
# Response:
"""
model = RWKV(model="./models/RWKV-4-Raven-3B-v7-Eng-20230404-ctx4096.pth", strategy="cpu fp32", tokens_path="./rwkv/20B_tokenizer.json")
response = model(generate_prompt("Once upon a time, "))
Model File#
You can find links to model file downloads at the RWKV-4-Raven repository.
Rwkv-4 models -> recommended VRAM#
RWKV VRAM
Model | 8bit | bf16/fp16 | fp32
14B | 16GB | 28GB | >50GB
7B | 8GB | 14GB | 28GB
3B | 2.8GB| 6GB | 12GB
1b5 | 1.3GB| 3GB | 6GB
See the rwkv pip page for more information about strategies, including streaming and cuda support.
previous
Runhouse
next
SageMaker Endpoint
Contents
Installation and Setup
Usage
RWKV
Model File
Rwkv-4 models -> recommended VRAM
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/rwkv.html |
8595aa55eb60-0 | .md
.pdf
iFixit
Contents
Installation and Setup
Document Loader
iFixit#
iFixit is the largest, open repair community on the web. The site contains nearly 100k
repair manuals, 200k Questions & Answers on 42k devices, and all the data is licensed under CC-BY-NC-SA 3.0.
Installation and Setup#
There isn’t any special setup for it.
Document Loader#
See a usage example.
from langchain.document_loaders import IFixitLoader
previous
Hugging Face
next
IMSDb
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/ifixit.html |
c4469d4dd9fc-0 | .md
.pdf
AnalyticDB
Contents
VectorStore
AnalyticDB#
This page covers how to use the AnalyticDB ecosystem within LangChain.
VectorStore#
There exists a wrapper around AnalyticDB, allowing you to use it as a vectorstore,
whether for semantic search or example selection.
To import this vectorstore:
from langchain.vectorstores import AnalyticDB
For a more detailed walkthrough of the AnalyticDB wrapper, see this notebook
previous
Amazon Bedrock
next
Annoy
Contents
VectorStore
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/analyticdb.html |
3270059c44c6-0 | .md
.pdf
Confluence
Contents
Installation and Setup
Document Loader
Confluence#
Confluence is a wiki collaboration platform that saves and organizes all of the project-related material. Confluence is a knowledge base that primarily handles content management activities.
Installation and Setup#
pip install atlassian-python-api
We need to set up username/api_key or Oauth2 login.
See instructions.
Document Loader#
See a usage example.
from langchain.document_loaders import ConfluenceLoader
previous
Comet
next
C Transformers
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/confluence.html |
f3b0c4bd0096-0 | .md
.pdf
Blackboard
Contents
Installation and Setup
Document Loader
Blackboard#
Blackboard Learn (previously the Blackboard Learning Management System)
is a web-based virtual learning environment and learning management system developed by Blackboard Inc.
The software features course management, customizable open architecture, and scalable design that allows
integration with student information systems and authentication protocols. It may be installed on local servers,
hosted by Blackboard ASP Solutions, or provided as Software as a Service hosted on Amazon Web Services.
Its main purposes are stated to include the addition of online elements to courses traditionally delivered
face-to-face and development of completely online courses with few or no face-to-face meetings.
Installation and Setup#
There isn’t any special setup for it.
Document Loader#
See a usage example.
from langchain.document_loaders import BlackboardLoader
previous
BiliBili
next
Cassandra
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/blackboard.html |
f1e02f0d48ac-0 | .ipynb
.pdf
MLflow
MLflow#
This notebook goes over how to track your LangChain experiments into your MLflow Server
!pip install azureml-mlflow
!pip install pandas
!pip install textstat
!pip install spacy
!pip install openai
!pip install google-search-results
!python -m spacy download en_core_web_sm
import os
os.environ["MLFLOW_TRACKING_URI"] = ""
os.environ["OPENAI_API_KEY"] = ""
os.environ["SERPAPI_API_KEY"] = ""
from langchain.callbacks import MlflowCallbackHandler
from langchain.llms import OpenAI
"""Main function.
This function is used to try the callback handler.
Scenarios:
1. OpenAI LLM
2. Chain with multiple SubChains on multiple generations
3. Agent with Tools
"""
mlflow_callback = MlflowCallbackHandler()
llm = OpenAI(model_name="gpt-3.5-turbo", temperature=0, callbacks=[mlflow_callback], verbose=True)
# SCENARIO 1 - LLM
llm_result = llm.generate(["Tell me a joke"])
mlflow_callback.flush_tracker(llm)
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
# SCENARIO 2 - Chain
template = """You are a playwright. Given the title of play, it is your job to write a synopsis for that title.
Title: {title}
Playwright: This is a synopsis for the above play:"""
prompt_template = PromptTemplate(input_variables=["title"], template=template)
synopsis_chain = LLMChain(llm=llm, prompt=prompt_template, callbacks=[mlflow_callback])
test_prompts = [
{
"title": "documentary about good video games that push the boundary of game design"
},
]
synopsis_chain.apply(test_prompts)
mlflow_callback.flush_tracker(synopsis_chain)
from langchain.agents import initialize_agent, load_tools
from langchain.agents import AgentType
# SCENARIO 3 - Agent with Tools
tools = load_tools(["serpapi", "llm-math"], llm=llm, callbacks=[mlflow_callback])
agent = initialize_agent(
tools,
llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
callbacks=[mlflow_callback],
verbose=True,
)
agent.run(
"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?"
)
mlflow_callback.flush_tracker(agent, finish=True)
previous
Milvus
next
Modal
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/mlflow_tracking.html |
3cf94281ef5b-0 | .md
.pdf
Anthropic
Contents
Installation and Setup
Chat Models
Anthropic#
Anthropic is an American artificial intelligence (AI) startup and
public-benefit corporation, founded by former members of OpenAI. Anthropic specializes in developing general AI
systems and language models, with a company ethos of responsible AI usage.
Anthropic develops a chatbot, named Claude. Similar to ChatGPT, Claude uses a messaging
interface where users can submit questions or requests and receive highly detailed and relevant responses.
Installation and Setup#
pip install anthropic
See the setup documentation.
Chat Models#
See a usage example
from langchain.chat_models import ChatAnthropic
previous
Annoy
next
Anyscale
Contents
Installation and Setup
Chat Models
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/anthropic.html |
472d6f942618-0 | .md
.pdf
WhatsApp
Contents
Installation and Setup
Document Loader
WhatsApp#
WhatsApp (also called WhatsApp Messenger) is a freeware, cross-platform, centralized instant messaging (IM) and voice-over-IP (VoIP) service. It allows users to send text and voice messages, make voice and video calls, and share images, documents, user locations, and other content.
Installation and Setup#
There isn’t any special setup for it.
Document Loader#
See a usage example.
from langchain.document_loaders import WhatsAppChatLoader
previous
Weaviate
next
WhyLabs
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/whatsapp.html |
f9dac209c4ac-0 | .ipynb
.pdf
ClearML
Contents
Installation and Setup
Getting API Credentials
Callbacks
Scenario 1: Just an LLM
Scenario 2: Creating an agent with tools
Tips and Next Steps
ClearML#
ClearML is a ML/DL development and production suite, it contains 5 main modules:
Experiment Manager - Automagical experiment tracking, environments and results
MLOps - Orchestration, Automation & Pipelines solution for ML/DL jobs (K8s / Cloud / bare-metal)
Data-Management - Fully differentiable data management & version control solution on top of object-storage (S3 / GS / Azure / NAS)
Model-Serving - cloud-ready Scalable model serving solution!
Deploy new model endpoints in under 5 minutes
Includes optimized GPU serving support backed by Nvidia-Triton
with out-of-the-box Model Monitoring
Fire Reports - Create and share rich MarkDown documents supporting embeddable online content
In order to properly keep track of your langchain experiments and their results, you can enable the ClearML integration. We use the ClearML Experiment Manager that neatly tracks and organizes all your experiment runs.
Installation and Setup#
!pip install clearml
!pip install pandas
!pip install textstat
!pip install spacy
!python -m spacy download en_core_web_sm
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"] = ""
Callbacks#
from langchain.callbacks import ClearMLCallbackHandler
from datetime import datetime
from langchain.callbacks import StdOutCallbackHandler
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
)
callbacks = [StdOutCallbackHandler(), clearml_callback]
# Get the OpenAI model ready to go
llm = OpenAI(temperature=0, callbacks=callbacks)
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'} | https://langchain.readthedocs.io/en/latest/integrations/clearml_tracking.html |
f9dac209c4ac-1 | {'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} | https://langchain.readthedocs.io/en/latest/integrations/clearml_tracking.html |
f9dac209c4ac-2 | {'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\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} | https://langchain.readthedocs.io/en/latest/integrations/clearml_tracking.html |
f9dac209c4ac-3 | {'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\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} | https://langchain.readthedocs.io/en/latest/integrations/clearml_tracking.html |
f9dac209c4ac-4 | {'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 | https://langchain.readthedocs.io/en/latest/integrations/clearml_tracking.html |
f9dac209c4ac-5 | 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
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
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 | https://langchain.readthedocs.io/en/latest/integrations/clearml_tracking.html |
f9dac209c4ac-6 | 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 | https://langchain.readthedocs.io/en/latest/integrations/clearml_tracking.html |
f9dac209c4ac-7 | 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
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
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
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 | https://langchain.readthedocs.io/en/latest/integrations/clearml_tracking.html |
f9dac209c4ac-8 | 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.
Scenario 2: Creating an 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, callbacks=callbacks)
agent = initialize_agent(
tools,
llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
callbacks=callbacks,
)
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:'} | https://langchain.readthedocs.io/en/latest/integrations/clearml_tracking.html |
f9dac209c4ac-9 | {'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).
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} | https://langchain.readthedocs.io/en/latest/integrations/clearml_tracking.html |
f9dac209c4ac-10 | {'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
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} | https://langchain.readthedocs.io/en/latest/integrations/clearml_tracking.html |
f9dac209c4ac-11 | {'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 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:'} | https://langchain.readthedocs.io/en/latest/integrations/clearml_tracking.html |
f9dac209c4ac-12 | {'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.
{'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
4 on_llm_start OpenAI 1 1 0 0 0
.. ... ... ... ... ... ... ...
66 on_tool_end NaN 11 7 4 0 0
67 on_llm_start OpenAI 12 8 4 0 0
68 on_llm_end NaN 13 8 5 0 0
69 on_agent_finish NaN 14 8 6 0 0
70 on_chain_end NaN 15 8 7 0 0
chain_starts chain_ends llm_starts ... gulpease_index osman input \
0 0 0 1 ... NaN NaN NaN
1 0 0 1 ... NaN NaN NaN | https://langchain.readthedocs.io/en/latest/integrations/clearml_tracking.html |
f9dac209c4ac-13 | 1 0 0 1 ... NaN NaN NaN
2 0 0 1 ... NaN NaN NaN
3 0 0 1 ... NaN NaN NaN
4 0 0 1 ... NaN NaN NaN
.. ... ... ... ... ... ... ...
66 1 0 2 ... NaN NaN NaN
67 1 0 3 ... NaN NaN NaN
68 1 0 3 ... 85.4 83.14 NaN
69 1 0 3 ... NaN NaN NaN
70 1 1 3 ... NaN NaN NaN
tool tool_input log \
0 NaN NaN NaN
1 NaN NaN NaN
2 NaN NaN NaN
3 NaN NaN NaN
4 NaN NaN NaN
.. ... ... ...
66 NaN NaN NaN
67 NaN NaN NaN
68 NaN NaN NaN
69 NaN NaN I now know the final answer.\nFinal Answer: B...
70 NaN NaN NaN
input_str description output \
0 NaN NaN NaN
1 NaN NaN NaN
2 NaN NaN NaN
3 NaN NaN NaN
4 NaN NaN NaN
.. ... ... ...
66 NaN NaN Bryan Adams has never married. In the 1990s, h...
67 NaN NaN NaN
68 NaN NaN NaN
69 NaN NaN Bryan Adams has never been married.
70 NaN NaN NaN
outputs
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
.. ...
66 NaN
67 NaN
68 NaN
69 NaN
70 Bryan Adams has never been married.
[71 rows x 47 columns], 'session_analysis': prompt_step prompts name \
0 2 Answer the following questions as best you can... OpenAI
1 7 Answer the following questions as best you can... OpenAI
2 12 Answer the following questions as best you can... OpenAI
output_step output \
0 3 I need to find out who sang summer of 69 and ...
1 8 I need to find out who Bryan Adams is married...
2 13 I now know the final answer.\nFinal Answer: B...
token_usage_total_tokens token_usage_prompt_tokens \
0 223 189
1 270 242
2 332 314
token_usage_completion_tokens flesch_reading_ease flesch_kincaid_grade \
0 34 91.61 3.8
1 28 94.66 2.7
2 18 81.29 3.7
... difficult_words linsear_write_formula gunning_fog \
0 ... 2 5.75 5.4
1 ... 2 4.25 4.2
2 ... 1 2.50 2.8
text_standard fernandez_huerta szigriszt_pazos gutierrez_polini \
0 3rd and 4th grade 121.07 119.50 54.91
1 4th and 5th grade 124.13 119.20 52.26
2 3rd and 4th grade 115.70 110.84 49.79
crawford gulpease_index osman
0 0.9 72.7 92.16 | https://langchain.readthedocs.io/en/latest/integrations/clearml_tracking.html |
f9dac209c4ac-14 | 0 0.9 72.7 92.16
1 0.7 74.7 84.20
2 0.7 85.4 83.14
[3 rows x 24 columns]}
Could not update last created model in Task 988bd727b0e94a29a3ac0ee526813545, Task status 'completed' cannot be updated
Tips and Next Steps#
Make sure you always use a unique name argument for the clearml_callback.flush_tracker function. If not, the model parameters used for a run will override the previous run!
If you close the ClearML Callback using clearml_callback.flush_tracker(..., finish=True) the Callback cannot be used anymore. Make a new one if you want to keep logging.
Check out the rest of the open source ClearML ecosystem, there is a data version manager, a remote execution agent, automated pipelines and much more!
previous
Chroma
next
ClickHouse
Contents
Installation and Setup
Getting API Credentials
Callbacks
Scenario 1: Just an LLM
Scenario 2: Creating an agent with tools
Tips and Next Steps
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/clearml_tracking.html |
759278a6851b-0 | .md
.pdf
Microsoft Word
Contents
Installation and Setup
Document Loader
Microsoft Word#
Microsoft Word is a word processor developed by Microsoft.
Installation and Setup#
There isn’t any special setup for it.
Document Loader#
See a usage example.
from langchain.document_loaders import UnstructuredWordDocumentLoader
previous
Microsoft PowerPoint
next
Milvus
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/microsoft_word.html |
beadf88e67de-0 | .md
.pdf
DuckDB
Contents
Installation and Setup
Document Loader
DuckDB#
DuckDB is an in-process SQL OLAP database management system.
Installation and Setup#
First, you need to install duckdb python package.
pip install duckdb
Document Loader#
See a usage example.
from langchain.document_loaders import DuckDBLoader
previous
Docugami
next
Elasticsearch
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/duckdb.html |
4a5780828f48-0 | .md
.pdf
Git
Contents
Installation and Setup
Document Loader
Git#
Git is a distributed version control system that tracks changes in any set of computer files, usually used for coordinating work among programmers collaboratively developing source code during software development.
Installation and Setup#
First, you need to install GitPython python package.
pip install GitPython
Document Loader#
See a usage example.
from langchain.document_loaders import GitLoader
previous
ForefrontAI
next
GitBook
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/git.html |
369ecdb9d975-0 | .md
.pdf
Tair
Contents
Installation and Setup
Wrappers
VectorStore
Tair#
This page covers how to use the Tair ecosystem within LangChain.
Installation and Setup#
Install Tair Python SDK with pip install tair.
Wrappers#
VectorStore#
There exists a wrapper around TairVector, allowing you to use it as a vectorstore,
whether for semantic search or example selection.
To import this vectorstore:
from langchain.vectorstores import Tair
For a more detailed walkthrough of the Tair wrapper, see this notebook
previous
Stripe
next
Telegram
Contents
Installation and Setup
Wrappers
VectorStore
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/tair.html |
5bc597bac429-0 | .md
.pdf
OpenAI
Contents
Installation and Setup
LLM
Text Embedding Model
Chat Model
Tokenizer
Chain
Document Loader
Retriever
OpenAI#
OpenAI is American artificial intelligence (AI) research laboratory
consisting of the non-profit OpenAI Incorporated
and its for-profit subsidiary corporation OpenAI Limited Partnership.
OpenAI conducts AI research with the declared intention of promoting and developing a friendly AI.
OpenAI systems run on an Azure-based supercomputing platform from Microsoft.
The OpenAI API is powered by a diverse set of models with different capabilities and price points.
ChatGPT is the Artificial Intelligence (AI) chatbot developed by OpenAI.
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
pip install tiktoken
LLM#
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
Text Embedding Model#
from langchain.embeddings import OpenAIEmbeddings
For a more detailed walkthrough of this, see this notebook
Chat Model#
from langchain.chat_models import ChatOpenAI
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
Chain#
See a usage example.
from langchain.chains import OpenAIModerationChain
Document Loader#
See a usage example.
from langchain.document_loaders.chatgpt import ChatGPTLoader
Retriever#
See a usage example.
from langchain.retrievers import ChatGPTPluginRetriever
previous
Obsidian
next
OpenSearch
Contents
Installation and Setup
LLM
Text Embedding Model
Chat Model
Tokenizer
Chain
Document Loader
Retriever
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/openai.html |
6f648314dc4c-0 | .md
.pdf
Notion DB
Contents
Installation and Setup
Document Loader
Notion DB#
Notion is a collaboration platform with modified Markdown support that integrates kanban
boards, tasks, wikis and databases. It is an all-in-one workspace for notetaking, knowledge and data management,
and project and task management.
Installation and Setup#
All instructions are in examples below.
Document Loader#
We have two different loaders: NotionDirectoryLoader and NotionDBLoader.
See a usage example for the NotionDirectoryLoader.
from langchain.document_loaders import NotionDirectoryLoader
See a usage example for the NotionDBLoader.
from langchain.document_loaders import NotionDBLoader
previous
NLPCloud
next
Obsidian
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/notion.html |
751b4fcef17d-0 | .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
Arxiv
next
AWS S3 Directory
Contents
Installation and Setup
Wrappers
VectorStore
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/atlas.html |
483f57ac776b-0 | .md
.pdf
Twitter
Contents
Installation and Setup
Document Loader
Twitter#
Twitter is an online social media and social networking service.
Installation and Setup#
pip install tweepy
We must initialize the loader with the Twitter API token, and we need to set up the Twitter username.
Document Loader#
See a usage example.
from langchain.document_loaders import TwitterTweetLoader
previous
Trello
next
Unstructured
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/twitter.html |
90434826f057-0 | .md
.pdf
Facebook Chat
Contents
Installation and Setup
Document Loader
Facebook Chat#
Messenger is an American proprietary instant messaging app and
platform developed by Meta Platforms. Originally developed as Facebook Chat in 2008, the company revamped its
messaging service in 2010.
Installation and Setup#
First, you need to install pandas python package.
pip install pandas
Document Loader#
See a usage example.
from langchain.document_loaders import FacebookChatLoader
previous
EverNote
next
Figma
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/facebook_chat.html |
44f158051c0c-0 | .md
.pdf
Telegram
Contents
Installation and Setup
Document Loader
Telegram#
Telegram Messenger is a globally accessible freemium, cross-platform, encrypted, cloud-based and centralized instant messaging service. The application also provides optional end-to-end encrypted chats and video calling, VoIP, file sharing and several other features.
Installation and Setup#
See setup instructions.
Document Loader#
See a usage example.
from langchain.document_loaders import TelegramChatFileLoader
from langchain.document_loaders import TelegramChatApiLoader
previous
Tair
next
Tensorflow Hub
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/telegram.html |
bd16384321b3-0 | .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
Psychic
next
Ray Serve
Contents
Installation and Setup
Wrappers
VectorStore
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/qdrant.html |
0e2df010774d-0 | .md
.pdf
Spreedly
Contents
Installation and Setup
Document Loader
Spreedly#
Spreedly is a service that allows you to securely store credit cards and use them to transact against any number of payment gateways and third party APIs. It does this by simultaneously providing a card tokenization/vault service as well as a gateway and receiver integration service. Payment methods tokenized by Spreedly are stored at Spreedly, allowing you to independently store a card and then pass that card to different end points based on your business requirements.
Installation and Setup#
See setup instructions.
Document Loader#
See a usage example.
from langchain.document_loaders import SpreedlyLoader
previous
spaCy
next
StochasticAI
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/spreedly.html |
5101a590d35a-0 | .md
.pdf
SerpAPI
Contents
Installation and Setup
Wrappers
Utility
Tool
SerpAPI#
This page covers how to use the SerpAPI search APIs within LangChain.
It is broken into two parts: installation and setup, and then references to the specific SerpAPI wrapper.
Installation and Setup#
Install requirements with pip install google-search-results
Get a SerpAPI api key and either set it as an environment variable (SERPAPI_API_KEY)
Wrappers#
Utility#
There exists a SerpAPI utility which wraps this API. To import this utility:
from langchain.utilities import SerpAPIWrapper
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(["serpapi"])
For more information on this, see this page
previous
SearxNG Search API
next
Shale Protocol
Contents
Installation and Setup
Wrappers
Utility
Tool
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/serpapi.html |
b9776f7afd96-0 | .ipynb
.pdf
Aim
Aim#
Aim makes it super easy to visualize and debug LangChain executions. Aim tracks inputs and outputs of LLMs and tools, as well as actions of agents.
With Aim, you can easily debug and examine an individual execution:
Additionally, you have the option to compare multiple executions side by side:
Aim is fully open source, learn more about Aim on GitHub.
Let’s move forward and see how to enable and configure Aim callback.
Tracking LangChain Executions with AimIn this notebook we will explore three usage scenarios. To start off, we will install the necessary packages and import certain modules. Subsequently, we will configure two environment variables that can be established either within the Python script or through the terminal.
!pip install aim
!pip install langchain
!pip install openai
!pip install google-search-results
import os
from datetime import datetime
from langchain.llms import OpenAI
from langchain.callbacks import AimCallbackHandler, StdOutCallbackHandler
Our examples use a GPT model as the LLM, and OpenAI offers an API for this purpose. You can obtain the key from the following link: https://platform.openai.com/account/api-keys .
We will use the SerpApi to retrieve search results from Google. To acquire the SerpApi key, please go to https://serpapi.com/manage-api-key .
os.environ["OPENAI_API_KEY"] = "..."
os.environ["SERPAPI_API_KEY"] = "..."
The event methods of AimCallbackHandler accept the LangChain module or agent as input and log at least the prompts and generated results, as well as the serialized version of the LangChain module, to the designated Aim run.
session_group = datetime.now().strftime("%m.%d.%Y_%H.%M.%S")
aim_callback = AimCallbackHandler(
repo=".",
experiment_name="scenario 1: OpenAI LLM",
)
callbacks = [StdOutCallbackHandler(), aim_callback]
llm = OpenAI(temperature=0, callbacks=callbacks)
The flush_tracker function is used to record LangChain assets on Aim. By default, the session is reset rather than being terminated outright.
Scenario 1 In the first scenario, we will use OpenAI LLM.
# scenario 1 - LLM
llm_result = llm.generate(["Tell me a joke", "Tell me a poem"] * 3)
aim_callback.flush_tracker(
langchain_asset=llm,
experiment_name="scenario 2: Chain with multiple SubChains on multiple generations",
)
Scenario 2 Scenario two involves chaining with multiple SubChains across multiple generations.
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
# scenario 2 - Chain
template = """You are a playwright. Given the title of play, it is your job to write a synopsis for that title.
Title: {title}
Playwright: This is a synopsis for the above play:"""
prompt_template = PromptTemplate(input_variables=["title"], template=template)
synopsis_chain = LLMChain(llm=llm, prompt=prompt_template, callbacks=callbacks)
test_prompts = [
{"title": "documentary about good video games that push the boundary of game design"},
{"title": "the phenomenon behind the remarkable speed of cheetahs"},
{"title": "the best in class mlops tooling"},
]
synopsis_chain.apply(test_prompts)
aim_callback.flush_tracker(
langchain_asset=synopsis_chain, experiment_name="scenario 3: Agent with Tools"
)
Scenario 3 The third scenario involves an agent with tools.
from langchain.agents import initialize_agent, load_tools
from langchain.agents import AgentType
# scenario 3 - Agent with Tools
tools = load_tools(["serpapi", "llm-math"], llm=llm, callbacks=callbacks)
agent = initialize_agent(
tools,
llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
callbacks=callbacks,
)
agent.run(
"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?"
)
aim_callback.flush_tracker(langchain_asset=agent, reset=False, finish=True)
> Entering new AgentExecutor chain...
I need to find out who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power.
Action: Search
Action Input: "Leo DiCaprio girlfriend" | https://langchain.readthedocs.io/en/latest/integrations/aim_tracking.html |
b9776f7afd96-1 | Action: Search
Action Input: "Leo DiCaprio girlfriend"
Observation: Leonardo DiCaprio seemed to prove a long-held theory about his love life right after splitting from girlfriend Camila Morrone just months ...
Thought: I need to find out Camila Morrone's age
Action: Search
Action Input: "Camila Morrone age"
Observation: 25 years
Thought: I need to calculate 25 raised to the 0.43 power
Action: Calculator
Action Input: 25^0.43
Observation: Answer: 3.991298452658078
Thought: I now know the final answer
Final Answer: Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.991298452658078.
> Finished chain.
previous
AI21 Labs
next
Airbyte
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/aim_tracking.html |
401f77a22f58-0 | .md
.pdf
Psychic
Contents
Installation and Setup
Advantages vs Other Document Loaders
Psychic#
Psychic is a platform for integrating with SaaS tools like Notion, Zendesk,
Confluence, and Google Drive via OAuth and syncing documents from these applications to your SQL or vector
database. You can think of it like Plaid for unstructured data.
Installation and Setup#
pip install psychicapi
Psychic is easy to set up - you import the react library and configure it with your Sidekick API key, which you get
from the Psychic dashboard. When you connect the applications, you
view these connections from the dashboard and retrieve data using the server-side libraries.
Create an account in the dashboard.
Use the react library to add the Psychic link modal to your frontend react app. You will use this to connect the SaaS apps.
Once you have created a connection, you can use the PsychicLoader by following the example notebook
Advantages vs Other Document Loaders#
Universal API: Instead of building OAuth flows and learning the APIs for every SaaS app, you integrate Psychic once and leverage our universal API to retrieve data.
Data Syncs: Data in your customers’ SaaS apps can get stale fast. With Psychic you can configure webhooks to keep your documents up to date on a daily or realtime basis.
Simplified OAuth: Psychic handles OAuth end-to-end so that you don’t have to spend time creating OAuth clients for each integration, keeping access tokens fresh, and handling OAuth redirect logic.
previous
PromptLayer
next
Qdrant
Contents
Installation and Setup
Advantages vs Other Document Loaders
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/psychic.html |
6a20ca25e62a-0 | .md
.pdf
GitBook
Contents
Installation and Setup
Document Loader
GitBook#
GitBook is a modern documentation platform where teams can document everything from products to internal knowledge bases and APIs.
Installation and Setup#
There isn’t any special setup for it.
Document Loader#
See a usage example.
from langchain.document_loaders import GitbookLoader
previous
Git
next
Google BigQuery
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/gitbook.html |
fa44c8f4ed46-0 | .md
.pdf
Arxiv
Contents
Installation and Setup
Document Loader
Retriever
Arxiv#
arXiv is an open-access archive for 2 million scholarly articles in the fields of physics,
mathematics, computer science, quantitative biology, quantitative finance, statistics, electrical engineering and
systems science, and economics.
Installation and Setup#
First, you need to install arxiv python package.
pip install arxiv
Second, you need to install PyMuPDF python package which transforms PDF files downloaded from the arxiv.org site into the text format.
pip install pymupdf
Document Loader#
See a usage example.
from langchain.document_loaders import ArxivLoader
Retriever#
See a usage example.
from langchain.retrievers import ArxivRetriever
previous
Argilla
next
AtlasDB
Contents
Installation and Setup
Document Loader
Retriever
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/arxiv.html |
1381b0b53316-0 | .md
.pdf
Graphsignal
Contents
Installation and Setup
Tracing and Monitoring
Graphsignal#
This page covers how to use Graphsignal to trace and monitor LangChain. Graphsignal enables full visibility into your application. It provides latency breakdowns by chains and tools, exceptions with full context, data monitoring, compute/GPU utilization, OpenAI cost analytics, and more.
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 and metrics are then available in your Graphsignal dashboards.
Initialize the tracer by providing a deployment name:
import graphsignal
graphsignal.configure(deployment='my-langchain-app-prod')
To additionally trace any function or code, you can use a decorator or a context manager:
@graphsignal.trace_function
def handle_request():
chain.run("some initial text")
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
Gutenberg
Contents
Installation and Setup
Tracing and Monitoring
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/graphsignal.html |
01a118eca97d-0 | .md
.pdf
MyScale
Contents
Introduction
Installation and Setup
Setting up envrionments
Wrappers
VectorStore
MyScale#
This page covers how to use MyScale vector database within LangChain.
It is broken into two parts: installation and setup, and then references to specific MyScale wrappers.
With MyScale, you can manage both structured and unstructured (vectorized) data, and perform joint queries and analytics on both types of data using SQL. Plus, MyScale’s cloud-native OLAP architecture, built on top of ClickHouse, enables lightning-fast data processing even on massive datasets.
Introduction#
Overview to MyScale and High performance vector search
You can now register on our SaaS and start a cluster now!
If you are also interested in how we managed to integrate SQL and vector, please refer to this document for further syntax reference.
We also deliver with live demo on huggingface! Please checkout our huggingface space! They search millions of vector within a blink!
Installation and Setup#
Install the Python SDK with pip install clickhouse-connect
Setting up envrionments#
There are two ways to set up parameters for myscale index.
Environment Variables
Before you run the app, please set the environment variable with export:
export MYSCALE_URL='<your-endpoints-url>' MYSCALE_PORT=<your-endpoints-port> MYSCALE_USERNAME=<your-username> MYSCALE_PASSWORD=<your-password> ...
You can easily find your account, password and other info on our SaaS. For details please refer to this document
Every attributes under MyScaleSettings can be set with prefix MYSCALE_ and is case insensitive.
Create MyScaleSettings object with parameters
from langchain.vectorstores import MyScale, MyScaleSettings
config = MyScaleSetting(host="<your-backend-url>", port=8443, ...)
index = MyScale(embedding_function, config)
index.add_documents(...)
Wrappers#
supported functions:
add_texts
add_documents
from_texts
from_documents
similarity_search
asimilarity_search
similarity_search_by_vector
asimilarity_search_by_vector
similarity_search_with_relevance_scores
VectorStore#
There exists a wrapper around MyScale database, allowing you to use it as a vectorstore,
whether for semantic search or similar example retrieval.
To import this vectorstore:
from langchain.vectorstores import MyScale
For a more detailed walkthrough of the MyScale wrapper, see this notebook
previous
Momento
next
NLPCloud
Contents
Introduction
Installation and Setup
Setting up envrionments
Wrappers
VectorStore
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/myscale.html |
3db7b2db4a10-0 | .md
.pdf
scikit-learn
Contents
Installation and Setup
Wrappers
VectorStore
scikit-learn#
This page covers how to use the scikit-learn package within LangChain.
It is broken into two parts: installation and setup, and then references to specific scikit-learn wrappers.
Installation and Setup#
Install the Python package with pip install scikit-learn
Wrappers#
VectorStore#
SKLearnVectorStore provides a simple wrapper around the nearest neighbor implementation in the
scikit-learn package, allowing you to use it as a vectorstore.
To import this vectorstore:
from langchain.vectorstores import SKLearnVectorStore
For a more detailed walkthrough of the SKLearnVectorStore wrapper, see this notebook.
previous
Shale Protocol
next
Slack
Contents
Installation and Setup
Wrappers
VectorStore
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/sklearn.html |
af4da1b074ff-0 | .md
.pdf
AWS S3 Directory
Contents
Installation and Setup
Document Loader
AWS S3 Directory#
Amazon Simple Storage Service (Amazon S3) is an object storage service.
AWS S3 Directory
AWS S3 Buckets
Installation and Setup#
pip install boto3
Document Loader#
See a usage example for S3DirectoryLoader.
See a usage example for S3FileLoader.
from langchain.document_loaders import S3DirectoryLoader, S3FileLoader
previous
AtlasDB
next
AZLyrics
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/aws_s3.html |
db54d04b800a-0 | .md
.pdf
Google Cloud Storage
Contents
Installation and Setup
Document Loader
Google Cloud Storage#
Google Cloud Storage is a managed service for storing unstructured data.
Installation and Setup#
First, you need to install google-cloud-bigquery python package.
pip install google-cloud-storage
Document Loader#
There are two loaders for the Google Cloud Storage: the Directory and the File loaders.
See a usage example.
from langchain.document_loaders import GCSDirectoryLoader
See a usage example.
from langchain.document_loaders import GCSFileLoader
previous
Google BigQuery
next
Google Drive
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/google_cloud_storage.html |
38a50083fab2-0 | .md
.pdf
EverNote
Contents
Installation and Setup
Document Loader
EverNote#
EverNote is intended for archiving and creating notes in which photos, audio and saved web content can be embedded. Notes are stored in virtual “notebooks” and can be tagged, annotated, edited, searched, and exported.
Installation and Setup#
First, you need to install lxml and html2text python packages.
pip install lxml
pip install html2text
Document Loader#
See a usage example.
from langchain.document_loaders import EverNoteLoader
previous
Elasticsearch
next
Facebook Chat
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/evernote.html |
73c8ba30b728-0 | .md
.pdf
Argilla
Contents
Installation and Setup
Tracking
Argilla#
Argilla is an open-source data curation platform for LLMs.
Using Argilla, everyone can build robust language models through faster data curation
using both human and machine feedback. We provide support for each step in the MLOps cycle,
from data labeling to model monitoring.
Installation and Setup#
First, you’ll need to install the argilla Python package as follows:
pip install argilla --upgrade
If you already have an Argilla Server running, then you’re good to go; but if
you don’t, follow the next steps to install it.
If you don’t you can refer to Argilla - 🚀 Quickstart to deploy Argilla either on HuggingFace Spaces, locally, or on a server.
Tracking#
See a usage example of ArgillaCallbackHandler.
from langchain.callbacks import ArgillaCallbackHandler
previous
Apify
next
Arxiv
Contents
Installation and Setup
Tracking
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/argilla.html |
3c9cdba644bb-0 | .md
.pdf
Azure Blob Storage
Contents
Installation and Setup
Document Loader
Azure Blob Storage#
Azure Blob Storage is Microsoft’s object storage solution for the cloud. Blob Storage is optimized for storing massive amounts of unstructured data. Unstructured data is data that doesn’t adhere to a particular data model or definition, such as text or binary data.
Azure Files offers fully managed
file shares in the cloud that are accessible via the industry standard Server Message Block (SMB) protocol,
Network File System (NFS) protocol, and Azure Files REST API. Azure Files are based on the Azure Blob Storage.
Azure Blob Storage is designed for:
Serving images or documents directly to a browser.
Storing files for distributed access.
Streaming video and audio.
Writing to log files.
Storing data for backup and restore, disaster recovery, and archiving.
Storing data for analysis by an on-premises or Azure-hosted service.
Installation and Setup#
pip install azure-storage-blob
Document Loader#
See a usage example for the Azure Blob Storage.
from langchain.document_loaders import AzureBlobStorageContainerLoader
See a usage example for the Azure Files.
from langchain.document_loaders import AzureBlobStorageFileLoader
previous
AZLyrics
next
Azure Cognitive Search
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/azure_blob_storage.html |
10843b3260b3-0 | .md
.pdf
Helicone
Contents
What is Helicone?
Quick start
How to enable Helicone caching
How to use Helicone custom properties
Helicone#
This page covers how to use the Helicone ecosystem within LangChain.
What is Helicone?#
Helicone is an open source observability platform that proxies your OpenAI traffic and provides you key insights into your spend, latency and usage.
Quick start#
With your LangChain environment you can just add the following parameter.
export OPENAI_API_BASE="https://oai.hconeai.com/v1"
Now head over to helicone.ai to create your account, and add your OpenAI API key within our dashboard to view your logs.
How to enable Helicone caching#
from langchain.llms import OpenAI
import openai
openai.api_base = "https://oai.hconeai.com/v1"
llm = OpenAI(temperature=0.9, headers={"Helicone-Cache-Enabled": "true"})
text = "What is a helicone?"
print(llm(text))
Helicone caching docs
How to use Helicone custom properties#
from langchain.llms import OpenAI
import openai
openai.api_base = "https://oai.hconeai.com/v1"
llm = OpenAI(temperature=0.9, headers={
"Helicone-Property-Session": "24",
"Helicone-Property-Conversation": "support_issue_2",
"Helicone-Property-App": "mobile",
})
text = "What is a helicone?"
print(llm(text))
Helicone property docs
previous
Hazy Research
next
Hugging Face
Contents
What is Helicone?
Quick start
How to enable Helicone caching
How to use Helicone custom properties
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/helicone.html |
9320f2c27efa-0 | .md
.pdf
Hugging Face
Contents
Installation and Setup
Wrappers
LLM
Embeddings
Tokenizer
Datasets
Hugging Face#
This page covers how to use the Hugging Face ecosystem (including the Hugging Face Hub) within LangChain.
It is broken into two parts: installation and setup, and then references to specific Hugging Face wrappers.
Installation and Setup#
If you want to work with the Hugging Face Hub:
Install the Hub client library with pip install huggingface_hub
Create a Hugging Face account (it’s free!)
Create an access token and set it as an environment variable (HUGGINGFACEHUB_API_TOKEN)
If you want work with the Hugging Face Python libraries:
Install pip install transformers for working with models and tokenizers
Install pip install datasets for working with datasets
Wrappers#
LLM#
There exists two Hugging Face LLM wrappers, one for a local pipeline and one for a model hosted on Hugging Face Hub.
Note that these wrappers only work for models that support the following tasks: text2text-generation, text-generation
To use the local pipeline wrapper:
from langchain.llms import HuggingFacePipeline
To use a the wrapper for a model hosted on Hugging Face Hub:
from langchain.llms import HuggingFaceHub
For a more detailed walkthrough of the Hugging Face Hub wrapper, see this notebook
Embeddings#
There exists two Hugging Face Embeddings wrappers, one for a local model and one for a model hosted on Hugging Face Hub.
Note that these wrappers only work for sentence-transformers models.
To use the local pipeline wrapper:
from langchain.embeddings import HuggingFaceEmbeddings
To use a the wrapper for a model hosted on Hugging Face Hub:
from langchain.embeddings import HuggingFaceHubEmbeddings
For a more detailed walkthrough of this, see this notebook
Tokenizer#
There are several places you can use tokenizers available through the transformers package.
By default, it is used to count tokens for all LLMs.
You can also use it to count tokens when splitting documents with
from langchain.text_splitter import CharacterTextSplitter
CharacterTextSplitter.from_huggingface_tokenizer(...)
For a more detailed walkthrough of this, see this notebook
Datasets#
The Hugging Face Hub has lots of great datasets that can be used to evaluate your LLM chains.
For a detailed walkthrough of how to use them to do so, see this notebook
previous
Helicone
next
iFixit
Contents
Installation and Setup
Wrappers
LLM
Embeddings
Tokenizer
Datasets
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/huggingface.html |
5cec93a1be09-0 | .md
.pdf
Trello
Contents
Installation and Setup
Document Loader
Trello#
Trello is a web-based project management and collaboration tool that allows individuals and teams to organize and track their tasks and projects. It provides a visual interface known as a “board” where users can create lists and cards to represent their tasks and activities.
The TrelloLoader allows us to load cards from a Trello board.
Installation and Setup#
pip install py-trello beautifulsoup4
See setup instructions.
Document Loader#
See a usage example.
from langchain.document_loaders import TrelloLoader
previous
2Markdown
next
Twitter
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/trello.html |
2be46843ff8a-0 | .md
.pdf
Slack
Contents
Installation and Setup
Document Loader
Slack#
Slack is an instant messaging program.
Installation and Setup#
There isn’t any special setup for it.
Document Loader#
See a usage example.
from langchain.document_loaders import SlackDirectoryLoader
previous
scikit-learn
next
spaCy
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/slack.html |
32beea063188-0 | .md
.pdf
SageMaker Endpoint
Contents
Installation and Setup
LLM
Text Embedding Models
SageMaker Endpoint#
Amazon SageMaker is a system that can build, train, and deploy machine learning (ML) models with fully managed infrastructure, tools, and workflows.
We use SageMaker to host our model and expose it as the SageMaker Endpoint.
Installation and Setup#
pip install boto3
For instructions on how to expose model as a SageMaker Endpoint, please see here.
Note: In order to handle batched requests, we need to adjust the return line in the predict_fn() function within the custom inference.py script:
Change from
return {"vectors": sentence_embeddings[0].tolist()}
to:
return {"vectors": sentence_embeddings.tolist()}
We have to set up following required parameters of the SagemakerEndpoint call:
endpoint_name: The name of the endpoint from the deployed Sagemaker model.
Must be unique within an AWS Region.
credentials_profile_name: The name of the profile in the ~/.aws/credentials or ~/.aws/config files, which
has either access keys or role information specified.
If not specified, the default credential profile or, if on an EC2 instance,
credentials from IMDS will be used.
See this guide.
LLM#
See a usage example.
from langchain import SagemakerEndpoint
from langchain.llms.sagemaker_endpoint import LLMContentHandler
Text Embedding Models#
See a usage example.
from langchain.embeddings import SagemakerEndpointEmbeddings
from langchain.llms.sagemaker_endpoint import ContentHandlerBase
previous
RWKV-4
next
SearxNG Search API
Contents
Installation and Setup
LLM
Text Embedding Models
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/sagemaker_endpoint.html |
0ef1e3b64b1a-0 | .md
.pdf
Databricks
Contents
Databricks connector for the SQLDatabase Chain
Databricks-managed MLflow integrates with LangChain
Databricks as an LLM provider
Databricks Dolly
Databricks#
The Databricks Lakehouse Platform unifies data, analytics, and AI on one platform.
Databricks embraces the LangChain ecosystem in various ways:
Databricks connector for the SQLDatabase Chain: SQLDatabase.from_databricks() provides an easy way to query your data on Databricks through LangChain
Databricks-managed MLflow integrates with LangChain: Tracking and serving LangChain applications with fewer steps
Databricks as an LLM provider: Deploy your fine-tuned LLMs on Databricks via serving endpoints or cluster driver proxy apps, and query it as langchain.llms.Databricks
Databricks Dolly: Databricks open-sourced Dolly which allows for commercial use, and can be accessed through the HuggingFace Hub
Databricks connector for the SQLDatabase Chain#
You can connect to Databricks runtimes and Databricks SQL using the SQLDatabase wrapper of LangChain. See the notebook Connect to Databricks for details.
Databricks-managed MLflow integrates with LangChain#
MLflow is an open source platform to manage the ML lifecycle, including experimentation, reproducibility, deployment, and a central model registry. See the notebook MLflow Callback Handler for details about MLflow’s integration with LangChain.
Databricks provides a fully managed and hosted version of MLflow integrated with enterprise security features, high availability, and other Databricks workspace features such as experiment and run management and notebook revision capture. MLflow on Databricks offers an integrated experience for tracking and securing machine learning model training runs and running machine learning projects. See MLflow guide for more details.
Databricks-managed MLflow makes it more convenient to develop LangChain applications on Databricks. For MLflow tracking, you don’t need to set the tracking uri. For MLflow Model Serving, you can save LangChain Chains in the MLflow langchain flavor, and then register and serve the Chain with a few clicks on Databricks, with credentials securely managed by MLflow Model Serving.
Databricks as an LLM provider#
The notebook Wrap Databricks endpoints as LLMs illustrates the method to wrap Databricks endpoints as LLMs in LangChain. It supports two types of endpoints: the serving endpoint, which is recommended for both production and development, and the cluster driver proxy app, which is recommended for interactive development.
Databricks endpoints support Dolly, but are also great for hosting models like MPT-7B or any other models from the HuggingFace ecosystem. Databricks endpoints can also be used with proprietary models like OpenAI to provide a governance layer for enterprises.
Databricks Dolly#
Databricks’ Dolly is an instruction-following large language model trained on the Databricks machine learning platform that is licensed for commercial use. The model is available on Hugging Face Hub as databricks/dolly-v2-12b. See the notebook HuggingFace Hub for instructions to access it through the HuggingFace Hub integration with LangChain.
previous
Databerry
next
DeepInfra
Contents
Databricks connector for the SQLDatabase Chain
Databricks-managed MLflow integrates with LangChain
Databricks as an LLM provider
Databricks Dolly
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/databricks.html |
9072d739590d-0 | .md
.pdf
Momento
Contents
Installation and Setup
Cache
Memory
Chat Message History Memory
Momento#
Momento Cache is the world’s first truly serverless caching service. It provides instant elasticity, scale-to-zero
capability, and blazing-fast performance.
With Momento Cache, you grab the SDK, you get an end point, input a few lines into your code, and you’re off and running.
This page covers how to use the Momento ecosystem within LangChain.
Installation and Setup#
Sign up for a free account here and get an auth token
Install the Momento Python SDK with pip install momento
Cache#
The Cache wrapper allows for Momento to be used as a serverless, distributed, low-latency cache for LLM prompts and responses.
The standard cache is the go-to use case for Momento users in any environment.
Import the cache as follows:
from langchain.cache import MomentoCache
And set up like so:
from datetime import timedelta
from momento import CacheClient, Configurations, CredentialProvider
import langchain
# Instantiate the Momento client
cache_client = CacheClient(
Configurations.Laptop.v1(),
CredentialProvider.from_environment_variable("MOMENTO_AUTH_TOKEN"),
default_ttl=timedelta(days=1))
# Choose a Momento cache name of your choice
cache_name = "langchain"
# Instantiate the LLM cache
langchain.llm_cache = MomentoCache(cache_client, cache_name)
Memory#
Momento can be used as a distributed memory store for LLMs.
Chat Message History Memory#
See this notebook for a walkthrough of how to use Momento as a memory store for chat message history.
previous
Modern Treasury
next
MyScale
Contents
Installation and Setup
Cache
Memory
Chat Message History Memory
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/momento.html |
94cc2d9100cf-0 | .md
.pdf
Google Serper
Contents
Setup
Wrappers
Utility
Output
Tool
Google Serper#
This page covers how to use the Serper Google Search API within LangChain. Serper is a low-cost Google Search API that can be used to add answer box, knowledge graph, and organic results data from Google Search.
It is broken into two parts: setup, and then references to the specific Google Serper wrapper.
Setup#
Go to serper.dev to sign up for a free account
Get the api key and set it as an environment variable (SERPER_API_KEY)
Wrappers#
Utility#
There exists a GoogleSerperAPIWrapper utility which wraps this API. To import this utility:
from langchain.utilities import GoogleSerperAPIWrapper
You can use it as part of a Self Ask chain:
from langchain.utilities import GoogleSerperAPIWrapper
from langchain.llms.openai import OpenAI
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
import os
os.environ["SERPER_API_KEY"] = ""
os.environ['OPENAI_API_KEY'] = ""
llm = OpenAI(temperature=0)
search = GoogleSerperAPIWrapper()
tools = [
Tool(
name="Intermediate Answer",
func=search.run,
description="useful for when you need to ask with search"
)
]
self_ask_with_search = initialize_agent(tools, llm, agent=AgentType.SELF_ASK_WITH_SEARCH, verbose=True)
self_ask_with_search.run("What is the hometown of the reigning men's U.S. Open champion?")
Output#
Entering new AgentExecutor chain...
Yes.
Follow up: Who is the reigning men's U.S. Open champion?
Intermediate answer: Current champions Carlos Alcaraz, 2022 men's singles champion.
Follow up: Where is Carlos Alcaraz from?
Intermediate answer: El Palmar, Spain
So the final answer is: El Palmar, Spain
> Finished chain.
'El Palmar, Spain'
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-serper"])
For more information on this, see this page
previous
Google Search
next
Google Vertex AI
Contents
Setup
Wrappers
Utility
Output
Tool
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/google_serper.html |
57ba7dfa9871-0 | .md
.pdf
AZLyrics
Contents
Installation and Setup
Document Loader
AZLyrics#
AZLyrics is a large, legal, every day growing collection of lyrics.
Installation and Setup#
There isn’t any special setup for it.
Document Loader#
See a usage example.
from langchain.document_loaders import AZLyricsLoader
previous
AWS S3 Directory
next
Azure Blob Storage
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/azlyrics.html |
5150c08a5bf8-0 | .md
.pdf
CerebriumAI
Contents
Installation and Setup
Wrappers
LLM
CerebriumAI#
This page covers how to use the CerebriumAI ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific CerebriumAI wrappers.
Installation and Setup#
Install with pip install cerebrium
Get an CerebriumAI api key and set it as an environment variable (CEREBRIUMAI_API_KEY)
Wrappers#
LLM#
There exists an CerebriumAI LLM wrapper, which you can access with
from langchain.llms import CerebriumAI
previous
Cassandra
next
Chroma
Contents
Installation and Setup
Wrappers
LLM
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/cerebriumai.html |
76671a2af3cb-0 | .md
.pdf
Prediction Guard
Contents
Installation and Setup
LLM
Example
Basic usage of the controlled or guarded LLM:
Basic LLM Chaining with the Prediction Guard:
Prediction Guard#
Prediction Guard gives a quick and easy access to state-of-the-art open and closed access LLMs, without needing to spend days and weeks figuring out all of the implementation details, managing a bunch of different API specs, and setting up the infrastructure for model deployments.
Installation and Setup#
Install the Python SDK:
pip install predictionguard
Get an Prediction Guard access token (as described here) and set it as an environment variable (PREDICTIONGUARD_TOKEN)
LLM#
from langchain.llms import PredictionGuard
Example#
You can provide the name of the Prediction Guard model as an argument when initializing the LLM:
pgllm = PredictionGuard(model="MPT-7B-Instruct")
You can also provide your access token directly as an argument:
pgllm = PredictionGuard(model="MPT-7B-Instruct", token="<your access token>")
Also, you can provide an “output” argument that is used to structure/ control the output of the LLM:
pgllm = PredictionGuard(model="MPT-7B-Instruct", output={"type": "boolean"})
Basic usage of the controlled or guarded LLM:#
import os
import predictionguard as pg
from langchain.llms import PredictionGuard
from langchain import PromptTemplate, LLMChain
# Your Prediction Guard API key. Get one at predictionguard.com
os.environ["PREDICTIONGUARD_TOKEN"] = "<your Prediction Guard access token>"
# Define a prompt template
template = """Respond to the following query based on the context.
Context: EVERY comment, DM + email suggestion has led us to this EXCITING announcement! 🎉 We have officially added TWO new candle subscription box options! 📦
Exclusive Candle Box - $80
Monthly Candle Box - $45 (NEW!)
Scent of The Month Box - $28 (NEW!)
Head to stories to get ALLL the deets on each box! 👆 BONUS: Save 50% on your first box with code 50OFF! 🎉
Query: {query}
Result: """
prompt = PromptTemplate(template=template, input_variables=["query"])
# With "guarding" or controlling the output of the LLM. See the
# Prediction Guard docs (https://docs.predictionguard.com) to learn how to
# control the output with integer, float, boolean, JSON, and other types and
# structures.
pgllm = PredictionGuard(model="MPT-7B-Instruct",
output={
"type": "categorical",
"categories": [
"product announcement",
"apology",
"relational"
]
})
pgllm(prompt.format(query="What kind of post is this?"))
Basic LLM Chaining with the Prediction Guard:#
import os
from langchain import PromptTemplate, LLMChain
from langchain.llms import PredictionGuard
# Optional, add your OpenAI API Key. This is optional, as Prediction Guard allows
# you to access all the latest open access models (see https://docs.predictionguard.com)
os.environ["OPENAI_API_KEY"] = "<your OpenAI api key>"
# Your Prediction Guard API key. Get one at predictionguard.com
os.environ["PREDICTIONGUARD_TOKEN"] = "<your Prediction Guard access token>"
pgllm = PredictionGuard(model="OpenAI-text-davinci-003")
template = """Question: {question}
Answer: Let's think step by step."""
prompt = PromptTemplate(template=template, input_variables=["question"])
llm_chain = LLMChain(prompt=prompt, llm=pgllm, verbose=True)
question = "What NFL team won the Super Bowl in the year Justin Beiber was born?"
llm_chain.predict(question=question)
previous
PipelineAI
next
PromptLayer
Contents
Installation and Setup
LLM
Example
Basic usage of the controlled or guarded LLM:
Basic LLM Chaining with the Prediction Guard:
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/predictionguard.html |
caf112407cb1-0 | .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
Spreedly
next
Stripe
Contents
Installation and Setup
Wrappers
LLM
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/stochasticai.html |
d44ab5f12b2b-0 | .md
.pdf
IMSDb
Contents
Installation and Setup
Document Loader
IMSDb#
IMSDb is the Internet Movie Script Database.
Installation and Setup#
There isn’t any special setup for it.
Document Loader#
See a usage example.
from langchain.document_loaders import IMSDbLoader
previous
iFixit
next
Jina
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/imsdb.html |
447ac8f3ee7f-0 | .md
.pdf
Yeager.ai
Contents
What is Yeager.ai?
yAgents
How to use?
Creating and Executing Tools with yAgents
Yeager.ai#
This page covers how to use Yeager.ai to generate LangChain tools and agents.
What is Yeager.ai?#
Yeager.ai is an ecosystem designed to simplify the process of creating AI agents and tools.
It features yAgents, a No-code LangChain Agent Builder, which enables users to build, test, and deploy AI solutions with ease. Leveraging the LangChain framework, yAgents allows seamless integration with various language models and resources, making it suitable for developers, researchers, and AI enthusiasts across diverse applications.
yAgents#
Low code generative agent designed to help you build, prototype, and deploy Langchain tools with ease.
How to use?#
pip install yeagerai-agent
yeagerai-agent
Go to http://127.0.0.1:7860
This will install the necessary dependencies and set up yAgents on your system. After the first run, yAgents will create a .env file where you can input your OpenAI API key. You can do the same directly from the Gradio interface under the tab “Settings”.
OPENAI_API_KEY=<your_openai_api_key_here>
We recommend using GPT-4,. However, the tool can also work with GPT-3 if the problem is broken down sufficiently.
Creating and Executing Tools with yAgents#
yAgents makes it easy to create and execute AI-powered tools. Here’s a brief overview of the process:
Create a tool: To create a tool, provide a natural language prompt to yAgents. The prompt should clearly describe the tool’s purpose and functionality. For example:
create a tool that returns the n-th prime number
Load the tool into the toolkit: To load a tool into yAgents, simply provide a command to yAgents that says so. For example:
load the tool that you just created it into your toolkit
Execute the tool: To run a tool or agent, simply provide a command to yAgents that includes the name of the tool and any required parameters. For example:
generate the 50th prime number
You can see a video of how it works here.
As you become more familiar with yAgents, you can create more advanced tools and agents to automate your work and enhance your productivity.
For more information, see yAgents’ Github or our docs
previous
Writer
next
YouTube
Contents
What is Yeager.ai?
yAgents
How to use?
Creating and Executing Tools with yAgents
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/yeagerai.html |
6390c5d16faa-0 | .md
.pdf
Google Search
Contents
Installation and Setup
Wrappers
Utility
Tool
Google Search#
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
Google Drive
next
Google Serper
Contents
Installation and Setup
Wrappers
Utility
Tool
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/google_search.html |
49115d8715cc-0 | .md
.pdf
Unstructured
Contents
Installation and Setup
Wrappers
Data Loaders
Unstructured#
The unstructured package from
Unstructured.IO extracts clean text from raw source documents like
PDFs and Word documents.
This page covers how to use the unstructured
ecosystem within LangChain.
Installation and Setup#
If you are using a loader that runs locally, use the following steps to get unstructured and
its dependencies running locally.
Install the Python SDK with pip install "unstructured[local-inference]"
Install the following system dependencies if they are not already available on your system.
Depending on what document types you’re parsing, you may not need all of these.
libmagic-dev (filetype detection)
poppler-utils (images and PDFs)
tesseract-ocr(images and PDFs)
libreoffice (MS Office docs)
pandoc (EPUBs)
If you want to get up and running with less set up, you can
simply run pip install unstructured and use UnstructuredAPIFileLoader or
UnstructuredAPIFileIOLoader. That will process your document using the hosted Unstructured API.
Note that currently (as of 1 May 2023) the Unstructured API is open, but it will soon require
an API. The Unstructured documentation page will have
instructions on how to generate an API key once they’re available. Check out the instructions
here
if you’d like to self-host the Unstructured API or run it locally.
Wrappers#
Data Loaders#
The primary unstructured wrappers within langchain are data loaders. The following
shows how to use the most basic unstructured data loader. There are other file-specific
data loaders available in the langchain.document_loaders module.
from langchain.document_loaders import UnstructuredFileLoader
loader = UnstructuredFileLoader("state_of_the_union.txt")
loader.load()
If you instantiate the loader with UnstructuredFileLoader(mode="elements"), the loader
will track additional metadata like the page number and text type (i.e. title, narrative text)
when that information is available.
previous
Twitter
next
Vectara
Contents
Installation and Setup
Wrappers
Data Loaders
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/unstructured.html |
abcd4c9ad83b-0 | .md
.pdf
C Transformers
Contents
Installation and Setup
Wrappers
LLM
C Transformers#
This page covers how to use the C Transformers library within LangChain.
It is broken into two parts: installation and setup, and then references to specific C Transformers wrappers.
Installation and Setup#
Install the Python package with pip install ctransformers
Download a supported GGML model (see Supported Models)
Wrappers#
LLM#
There exists a CTransformers LLM wrapper, which you can access with:
from langchain.llms import CTransformers
It provides a unified interface for all models:
llm = CTransformers(model='/path/to/ggml-gpt-2.bin', model_type='gpt2')
print(llm('AI is going to'))
If you are getting illegal instruction error, try using lib='avx' or lib='basic':
llm = CTransformers(model='/path/to/ggml-gpt-2.bin', model_type='gpt2', lib='avx')
It can be used with models hosted on the Hugging Face Hub:
llm = CTransformers(model='marella/gpt-2-ggml')
If a model repo has multiple model files (.bin files), specify a model file using:
llm = CTransformers(model='marella/gpt-2-ggml', model_file='ggml-model.bin')
Additional parameters can be passed using the config parameter:
config = {'max_new_tokens': 256, 'repetition_penalty': 1.1}
llm = CTransformers(model='marella/gpt-2-ggml', config=config)
See Documentation for a list of available parameters.
For a more detailed walkthrough of this, see this notebook.
previous
Confluence
next
Databerry
Contents
Installation and Setup
Wrappers
LLM
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/ctransformers.html |
a2ff56208256-0 | .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?")
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
SageMaker Endpoint
next
SerpAPI
Contents
Installation and Setup
Self Hosted Instance:
Wrappers
Utility
Tool
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/searx.html |
29fffff30d47-0 | .md
.pdf
Azure Cognitive Search
Contents
Installation and Setup
Retriever
Azure Cognitive Search#
Azure Cognitive Search (formerly known as Azure Search) is a cloud search service that gives developers infrastructure, APIs, and tools for building a rich search experience over private, heterogeneous content in web, mobile, and enterprise applications.
Search is foundational to any app that surfaces text to users, where common scenarios include catalog or document search, online retail apps, or data exploration over proprietary content. When you create a search service, you’ll work with the following capabilities:
A search engine for full text search over a search index containing user-owned content
Rich indexing, with lexical analysis and optional AI enrichment for content extraction and transformation
Rich query syntax for text search, fuzzy search, autocomplete, geo-search and more
Programmability through REST APIs and client libraries in Azure SDKs
Azure integration at the data layer, machine learning layer, and AI (Cognitive Services)
Installation and Setup#
See set up instructions.
Retriever#
See a usage example.
from langchain.retrievers import AzureCognitiveSearchRetriever
previous
Azure Blob Storage
next
Azure OpenAI
Contents
Installation and Setup
Retriever
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/azure_cognitive_search_.html |
c488c68d84de-0 | .md
.pdf
Annoy
Contents
Installation and Setup
Vectorstore
Annoy#
Annoy (Approximate Nearest Neighbors Oh Yeah) is a C++ library with Python bindings to search for points in space that are close to a given query point. It also creates large read-only file-based data structures that are mmapped into memory so that many processes may share the same data.
Installation and Setup#
pip install annoy
Vectorstore#
See a usage example.
from langchain.vectorstores import Annoy
previous
AnalyticDB
next
Anthropic
Contents
Installation and Setup
Vectorstore
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/annoy.html |
3e30e0abb87f-0 | .md
.pdf
Databerry
Contents
Installation and Setup
Retriever
Databerry#
Databerry is an open source document retrieval platform that helps to connect your personal data with Large Language Models.
Installation and Setup#
We need to sign up for Databerry, create a datastore, add some data and get your datastore api endpoint url.
We need the API Key.
Retriever#
See a usage example.
from langchain.retrievers import DataberryRetriever
previous
C Transformers
next
Databricks
Contents
Installation and Setup
Retriever
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/databerry.html |
5e4a53546238-0 | .md
.pdf
Writer
Contents
Installation and Setup
Wrappers
LLM
Writer#
This page covers how to use the Writer ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific Writer wrappers.
Installation and Setup#
Get an Writer api key and set it as an environment variable (WRITER_API_KEY)
Wrappers#
LLM#
There exists an Writer LLM wrapper, which you can access with
from langchain.llms import Writer
previous
Wolfram Alpha
next
Yeager.ai
Contents
Installation and Setup
Wrappers
LLM
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/writer.html |
e81cb2f21d2f-0 | .md
.pdf
Metal
Contents
What is Metal?
Quick start
Metal#
This page covers how to use Metal within LangChain.
What is Metal?#
Metal is a managed retrieval & memory platform built for production. Easily index your data into Metal and run semantic search and retrieval on it.
Quick start#
Get started by creating a Metal account.
Then, you can easily take advantage of the MetalRetriever class to start retrieving your data for semantic search, prompting context, etc. This class takes a Metal instance and a dictionary of parameters to pass to the Metal API.
from langchain.retrievers import MetalRetriever
from metal_sdk.metal import Metal
metal = Metal("API_KEY", "CLIENT_ID", "INDEX_ID");
retriever = MetalRetriever(metal, params={"limit": 2})
docs = retriever.get_relevant_documents("search term")
previous
MediaWikiDump
next
Microsoft OneDrive
Contents
What is Metal?
Quick start
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/metal.html |
27221b9858b0-0 | .md
.pdf
Amazon Bedrock
Contents
Installation and Setup
LLM
Text Embedding Models
Amazon Bedrock#
Amazon Bedrock is a fully managed service that makes FMs from leading AI startups and Amazon available via an API, so you can choose from a wide range of FMs to find the model that is best suited for your use case.
Installation and Setup#
pip install boto3
LLM#
See a usage example.
from langchain import Bedrock
Text Embedding Models#
See a usage example.
from langchain.embeddings import BedrockEmbeddings
previous
Aleph Alpha
next
AnalyticDB
Contents
Installation and Setup
LLM
Text Embedding Models
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/amazon_bedrock.html |
fd2402ca8e9e-0 | .md
.pdf
Jina
Contents
Installation and Setup
Wrappers
Embeddings
Jina#
This page covers how to use the Jina ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific Jina wrappers.
Installation and Setup#
Install the Python SDK with pip install jina
Get a Jina AI Cloud auth token from here and set it as an environment variable (JINA_AUTH_TOKEN)
Wrappers#
Embeddings#
There exists a Jina Embeddings wrapper, which you can access with
from langchain.embeddings import JinaEmbeddings
For a more detailed walkthrough of this, see this notebook
previous
IMSDb
next
LanceDB
Contents
Installation and Setup
Wrappers
Embeddings
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/jina.html |
28d5cab7b551-0 | .md
.pdf
Aleph Alpha
Contents
Installation and Setup
LLM
Text Embedding Models
Aleph Alpha#
Aleph Alpha was founded in 2019 with the mission to research and build the foundational technology for an era of strong AI. The team of international scientists, engineers, and innovators researches, develops, and deploys transformative AI like large language and multimodal models and runs the fastest European commercial AI cluster.
The Luminous series is a family of large language models.
Installation and Setup#
pip install aleph-alpha-client
You have to create a new token. Please, see instructions.
from getpass import getpass
ALEPH_ALPHA_API_KEY = getpass()
LLM#
See a usage example.
from langchain.llms import AlephAlpha
Text Embedding Models#
See a usage example.
from langchain.embeddings import AlephAlphaSymmetricSemanticEmbedding, AlephAlphaAsymmetricSemanticEmbedding
previous
Airbyte
next
Amazon Bedrock
Contents
Installation and Setup
LLM
Text Embedding Models
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/aleph_alpha.html |
79b614e0590a-0 | .md
.pdf
Tensorflow Hub
Contents
Installation and Setup
Text Embedding Models
Tensorflow Hub#
TensorFlow Hub is a repository of trained machine learning models ready for fine-tuning and deployable anywhere.
TensorFlow Hub lets you search and discover hundreds of trained, ready-to-deploy machine learning models in one place.
Installation and Setup#
pip install tensorflow-hub
pip install tensorflow_text
Text Embedding Models#
See a usage example
from langchain.embeddings import TensorflowHubEmbeddings
previous
Telegram
next
2Markdown
Contents
Installation and Setup
Text Embedding Models
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/tensorflow_hub.html |
ba7f13c8b7c3-0 | .md
.pdf
Docugami
Contents
Installation and Setup
Document Loader
Docugami#
Docugami converts business documents into a Document XML Knowledge Graph, generating forests
of XML semantic trees representing entire documents. This is a rich representation that includes the semantic and
structural characteristics of various chunks in the document as an XML tree.
Installation and Setup#
pip install lxml
Document Loader#
See a usage example.
from langchain.document_loaders import DocugamiLoader
previous
Discord
next
DuckDB
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/docugami.html |
552241e22eff-0 | .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 dolly model, click on the API tab. The model name/version would be: "replicate/dolly-v2-12b:ef0e1aefc61f8e096ebe4db6b2bacc297daf2ef6899f0f7e001ec445893500e5"
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="replicate/dolly-v2-12b:ef0e1aefc61f8e096ebe4db6b2bacc297daf2ef6899f0f7e001ec445893500e5")
And run it:
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
Redis
next
Roam
Contents
Installation and Setup
Calling a model
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/replicate.html |
afd2d70a1968-0 | .md
.pdf
Azure OpenAI
Contents
Installation and Setup
LLM
Text Embedding Models
Chat Models
Azure OpenAI#
Microsoft Azure, often referred to as Azure is a cloud computing platform run by Microsoft, which offers access, management, and development of applications and services through global data centers. It provides a range of capabilities, including software as a service (SaaS), platform as a service (PaaS), and infrastructure as a service (IaaS). Microsoft Azure supports many programming languages, tools, and frameworks, including Microsoft-specific and third-party software and systems.
Azure OpenAI is an Azure service with powerful language models from OpenAI including the GPT-3, Codex and Embeddings model series for content generation, summarization, semantic search, and natural language to code translation.
Installation and Setup#
pip install openai
pip install tiktoken
Set the environment variables to get access to the Azure OpenAI service.
import os
os.environ["OPENAI_API_TYPE"] = "azure"
os.environ["OPENAI_API_BASE"] = "https://<your-endpoint.openai.azure.com/"
os.environ["OPENAI_API_KEY"] = "your AzureOpenAI key"
os.environ["OPENAI_API_VERSION"] = "2023-03-15-preview"
LLM#
See a usage example.
from langchain.llms import AzureOpenAI
Text Embedding Models#
See a usage example
from langchain.embeddings import OpenAIEmbeddings
Chat Models#
See a usage example
from langchain.chat_models import AzureChatOpenAI
previous
Azure Cognitive Search
next
Banana
Contents
Installation and Setup
LLM
Text Embedding Models
Chat Models
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/azure_openai.html |
cfdc56482701-0 | .md
.pdf
Modern Treasury
Contents
Installation and Setup
Document Loader
Modern Treasury#
Modern Treasury simplifies complex payment operations. It is a unified platform to power products and processes that move money.
Connect to banks and payment systems
Track transactions and balances in real-time
Automate payment operations for scale
Installation and Setup#
There isn’t any special setup for it.
Document Loader#
See a usage example.
from langchain.document_loaders import ModernTreasuryLoader
previous
Modal
next
Momento
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/modern_treasury.html |
702811d2da3b-0 | .md
.pdf
Vespa
Contents
Installation and Setup
Retriever
Vespa#
Vespa is a fully featured search engine and vector database.
It supports vector search (ANN), lexical search, and search in structured data, all in the same query.
Installation and Setup#
pip install pyvespa
Retriever#
See a usage example.
from langchain.retrievers import VespaRetriever
previous
Vectara
next
Weights & Biases
Contents
Installation and Setup
Retriever
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/vespa.html |
77c2db3e9a27-0 | .md
.pdf
Figma
Contents
Installation and Setup
Document Loader
Figma#
Figma is a collaborative web application for interface design.
Installation and Setup#
The Figma API requires an access token, node_ids, and a file key.
The file key can be pulled from the URL. https://www.figma.com/file/{filekey}/sampleFilename
Node IDs are also available in the URL. Click on anything and look for the ‘?node-id={node_id}’ param.
Access token instructions.
Document Loader#
See a usage example.
from langchain.document_loaders import FigmaFileLoader
previous
Facebook Chat
next
ForefrontAI
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/figma.html |
9f7b8e521734-0 | .md
.pdf
Google Vertex AI
Contents
Installation and Setup
Chat Models
Google Vertex AI#
Vertex AI is a machine learning (ML)
platform that lets you train and deploy ML models and AI applications.
Vertex AI combines data engineering, data science, and ML engineering workflows, enabling your teams to
collaborate using a common toolset.
Installation and Setup#
pip install google-cloud-aiplatform
See the setup instructions
Chat Models#
See a usage example
from langchain.chat_models import ChatVertexAI
previous
Google Serper
next
GooseAI
Contents
Installation and Setup
Chat Models
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/google_vertex_ai.html |
e168f932f995-0 | .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 Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/pgvector.html |
62c3afd30fda-0 | .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]]]
)
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
Azure OpenAI
next
Beam
Contents
Installation and Setup
Define your Banana Template
Build the Banana app
Wrappers
LLM
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/bananadev.html |
cb911550b6dc-0 | .md
.pdf
Microsoft PowerPoint
Contents
Installation and Setup
Document Loader
Microsoft PowerPoint#
Microsoft PowerPoint is a presentation program by Microsoft.
Installation and Setup#
There isn’t any special setup for it.
Document Loader#
See a usage example.
from langchain.document_loaders import UnstructuredPowerPointLoader
previous
Microsoft OneDrive
next
Microsoft Word
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/microsoft_powerpoint.html |
98935f0560d4-0 | .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
Twitter the-algorithm codebase analysis with Deep Lake
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
Diffbot
Contents
Why Deep Lake?
More Resources
Installation and Setup
Wrappers
VectorStore
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/deeplake.html |
680569e5fc8d-0 | .md
.pdf
Cohere
Contents
Installation and Setup
LLM
Text Embedding Model
Retriever
Cohere#
Cohere is a Canadian startup that provides natural language processing models
that help companies improve human-machine interactions.
Installation and Setup#
Install the Python SDK :
pip install cohere
Get a Cohere api key and set it as an environment variable (COHERE_API_KEY)
LLM#
There exists an Cohere LLM wrapper, which you can access with
See a usage example.
from langchain.llms import Cohere
Text Embedding Model#
There exists an Cohere Embedding model, which you can access with
from langchain.embeddings import CohereEmbeddings
For a more detailed walkthrough of this, see this notebook
Retriever#
See a usage example.
from langchain.retrievers.document_compressors import CohereRerank
previous
ClickHouse
next
College Confidential
Contents
Installation and Setup
LLM
Text Embedding Model
Retriever
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/cohere.html |
3544f34b53d1-0 | .md
.pdf
PromptLayer
Contents
Installation and Setup
LLM
Example
Chat Model
PromptLayer#
PromptLayer
is a devtool that allows you to track, manage, and share your GPT prompt engineering.
It acts as a middleware between your code and OpenAI’s python library, recording all your API requests
and saving relevant metadata for easy exploration and search in the PromptLayer dashboard.
Installation and Setup#
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)
LLM#
from langchain.llms import PromptLayerOpenAI
Example#
To tag your requests, use the argument pl_tags when instantiating 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 instantiating 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 instantiating to tag your requests on PromptLayer
you can add return_pl_id when instantiating to return a PromptLayer request id to use while tracking requests.
Chat Model#
from langchain.chat_models import PromptLayerChatOpenAI
See a usage example.
previous
Prediction Guard
next
Psychic
Contents
Installation and Setup
LLM
Example
Chat Model
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/promptlayer.html |
9ca622f60b98-0 | .md
.pdf
ClickHouse
Contents
Installation
Configure clickhouse vector index
Wrappers
VectorStore
ClickHouse#
This page covers how to use ClickHouse Vector Search within LangChain.
ClickHouse is a open source real-time OLAP database with full SQL support and a wide range of functions to assist users in writing analytical queries. Some of these functions and data structures perform distance operations between vectors, enabling ClickHouse to be used as a vector database.
Due to the fully parallelized query pipeline, ClickHouse can process vector search operations very quickly, especially when performing exact matching through a linear scan over all rows, delivering processing speed comparable to dedicated vector databases.
High compression levels, tunable through custom compression codecs, enable very large datasets to be stored and queried. ClickHouse is not memory-bound, allowing multi-TB datasets containing embeddings to be queried.
The capabilities for computing the distance between two vectors are just another SQL function and can be effectively combined with more traditional SQL filtering and aggregation capabilities. This allows vectors to be stored and queried alongside metadata, and even rich text, enabling a broad array of use cases and applications.
Finally, experimental ClickHouse capabilities like Approximate Nearest Neighbour (ANN) indices support faster approximate matching of vectors and provide a promising development aimed to further enhance the vector matching capabilities of ClickHouse.
Installation#
Install clickhouse server by binary or docker image
Install the Python SDK with pip install clickhouse-connect
Configure clickhouse vector index#
Customize ClickhouseSettings object with parameters
```python
from langchain.vectorstores import ClickHouse, ClickhouseSettings
config = ClickhouseSettings(host="<clickhouse-server-host>", port=8123, ...)
index = Clickhouse(embedding_function, config)
index.add_documents(...)
```
Wrappers#
supported functions:
add_texts
add_documents
from_texts
from_documents
similarity_search
asimilarity_search
similarity_search_by_vector
asimilarity_search_by_vector
similarity_search_with_relevance_scores
VectorStore#
There exists a wrapper around open source Clickhouse database, allowing you to use it as a vectorstore,
whether for semantic search or similar example retrieval.
To import this vectorstore:
from langchain.vectorstores import Clickhouse
For a more detailed walkthrough of the MyScale wrapper, see this notebook
previous
ClearML
next
Cohere
Contents
Installation
Configure clickhouse vector index
Wrappers
VectorStore
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/clickhouse.html |
9a73d89e773f-0 | .md
.pdf
Cassandra
Contents
Installation and Setup
Memory
Cassandra#
Cassandra is a free and open-source, distributed, wide-column
store, NoSQL database management system designed to handle large amounts of data across many commodity servers,
providing high availability with no single point of failure. Cassandra offers support for clusters spanning
multiple datacenters, with asynchronous masterless replication allowing low latency operations for all clients.
Cassandra was designed to implement a combination of Amazon's Dynamo distributed storage and replication
techniques combined with Google's Bigtable data and storage engine model.
Installation and Setup#
pip install cassandra-drive
Memory#
See a usage example.
from langchain.memory import CassandraChatMessageHistory
previous
Blackboard
next
CerebriumAI
Contents
Installation and Setup
Memory
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/cassandra.html |
855eb93890c6-0 | .md
.pdf
Stripe
Contents
Installation and Setup
Document Loader
Stripe#
Stripe is an Irish-American financial services and software as a service (SaaS) company. It offers payment-processing software and application programming interfaces for e-commerce websites and mobile applications.
Installation and Setup#
See setup instructions.
Document Loader#
See a usage example.
from langchain.document_loaders import StripeLoader
previous
StochasticAI
next
Tair
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/stripe.html |
3593f33dcb8c-0 | .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
Anyscale
next
Argilla
Contents
Overview
Installation and Setup
Wrappers
Utility
Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/apify.html |
b7e7492049f0-0 | .md
.pdf
Reddit
Contents
Installation and Setup
Document Loader
Reddit#
Reddit is an American social news aggregation, content rating, and discussion website.
Installation and Setup#
First, you need to install a python package.
pip install praw
Make a Reddit Application and initialize the loader with with your Reddit API credentials.
Document Loader#
See a usage example.
from langchain.document_loaders import RedditPostsLoader
previous
Rebuff
next
Redis
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/reddit.html |
d0074fc513d6-0 | .md
.pdf
YouTube
Contents
Installation and Setup
Document Loader
YouTube#
YouTube is an online video sharing and social media platform created by Google.
We download the YouTube transcripts and video information.
Installation and Setup#
pip install youtube-transcript-api
pip install pytube
See a usage example.
Document Loader#
See a usage example.
from langchain.document_loaders import YoutubeLoader
from langchain.document_loaders import GoogleApiYoutubeLoader
previous
Yeager.ai
next
Zep
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/youtube.html |
5934f441bec9-0 | .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):
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
MLflow
next
Modern Treasury
Contents
Installation and Setup
Define your Modal Functions and Webhooks
Wrappers
LLM
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 08, 2023. | https://langchain.readthedocs.io/en/latest/integrations/modal.html |
a0c062c47ffd-0 | .md
.pdf
Quickstart Guide
Contents
Installation
Environment Setup
Building a Language Model Application: LLMs
LLMs: Get predictions from a language model
Prompt Templates: Manage prompts for LLMs
Chains: Combine LLMs and prompts in multi-step workflows
Agents: Dynamically Call Chains Based on User Input
Memory: Add State to Chains and Agents
Building a Language Model Application: Chat Models
Get Message Completions from a Chat Model
Chat Prompt Templates
Chains with Chat Models
Agents with Chat Models
Memory: Add State to Chains and Agents
Quickstart Guide#
This tutorial gives you a quick walkthrough about building an end-to-end language model application with LangChain.
Installation#
To get started, install LangChain with the following command:
pip install langchain
# or
conda install langchain -c conda-forge
Environment Setup#
Using LangChain will usually require integrations with one or more model providers, data stores, apis, etc.
For this example, we will be using OpenAI’s APIs, so we will first need to install their SDK:
pip install openai
We will then need to set the environment variable in the terminal.
export OPENAI_API_KEY="..."
Alternatively, you could do this from inside the Jupyter notebook (or Python script):
import os
os.environ["OPENAI_API_KEY"] = "..."
If you want to set the API key dynamically, you can use the openai_api_key parameter when initiating OpenAI class—for instance, each user’s API key.
from langchain.llms import OpenAI
llm = OpenAI(openai_api_key="OPENAI_API_KEY")
Building a Language Model Application: LLMs#
Now that we have installed LangChain and set up our environment, we can start building our language model application.
LangChain provides many modules that can be used to build language model applications. Modules can be combined to create more complex applications, or be used individually for simple applications.
LLMs: Get predictions from a language model#
The most basic building block of LangChain is calling an LLM on some input.
Let’s walk through a simple example of how to do this.
For this purpose, let’s pretend we are building a service that generates a company name based on what the company makes.
In order to do this, we first need to import the LLM wrapper.
from langchain.llms import OpenAI
We can then initialize the wrapper with any arguments.
In this example, we probably want the outputs to be MORE random, so we’ll initialize it with a HIGH temperature.
llm = OpenAI(temperature=0.9)
We can now call it on some input!
text = "What would be a good company name for a company that makes colorful socks?"
print(llm(text))
Feetful of Fun
For more details on how to use LLMs within LangChain, see the LLM getting started guide.
Prompt Templates: Manage prompts for LLMs#
Calling an LLM is a great first step, but it’s just the beginning.
Normally when you use an LLM in an application, you are not sending user input directly to the LLM.
Instead, you are probably taking user input and constructing a prompt, and then sending that to the LLM.
For example, in the previous example, the text we passed in was hardcoded to ask for a name for a company that made colorful socks.
In this imaginary service, what we would want to do is take only the user input describing what the company does, and then format the prompt with that information.
This is easy to do with LangChain!
First lets define the prompt template:
from langchain.prompts import PromptTemplate
prompt = PromptTemplate(
input_variables=["product"],
template="What is a good name for a company that makes {product}?",
)
Let’s now see how this works! We can call the .format method to format it.
print(prompt.format(product="colorful socks"))
What is a good name for a company that makes colorful socks?
For more details, check out the getting started guide for prompts.
Chains: Combine LLMs and prompts in multi-step workflows#
Up until now, we’ve worked with the PromptTemplate and LLM primitives by themselves. But of course, a real application is not just one primitive, but rather a combination of them.
A chain in LangChain is made up of links, which can be either primitives like LLMs or other chains.
The most core type of chain is an LLMChain, which consists of a PromptTemplate and an LLM. | https://langchain.readthedocs.io/en/latest/getting_started/getting_started.html |
a0c062c47ffd-1 | Extending the previous example, we can construct an LLMChain which takes user input, formats it with a PromptTemplate, and then passes the formatted response to an LLM.
from langchain.prompts import PromptTemplate
from langchain.llms import OpenAI
llm = OpenAI(temperature=0.9)
prompt = PromptTemplate(
input_variables=["product"],
template="What is a good name for a company that makes {product}?",
)
We can now create a very simple chain that will take user input, format the prompt with it, and then send it to the LLM:
from langchain.chains import LLMChain
chain = LLMChain(llm=llm, prompt=prompt)
Now we can run that chain only specifying the product!
chain.run("colorful socks")
# -> '\n\nSocktastic!'
There we go! There’s the first chain - an LLM Chain.
This is one of the simpler types of chains, but understanding how it works will set you up well for working with more complex chains.
For more details, check out the getting started guide for chains.
Agents: Dynamically Call Chains Based on User Input#
So far the chains we’ve looked at run in a predetermined order.
Agents no longer do: they use an LLM to determine which actions to take and in what order. An action can either be using a tool and observing its output, or returning to the user.
When used correctly agents can be extremely powerful. In this tutorial, we show you how to easily use agents through the simplest, highest level API.
In order to load agents, you should understand the following concepts:
Tool: A function that performs a specific duty. This can be things like: Google Search, Database lookup, Python REPL, other chains. The interface for a tool is currently a function that is expected to have a string as an input, with a string as an output.
LLM: The language model powering the agent.
Agent: The agent to use. This should be a string that references a support agent class. Because this notebook focuses on the simplest, highest level API, this only covers using the standard supported agents. If you want to implement a custom agent, see the documentation for custom agents (coming soon).
Agents: For a list of supported agents and their specifications, see here.
Tools: For a list of predefined tools and their specifications, see here.
For this example, you will also need to install the SerpAPI Python package.
pip install google-search-results
And set the appropriate environment variables.
import os
os.environ["SERPAPI_API_KEY"] = "..."
Now we can get started!
from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.llms import OpenAI
# First, let's load the language model we're going to use to control the agent.
llm = OpenAI(temperature=0)
# Next, let's load some tools to use. Note that the `llm-math` tool uses an LLM, so we need to pass that in.
tools = load_tools(["serpapi", "llm-math"], llm=llm)
# Finally, let's initialize an agent with the tools, the language model, and the type of agent we want to use.
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
# Now let's test it out!
agent.run("What was the high temperature in SF yesterday in Fahrenheit? What is that number raised to the .023 power?")
> Entering new AgentExecutor chain...
I need to find the temperature first, then use the calculator to raise it to the .023 power.
Action: Search
Action Input: "High temperature in SF yesterday"
Observation: San Francisco Temperature Yesterday. Maximum temperature yesterday: 57 °F (at 1:56 pm) Minimum temperature yesterday: 49 °F (at 1:56 am) Average temperature ...
Thought: I now have the temperature, so I can use the calculator to raise it to the .023 power.
Action: Calculator
Action Input: 57^.023
Observation: Answer: 1.0974509573251117
Thought: I now know the final answer
Final Answer: The high temperature in SF yesterday in Fahrenheit raised to the .023 power is 1.0974509573251117.
> Finished chain.
Memory: Add State to Chains and Agents# | https://langchain.readthedocs.io/en/latest/getting_started/getting_started.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.