id
stringlengths 14
16
| text
stringlengths 36
2.73k
| source
stringlengths 49
117
|
---|---|---|
d8afab8de34a-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 11, 2023. | https://python.langchain.com/en/latest/integrations/tair.html |
69477078768c-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"] = "" | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-1 | 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") | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-2 | clearml_callback.flush_tracker(langchain_asset=llm, name="simple_sequential")
{'action': 'on_llm_start', 'name': 'OpenAI', 'step': 3, 'starts': 2, 'ends': 1, 'errors': 0, 'text_ctr': 0, 'chain_starts': 0, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 1, 'llm_streams': 0, 'tool_starts': 0, 'tool_ends': 0, 'agent_ends': 0, 'prompts': 'Tell me a joke'}
{'action': 'on_llm_start', 'name': 'OpenAI', 'step': 3, 'starts': 2, 'ends': 1, 'errors': 0, 'text_ctr': 0, 'chain_starts': 0, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 1, 'llm_streams': 0, 'tool_starts': 0, 'tool_ends': 0, 'agent_ends': 0, 'prompts': 'Tell me a poem'}
{'action': 'on_llm_start', 'name': 'OpenAI', 'step': 3, 'starts': 2, 'ends': 1, 'errors': 0, 'text_ctr': 0, 'chain_starts': 0, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 1, 'llm_streams': 0, 'tool_starts': 0, 'tool_ends': 0, 'agent_ends': 0, 'prompts': 'Tell me a joke'} | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-3 | {'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'} | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-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\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://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-5 | {'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} | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-6 | {'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://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-7 | {'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} | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-8 | {'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://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-9 | {'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 \ | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-10 | 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 | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-11 | 14 on_llm_start OpenAI 3 2 1 0 0 0
15 on_llm_start OpenAI 3 2 1 0 0 0
16 on_llm_start OpenAI 3 2 1 0 0 0
17 on_llm_start OpenAI 3 2 1 0 0 0
18 on_llm_end NaN 4 2 2 0 0 0
19 on_llm_end NaN 4 2 2 0 0 0
20 on_llm_end NaN 4 2 2 0 0 0
21 on_llm_end NaN 4 2 2 0 0 0
22 on_llm_end NaN 4 2 2 0 0 0
23 on_llm_end NaN 4 2 2 0 0 0
chain_ends llm_starts ... difficult_words linsear_write_formula \
0 0 1 ... NaN NaN
1 0 1 ... NaN NaN
2 0 1 ... NaN NaN
3 0 1 ... NaN NaN
4 0 1 ... NaN NaN
5 0 1 ... NaN NaN | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-12 | 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 | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-13 | 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 | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-14 | 21 8.28 6th and 7th grade 115.58 112.37
22 5.20 5th and 6th grade 133.58 131.54
23 8.28 6th and 7th grade 115.58 112.37
gutierrez_polini crawford gulpease_index osman
0 NaN NaN NaN NaN
1 NaN NaN NaN NaN
2 NaN NaN NaN NaN
3 NaN NaN NaN NaN
4 NaN NaN NaN NaN
5 NaN NaN NaN NaN
6 62.30 -0.2 79.8 116.91
7 54.83 1.4 72.1 100.17
8 62.30 -0.2 79.8 116.91
9 54.83 1.4 72.1 100.17
10 62.30 -0.2 79.8 116.91
11 54.83 1.4 72.1 100.17
12 NaN NaN NaN NaN
13 NaN NaN NaN NaN
14 NaN NaN NaN NaN
15 NaN NaN NaN NaN
16 NaN NaN NaN NaN
17 NaN NaN NaN NaN
18 62.30 -0.2 79.8 116.91 | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-15 | 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... | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-16 | 2 \n\nQ: What did the fish say when it hit the w...
3 \n\nRoses are red,\nViolets are blue,\nSugar i...
4 \n\nQ: What did the fish say when it hit the w...
5 \n\nRoses are red,\nViolets are blue,\nSugar i...
6 \n\nQ: What did the fish say when it hit the w...
7 \n\nRoses are red,\nViolets are blue,\nSugar i...
8 \n\nQ: What did the fish say when it hit the w...
9 \n\nRoses are red,\nViolets are blue,\nSugar i...
10 \n\nQ: What did the fish say when it hit the w...
11 \n\nRoses are red,\nViolets are blue,\nSugar i...
token_usage_total_tokens token_usage_prompt_tokens \
0 162 24
1 162 24
2 162 24
3 162 24
4 162 24
5 162 24
6 162 24
7 162 24
8 162 24
9 162 24
10 162 24
11 162 24
token_usage_completion_tokens flesch_reading_ease flesch_kincaid_grade \
0 138 109.04 1.3
1 138 83.66 4.8 | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-17 | 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 | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-18 | 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 | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-19 | crawford gulpease_index osman
0 -0.2 79.8 116.91
1 1.4 72.1 100.17
2 -0.2 79.8 116.91
3 1.4 72.1 100.17
4 -0.2 79.8 116.91
5 1.4 72.1 100.17
6 -0.2 79.8 116.91
7 1.4 72.1 100.17
8 -0.2 79.8 116.91
9 1.4 72.1 100.17
10 -0.2 79.8 116.91
11 1.4 72.1 100.17
[12 rows x 24 columns]}
2023-03-29 14:00:25,948 - clearml.Task - INFO - Completed model upload to https://files.clear.ml/langchain_callback_demo/llm.988bd727b0e94a29a3ac0ee526813545/models/simple_sequential
At this point you can already go to https://app.clear.ml and take a look at the resulting ClearML Task that was created.
Among others, you should see that this notebook is saved along with any git information. The model JSON that contains the used parameters is saved as an artifact, there are also console logs and under the plots section, you’ll find tables that represent the flow of the chain.
Finally, if you enabled visualizations, these are stored as HTML files under debug samples. | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-20 | 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?'} | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-21 | {'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://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-22 | {'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} | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-23 | 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). | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-24 | 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://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-25 | {'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:'} | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-26 | {'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 | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-27 | I need to find out who Bryan Adams is married to.
Action: Search
Action Input: "Who is Bryan Adams married to"{'action': 'on_agent_action', 'tool': 'Search', 'tool_input': 'Who is Bryan Adams married to', 'log': ' I need to find out who Bryan Adams is married to.\nAction: Search\nAction Input: "Who is Bryan Adams married to"', 'step': 9, 'starts': 6, 'ends': 3, 'errors': 0, 'text_ctr': 0, 'chain_starts': 1, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 2, 'llm_streams': 0, 'tool_starts': 3, 'tool_ends': 1, 'agent_ends': 0}
{'action': 'on_tool_start', 'input_str': 'Who is Bryan Adams married to', 'name': 'Search', 'description': 'A search engine. Useful for when you need to answer questions about current events. Input should be a search query.', 'step': 10, 'starts': 7, 'ends': 3, 'errors': 0, 'text_ctr': 0, 'chain_starts': 1, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 2, 'llm_streams': 0, 'tool_starts': 4, 'tool_ends': 1, 'agent_ends': 0}
Observation: Bryan Adams has never married. In the 1990s, he was in a relationship with Danish model Cecilie Thomsen. In 2011, Bryan and Alicia Grimaldi, his ... | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-28 | 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} | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-29 | {'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 | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-30 | 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://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-31 | {'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. | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-32 | 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 | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-33 | 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
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 | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-34 | 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 | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-35 | 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 | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
69477078768c-36 | 2 3rd and 4th grade 115.70 110.84 49.79
crawford gulpease_index osman
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 11, 2023. | https://python.langchain.com/en/latest/integrations/clearml_tracking.html |
65099db541e8-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 11, 2023. | https://python.langchain.com/en/latest/integrations/reddit.html |
246843049ab4-0 | .md
.pdf
PipelineAI
Contents
Installation and Setup
Wrappers
LLM
PipelineAI#
This page covers how to use the PipelineAI ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific PipelineAI wrappers.
Installation and Setup#
Install with pip install pipeline-ai
Get a Pipeline Cloud api key and set it as an environment variable (PIPELINE_API_KEY)
Wrappers#
LLM#
There exists a PipelineAI LLM wrapper, which you can access with
from langchain.llms import PipelineAI
previous
Pinecone
next
Prediction Guard
Contents
Installation and Setup
Wrappers
LLM
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/integrations/pipelineai.html |
8c6feab09f67-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 | https://python.langchain.com/en/latest/integrations/helicone.html |
8c6feab09f67-1 | Quick start
How to enable Helicone caching
How to use Helicone custom properties
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/integrations/helicone.html |
e068e9a43620-0 | .md
.pdf
Pinecone
Contents
Installation and Setup
Vectorstore
Pinecone#
This page covers how to use the Pinecone ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific Pinecone wrappers.
Installation and Setup#
Install the Python SDK:
pip install pinecone-client
Vectorstore#
There exists a wrapper around Pinecone indexes, allowing you to use it as a vectorstore,
whether for semantic search or example selection.
from langchain.vectorstores import Pinecone
For a more detailed walkthrough of the Pinecone vectorstore, see this notebook
previous
PGVector
next
PipelineAI
Contents
Installation and Setup
Vectorstore
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/integrations/pinecone.html |
1b1f044a33f3-0 | .md
.pdf
ForefrontAI
Contents
Installation and Setup
Wrappers
LLM
ForefrontAI#
This page covers how to use the ForefrontAI ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific ForefrontAI wrappers.
Installation and Setup#
Get an ForefrontAI api key and set it as an environment variable (FOREFRONTAI_API_KEY)
Wrappers#
LLM#
There exists an ForefrontAI LLM wrapper, which you can access with
from langchain.llms import ForefrontAI
previous
Figma
next
Git
Contents
Installation and Setup
Wrappers
LLM
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/integrations/forefrontai.html |
c3650930ac7c-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. | https://python.langchain.com/en/latest/integrations/sagemaker_endpoint.html |
c3650930ac7c-1 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/integrations/sagemaker_endpoint.html |
8cbc91e1c2d8-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 11, 2023. | https://python.langchain.com/en/latest/integrations/vespa.html |
085928fae06b-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? | https://python.langchain.com/en/latest/integrations/google_serper.html |
085928fae06b-1 | 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 11, 2023. | https://python.langchain.com/en/latest/integrations/google_serper.html |
08c302b3fe9f-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 11, 2023. | https://python.langchain.com/en/latest/integrations/sklearn.html |
6417bae4b0f6-0 | .md
.pdf
BiliBili
Contents
Installation and Setup
Document Loader
BiliBili#
Bilibili is one of the most beloved long-form video sites in China.
Installation and Setup#
pip install bilibili-api-python
Document Loader#
See a usage example.
from langchain.document_loaders import BiliBiliLoader
previous
Beam
next
Blackboard
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/integrations/bilibili.html |
954ddd48e058-0 | .md
.pdf
Shale Protocol
Contents
How to
1. Find the link to our Discord on https://shaleprotocol.com. Generate an API key through the “Shale Bot” on our Discord. No credit card is required and no free trials. It’s a forever free tier with 1K limit per day per API key.
2. Use https://shale.live/v1 as OpenAI API drop-in replacement
Shale Protocol#
Shale Protocol provides production-ready inference APIs for open LLMs. It’s a Plug & Play API as it’s hosted on a highly scalable GPU cloud infrastructure.
Our free tier supports up to 1K daily requests per key as we want to eliminate the barrier for anyone to start building genAI apps with LLMs.
With Shale Protocol, developers/researchers can create apps and explore the capabilities of open LLMs at no cost.
This page covers how Shale-Serve API can be incorporated with LangChain.
As of June 2023, the API supports Vicuna-13B by default. We are going to support more LLMs such as Falcon-40B in future releases.
How to#
1. Find the link to our Discord on https://shaleprotocol.com. Generate an API key through the “Shale Bot” on our Discord. No credit card is required and no free trials. It’s a forever free tier with 1K limit per day per API key.#
2. Use https://shale.live/v1 as OpenAI API drop-in replacement#
For example
from langchain.llms import OpenAI
from langchain import PromptTemplate, LLMChain
import os
os.environ['OPENAI_API_BASE'] = "https://shale.live/v1"
os.environ['OPENAI_API_KEY'] = "ENTER YOUR API KEY"
llm = OpenAI() | https://python.langchain.com/en/latest/integrations/shaleprotocol.html |
954ddd48e058-1 | llm = OpenAI()
template = """Question: {question}
# Answer: Let's think step by step."""
prompt = PromptTemplate(template=template, input_variables=["question"])
llm_chain = LLMChain(prompt=prompt, llm=llm)
question = "What NFL team won the Super Bowl in the year Justin Beiber was born?"
llm_chain.run(question)
previous
SerpAPI
next
scikit-learn
Contents
How to
1. Find the link to our Discord on https://shaleprotocol.com. Generate an API key through the “Shale Bot” on our Discord. No credit card is required and no free trials. It’s a forever free tier with 1K limit per day per API key.
2. Use https://shale.live/v1 as OpenAI API drop-in replacement
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/integrations/shaleprotocol.html |
656bb0adfdad-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 11, 2023. | https://python.langchain.com/en/latest/integrations/docugami.html |
e7cbceee4805-0 | .md
.pdf
Hacker News
Contents
Installation and Setup
Document Loader
Hacker News#
Hacker News (sometimes abbreviated as HN) is a social news
website focusing on computer science and entrepreneurship. It is run by the investment fund and startup
incubator Y Combinator. In general, content that can be submitted is defined as “anything that gratifies
one’s intellectual curiosity.”
Installation and Setup#
There isn’t any special setup for it.
Document Loader#
See a usage example.
from langchain.document_loaders import HNLoader
previous
Gutenberg
next
Hazy Research
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/integrations/hacker_news.html |
fd9b29364d80-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
AwaDB
next
AZLyrics
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/integrations/aws_s3.html |
382869473311-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 11, 2023. | https://python.langchain.com/en/latest/integrations/psychic.html |
b099f5b6a912-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 11, 2023. | https://python.langchain.com/en/latest/integrations/deeplake.html |
5c0f1bc4c490-0 | .md
.pdf
Anyscale
Contents
Installation and Setup
Wrappers
LLM
Anyscale#
This page covers how to use the Anyscale ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific Anyscale wrappers.
Installation and Setup#
Get an Anyscale Service URL, route and API key and set them as environment variables (ANYSCALE_SERVICE_URL,ANYSCALE_SERVICE_ROUTE, ANYSCALE_SERVICE_TOKEN).
Please see the Anyscale docs for more details.
Wrappers#
LLM#
There exists an Anyscale LLM wrapper, which you can access with
from langchain.llms import Anyscale
previous
Anthropic
next
Apify
Contents
Installation and Setup
Wrappers
LLM
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/integrations/anyscale.html |
362c7858350c-0 | .md
.pdf
2Markdown
Contents
Installation and Setup
Document Loader
2Markdown#
2markdown service transforms website content into structured markdown files.
Installation and Setup#
We need the API key. See instructions how to get it.
Document Loader#
See a usage example.
from langchain.document_loaders import ToMarkdownLoader
previous
Tensorflow Hub
next
Trello
Contents
Installation and Setup
Document Loader
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/integrations/tomarkdown.html |
5b1386047286-0 | .md
.pdf
NLPCloud
Contents
Installation and Setup
Wrappers
LLM
NLPCloud#
This page covers how to use the NLPCloud ecosystem within LangChain.
It is broken into two parts: installation and setup, and then references to specific NLPCloud wrappers.
Installation and Setup#
Install the Python SDK with pip install nlpcloud
Get an NLPCloud api key and set it as an environment variable (NLPCLOUD_API_KEY)
Wrappers#
LLM#
There exists an NLPCloud LLM wrapper, which you can access with
from langchain.llms import NLPCloud
previous
MyScale
next
Notion DB
Contents
Installation and Setup
Wrappers
LLM
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/integrations/nlpcloud.html |
67bc01b3cc54-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 11, 2023. | https://python.langchain.com/en/latest/integrations/pgvector.html |
e0cd19790018-0 | .md
.pdf
AwaDB
Contents
Installation and Setup
VectorStore
AwaDB#
AwaDB is an AI Native database for the search and storage of embedding vectors used by LLM Applications.
Installation and Setup#
pip install awadb
VectorStore#
There exists a wrapper around AwaDB vector databases, allowing you to use it as a vectorstore,
whether for semantic search or example selection.
from langchain.vectorstores import AwaDB
For a more detailed walkthrough of the AwaDB wrapper, see this notebook
previous
AtlasDB
next
AWS S3 Directory
Contents
Installation and Setup
VectorStore
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/integrations/awadb.html |
896e0d10d705-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 11, 2023. | https://python.langchain.com/en/latest/integrations/telegram.html |
26ffc434d3ce-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 11, 2023. | https://python.langchain.com/en/latest/integrations/arxiv.html |
10e07c9f4b58-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 11, 2023. | https://python.langchain.com/en/latest/integrations/annoy.html |
2ffce693ebb0-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 11, 2023. | https://python.langchain.com/en/latest/integrations/trello.html |
2c36e214e143-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 11, 2023. | https://python.langchain.com/en/latest/integrations/google_cloud_storage.html |
74a13aee0346-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 | https://python.langchain.com/en/latest/integrations/ctransformers.html |
74a13aee0346-1 | previous
Confluence
next
Databerry
Contents
Installation and Setup
Wrappers
LLM
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/integrations/ctransformers.html |
6dc6547e61de-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 11, 2023. | https://python.langchain.com/en/latest/integrations/argilla.html |
00f67676305e-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 11, 2023. | https://python.langchain.com/en/latest/integrations/anthropic.html |
637e19acc09b-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 11, 2023. | https://python.langchain.com/en/latest/integrations/microsoft_powerpoint.html |
431ea2a2d048-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 | https://python.langchain.com/en/latest/integrations/rwkv.html |
431ea2a2d048-1 | 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 11, 2023. | https://python.langchain.com/en/latest/integrations/rwkv.html |
4d5e722fe097-0 | .ipynb
.pdf
Databricks
Contents
Installation and Setup
Connecting to Databricks
Syntax
Required Parameters
Optional Parameters
Examples
SQL Chain example
SQL Database Agent example
Databricks#
This notebook covers how to connect to the Databricks runtimes and Databricks SQL using the SQLDatabase wrapper of LangChain.
It is broken into 3 parts: installation and setup, connecting to Databricks, and examples.
Installation and Setup#
!pip install databricks-sql-connector
Connecting to Databricks#
You can connect to Databricks runtimes and Databricks SQL using the SQLDatabase.from_databricks() method.
Syntax#
SQLDatabase.from_databricks(
catalog: str,
schema: str,
host: Optional[str] = None,
api_token: Optional[str] = None,
warehouse_id: Optional[str] = None,
cluster_id: Optional[str] = None,
engine_args: Optional[dict] = None,
**kwargs: Any)
Required Parameters#
catalog: The catalog name in the Databricks database.
schema: The schema name in the catalog.
Optional Parameters#
There following parameters are optional. When executing the method in a Databricks notebook, you don’t need to provide them in most of the cases.
host: The Databricks workspace hostname, excluding ‘https://’ part. Defaults to ‘DATABRICKS_HOST’ environment variable or current workspace if in a Databricks notebook.
api_token: The Databricks personal access token for accessing the Databricks SQL warehouse or the cluster. Defaults to ‘DATABRICKS_TOKEN’ environment variable or a temporary one is generated if in a Databricks notebook.
warehouse_id: The warehouse ID in the Databricks SQL. | https://python.langchain.com/en/latest/integrations/databricks/databricks.html |
4d5e722fe097-1 | warehouse_id: The warehouse ID in the Databricks SQL.
cluster_id: The cluster ID in the Databricks Runtime. If running in a Databricks notebook and both ‘warehouse_id’ and ‘cluster_id’ are None, it uses the ID of the cluster the notebook is attached to.
engine_args: The arguments to be used when connecting Databricks.
**kwargs: Additional keyword arguments for the SQLDatabase.from_uri method.
Examples#
# Connecting to Databricks with SQLDatabase wrapper
from langchain import SQLDatabase
db = SQLDatabase.from_databricks(catalog='samples', schema='nyctaxi')
# Creating a OpenAI Chat LLM wrapper
from langchain.chat_models import ChatOpenAI
llm = ChatOpenAI(temperature=0, model_name="gpt-4")
SQL Chain example#
This example demonstrates the use of the SQL Chain for answering a question over a Databricks database.
from langchain import SQLDatabaseChain
db_chain = SQLDatabaseChain.from_llm(llm, db, verbose=True)
db_chain.run("What is the average duration of taxi rides that start between midnight and 6am?")
> Entering new SQLDatabaseChain chain...
What is the average duration of taxi rides that start between midnight and 6am?
SQLQuery:SELECT AVG(UNIX_TIMESTAMP(tpep_dropoff_datetime) - UNIX_TIMESTAMP(tpep_pickup_datetime)) as avg_duration
FROM trips
WHERE HOUR(tpep_pickup_datetime) >= 0 AND HOUR(tpep_pickup_datetime) < 6
SQLResult: [(987.8122786304605,)]
Answer:The average duration of taxi rides that start between midnight and 6am is 987.81 seconds.
> Finished chain.
'The average duration of taxi rides that start between midnight and 6am is 987.81 seconds.' | https://python.langchain.com/en/latest/integrations/databricks/databricks.html |
4d5e722fe097-2 | SQL Database Agent example#
This example demonstrates the use of the SQL Database Agent for answering questions over a Databricks database.
from langchain.agents import create_sql_agent
from langchain.agents.agent_toolkits import SQLDatabaseToolkit
toolkit = SQLDatabaseToolkit(db=db, llm=llm)
agent = create_sql_agent(
llm=llm,
toolkit=toolkit,
verbose=True
)
agent.run("What is the longest trip distance and how long did it take?")
> Entering new AgentExecutor chain...
Action: list_tables_sql_db
Action Input:
Observation: trips
Thought:I should check the schema of the trips table to see if it has the necessary columns for trip distance and duration.
Action: schema_sql_db
Action Input: trips
Observation:
CREATE TABLE trips (
tpep_pickup_datetime TIMESTAMP,
tpep_dropoff_datetime TIMESTAMP,
trip_distance FLOAT,
fare_amount FLOAT,
pickup_zip INT,
dropoff_zip INT
) USING DELTA
/*
3 rows from trips table:
tpep_pickup_datetime tpep_dropoff_datetime trip_distance fare_amount pickup_zip dropoff_zip
2016-02-14 16:52:13+00:00 2016-02-14 17:16:04+00:00 4.94 19.0 10282 10171
2016-02-04 18:44:19+00:00 2016-02-04 18:46:00+00:00 0.28 3.5 10110 10110 | https://python.langchain.com/en/latest/integrations/databricks/databricks.html |
4d5e722fe097-3 | 2016-02-17 17:13:57+00:00 2016-02-17 17:17:55+00:00 0.7 5.0 10103 10023
*/
Thought:The trips table has the necessary columns for trip distance and duration. I will write a query to find the longest trip distance and its duration.
Action: query_checker_sql_db
Action Input: SELECT trip_distance, tpep_dropoff_datetime - tpep_pickup_datetime as duration FROM trips ORDER BY trip_distance DESC LIMIT 1
Observation: SELECT trip_distance, tpep_dropoff_datetime - tpep_pickup_datetime as duration FROM trips ORDER BY trip_distance DESC LIMIT 1
Thought:The query is correct. I will now execute it to find the longest trip distance and its duration.
Action: query_sql_db
Action Input: SELECT trip_distance, tpep_dropoff_datetime - tpep_pickup_datetime as duration FROM trips ORDER BY trip_distance DESC LIMIT 1
Observation: [(30.6, '0 00:43:31.000000000')]
Thought:I now know the final answer.
Final Answer: The longest trip distance is 30.6 miles and it took 43 minutes and 31 seconds.
> Finished chain.
'The longest trip distance is 30.6 miles and it took 43 minutes and 31 seconds.'
Contents
Installation and Setup
Connecting to Databricks
Syntax
Required Parameters
Optional Parameters
Examples
SQL Chain example
SQL Database Agent example
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/integrations/databricks/databricks.html |
8c361b8d77e0-0 | .ipynb
.pdf
Chat Over Documents with Vectara
Contents
Pass in chat history
Return Source Documents
ConversationalRetrievalChain with search_distance
ConversationalRetrievalChain with map_reduce
ConversationalRetrievalChain with Question Answering with sources
ConversationalRetrievalChain with streaming to stdout
get_chat_history Function
Chat Over Documents with Vectara#
This notebook is based on the chat_vector_db notebook, but using Vectara as the vector database.
import os
from langchain.vectorstores import Vectara
from langchain.vectorstores.vectara import VectaraRetriever
from langchain.llms import OpenAI
from langchain.chains import ConversationalRetrievalChain
Load in documents. You can replace this with a loader for whatever type of data you want
from langchain.document_loaders import TextLoader
loader = TextLoader("../../modules/state_of_the_union.txt")
documents = loader.load()
We now split the documents, create embeddings for them, and put them in a vectorstore. This allows us to do semantic search over them.
vectorstore = Vectara.from_documents(documents, embedding=None)
We can now create a memory object, which is neccessary to track the inputs/outputs and hold a conversation.
from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
We now initialize the ConversationalRetrievalChain
openai_api_key = os.environ['OPENAI_API_KEY']
llm = OpenAI(openai_api_key=openai_api_key, temperature=0)
retriever = vectorstore.as_retriever(lambda_val=0.025, k=5, filter=None)
d = retriever.get_relevant_documents('What did the president say about Ketanji Brown Jackson') | https://python.langchain.com/en/latest/integrations/vectara/vectara_chat.html |
8c361b8d77e0-1 | qa = ConversationalRetrievalChain.from_llm(llm, retriever, memory=memory)
query = "What did the president say about Ketanji Brown Jackson"
result = qa({"question": query})
result["answer"]
" The president said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence."
query = "Did he mention who she suceeded"
result = qa({"question": query})
result['answer']
' Justice Stephen Breyer'
Pass in chat history#
In the above example, we used a Memory object to track chat history. We can also just pass it in explicitly. In order to do this, we need to initialize a chain without any memory object.
qa = ConversationalRetrievalChain.from_llm(OpenAI(temperature=0), vectorstore.as_retriever())
Here’s an example of asking a question with no chat history
chat_history = []
query = "What did the president say about Ketanji Brown Jackson"
result = qa({"question": query, "chat_history": chat_history})
result["answer"]
" The president said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence."
Here’s an example of asking a question with some chat history
chat_history = [(query, result["answer"])]
query = "Did he mention who she suceeded"
result = qa({"question": query, "chat_history": chat_history})
result['answer']
' Justice Stephen Breyer'
Return Source Documents#
You can also easily return source documents from the ConversationalRetrievalChain. This is useful for when you want to inspect what documents were returned. | https://python.langchain.com/en/latest/integrations/vectara/vectara_chat.html |
8c361b8d77e0-2 | qa = ConversationalRetrievalChain.from_llm(llm, vectorstore.as_retriever(), return_source_documents=True)
chat_history = []
query = "What did the president say about Ketanji Brown Jackson"
result = qa({"question": query, "chat_history": chat_history})
result['source_documents'][0]
Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', metadata={'source': '../../../state_of_the_union.txt'})
ConversationalRetrievalChain with search_distance#
If you are using a vector store that supports filtering by search distance, you can add a threshold value parameter.
vectordbkwargs = {"search_distance": 0.9}
qa = ConversationalRetrievalChain.from_llm(OpenAI(temperature=0), vectorstore.as_retriever(), return_source_documents=True)
chat_history = []
query = "What did the president say about Ketanji Brown Jackson"
result = qa({"question": query, "chat_history": chat_history, "vectordbkwargs": vectordbkwargs})
print(result['answer']) | https://python.langchain.com/en/latest/integrations/vectara/vectara_chat.html |
8c361b8d77e0-3 | print(result['answer'])
The president said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence.
ConversationalRetrievalChain with map_reduce#
We can also use different types of combine document chains with the ConversationalRetrievalChain chain.
from langchain.chains import LLMChain
from langchain.chains.question_answering import load_qa_chain
from langchain.chains.conversational_retrieval.prompts import CONDENSE_QUESTION_PROMPT
question_generator = LLMChain(llm=llm, prompt=CONDENSE_QUESTION_PROMPT)
doc_chain = load_qa_chain(llm, chain_type="map_reduce")
chain = ConversationalRetrievalChain(
retriever=vectorstore.as_retriever(),
question_generator=question_generator,
combine_docs_chain=doc_chain,
)
chat_history = []
query = "What did the president say about Ketanji Brown Jackson"
result = chain({"question": query, "chat_history": chat_history})
result['answer']
" The president said that he nominated Circuit Court of Appeals Judge Ketanji Brown Jackson, who he described as one of the nation's top legal minds, to continue Justice Breyer's legacy of excellence."
ConversationalRetrievalChain with Question Answering with sources#
You can also use this chain with the question answering with sources chain.
from langchain.chains.qa_with_sources import load_qa_with_sources_chain
question_generator = LLMChain(llm=llm, prompt=CONDENSE_QUESTION_PROMPT)
doc_chain = load_qa_with_sources_chain(llm, chain_type="map_reduce")
chain = ConversationalRetrievalChain(
retriever=vectorstore.as_retriever(),
question_generator=question_generator, | https://python.langchain.com/en/latest/integrations/vectara/vectara_chat.html |
8c361b8d77e0-4 | retriever=vectorstore.as_retriever(),
question_generator=question_generator,
combine_docs_chain=doc_chain,
)
chat_history = []
query = "What did the president say about Ketanji Brown Jackson"
result = chain({"question": query, "chat_history": chat_history})
result['answer']
" The president said that he nominated Circuit Court of Appeals Judge Ketanji Brown Jackson, who he described as one of the nation's top legal minds, and that she will continue Justice Breyer's legacy of excellence.\nSOURCES: ../../../state_of_the_union.txt"
ConversationalRetrievalChain with streaming to stdout#
Output from the chain will be streamed to stdout token by token in this example.
from langchain.chains.llm import LLMChain
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
from langchain.chains.conversational_retrieval.prompts import CONDENSE_QUESTION_PROMPT, QA_PROMPT
from langchain.chains.question_answering import load_qa_chain
# Construct a ConversationalRetrievalChain with a streaming llm for combine docs
# and a separate, non-streaming llm for question generation
llm = OpenAI(temperature=0, openai_api_key=openai_api_key)
streaming_llm = OpenAI(streaming=True, callbacks=[StreamingStdOutCallbackHandler()], temperature=0, openai_api_key=openai_api_key)
question_generator = LLMChain(llm=llm, prompt=CONDENSE_QUESTION_PROMPT)
doc_chain = load_qa_chain(streaming_llm, chain_type="stuff", prompt=QA_PROMPT)
qa = ConversationalRetrievalChain(
retriever=vectorstore.as_retriever(), combine_docs_chain=doc_chain, question_generator=question_generator)
chat_history = [] | https://python.langchain.com/en/latest/integrations/vectara/vectara_chat.html |
8c361b8d77e0-5 | chat_history = []
query = "What did the president say about Ketanji Brown Jackson"
result = qa({"question": query, "chat_history": chat_history})
The president said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence.
chat_history = [(query, result["answer"])]
query = "Did he mention who she suceeded"
result = qa({"question": query, "chat_history": chat_history})
Justice Stephen Breyer
get_chat_history Function#
You can also specify a get_chat_history function, which can be used to format the chat_history string.
def get_chat_history(inputs) -> str:
res = []
for human, ai in inputs:
res.append(f"Human:{human}\nAI:{ai}")
return "\n".join(res)
qa = ConversationalRetrievalChain.from_llm(llm, vectorstore.as_retriever(), get_chat_history=get_chat_history)
chat_history = []
query = "What did the president say about Ketanji Brown Jackson"
result = qa({"question": query, "chat_history": chat_history})
result['answer']
" The president said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence."
Contents
Pass in chat history
Return Source Documents
ConversationalRetrievalChain with search_distance
ConversationalRetrievalChain with map_reduce
ConversationalRetrievalChain with Question Answering with sources
ConversationalRetrievalChain with streaming to stdout
get_chat_history Function
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/integrations/vectara/vectara_chat.html |
4975365a1e8b-0 | .ipynb
.pdf
Vectara Text Generation
Contents
Prepare Data
Set Up Vector DB
Set Up LLM Chain with Custom Prompt
Generate Text
Vectara Text Generation#
This notebook is based on text generation notebook and adapted to Vectara.
Prepare Data#
First, we prepare the data. For this example, we fetch a documentation site that consists of markdown files hosted on Github and split them into small enough Documents.
import os
from langchain.llms import OpenAI
from langchain.docstore.document import Document
import requests
from langchain.vectorstores import Vectara
from langchain.text_splitter import CharacterTextSplitter
from langchain.prompts import PromptTemplate
import pathlib
import subprocess
import tempfile
def get_github_docs(repo_owner, repo_name):
with tempfile.TemporaryDirectory() as d:
subprocess.check_call(
f"git clone --depth 1 https://github.com/{repo_owner}/{repo_name}.git .",
cwd=d,
shell=True,
)
git_sha = (
subprocess.check_output("git rev-parse HEAD", shell=True, cwd=d)
.decode("utf-8")
.strip()
)
repo_path = pathlib.Path(d)
markdown_files = list(repo_path.glob("*/*.md")) + list(
repo_path.glob("*/*.mdx")
)
for markdown_file in markdown_files:
with open(markdown_file, "r") as f:
relative_path = markdown_file.relative_to(repo_path)
github_url = f"https://github.com/{repo_owner}/{repo_name}/blob/{git_sha}/{relative_path}"
yield Document(page_content=f.read(), metadata={"source": github_url})
sources = get_github_docs("yirenlu92", "deno-manual-forked") | https://python.langchain.com/en/latest/integrations/vectara/vectara_text_generation.html |
4975365a1e8b-1 | source_chunks = []
splitter = CharacterTextSplitter(separator=" ", chunk_size=1024, chunk_overlap=0)
for source in sources:
for chunk in splitter.split_text(source.page_content):
source_chunks.append(chunk)
Cloning into '.'...
Set Up Vector DB#
Now that we have the documentation content in chunks, let’s put all this information in a vector index for easy retrieval.
import os
search_index = Vectara.from_texts(source_chunks, embedding=None)
Set Up LLM Chain with Custom Prompt#
Next, let’s set up a simple LLM chain but give it a custom prompt for blog post generation. Note that the custom prompt is parameterized and takes two inputs: context, which will be the documents fetched from the vector search, and topic, which is given by the user.
from langchain.chains import LLMChain
prompt_template = """Use the context below to write a 400 word blog post about the topic below:
Context: {context}
Topic: {topic}
Blog post:"""
PROMPT = PromptTemplate(
template=prompt_template, input_variables=["context", "topic"]
)
llm = OpenAI(openai_api_key=os.environ['OPENAI_API_KEY'], temperature=0)
chain = LLMChain(llm=llm, prompt=PROMPT)
Generate Text#
Finally, we write a function to apply our inputs to the chain. The function takes an input parameter topic. We find the documents in the vector index that correspond to that topic, and use them as additional context in our simple LLM chain.
def generate_blog_post(topic):
docs = search_index.similarity_search(topic, k=4)
inputs = [{"context": doc.page_content, "topic": topic} for doc in docs]
print(chain.apply(inputs)) | https://python.langchain.com/en/latest/integrations/vectara/vectara_text_generation.html |
4975365a1e8b-2 | print(chain.apply(inputs))
generate_blog_post("environment variables") | https://python.langchain.com/en/latest/integrations/vectara/vectara_text_generation.html |
4975365a1e8b-3 | [{'text': '\n\nEnvironment variables are a powerful tool for managing configuration settings in your applications. They allow you to store and access values from anywhere in your code, making it easier to keep your codebase organized and maintainable.\n\nHowever, there are times when you may want to use environment variables specifically for a single command. This is where shell variables come in. Shell variables are similar to environment variables, but they won\'t be exported to spawned commands. They are defined with the following syntax:\n\n```sh\nVAR_NAME=value\n```\n\nFor example, if you wanted to use a shell variable instead of an environment variable in a command, you could do something like this:\n\n```sh\nVAR=hello && echo $VAR && deno eval "console.log(\'Deno: \' + Deno.env.get(\'VAR\'))"\n```\n\nThis would output the following:\n\n```\nhello\nDeno: undefined\n```\n\nShell variables can be useful when you want to re-use a value, but don\'t want it available in any spawned processes.\n\nAnother way to use environment variables is through pipelines. Pipelines provide a way to pipe the'}, {'text': '\n\nEnvironment variables are a great way to store and access sensitive information in your applications. They are also useful for configuring applications and managing different environments. In Deno, there are two ways to use environment variables: the built-in `Deno.env` and the `.env` file.\n\nThe `Deno.env` is a built-in feature of the Deno runtime that allows you to set and get environment variables. It has getter and setter methods that you can use to access and set environment variables. For example, you can set the `FIREBASE_API_KEY` and `FIREBASE_AUTH_DOMAIN` environment variables like | https://python.langchain.com/en/latest/integrations/vectara/vectara_text_generation.html |
4975365a1e8b-4 | set the `FIREBASE_API_KEY` and `FIREBASE_AUTH_DOMAIN` environment variables like this:\n\n```ts\nDeno.env.set("FIREBASE_API_KEY", "examplekey123");\nDeno.env.set("FIREBASE_AUTH_DOMAIN", "firebasedomain.com");\n\nconsole.log(Deno.env.get("FIREBASE_API_KEY")); // examplekey123\nconsole.log(Deno.env.get("FIREBASE_AUTH_DOMAIN")); // firebasedomain'}, {'text': "\n\nEnvironment variables are a powerful tool for managing configuration and settings in your applications. They allow you to store and access values that can be used in your code, and they can be set and changed without having to modify your code.\n\nIn Deno, environment variables are defined using the `export` command. For example, to set a variable called `VAR_NAME` to the value `value`, you would use the following command:\n\n```sh\nexport VAR_NAME=value\n```\n\nYou can then access the value of the environment variable in your code using the `Deno.env.get()` method. For example, if you wanted to log the value of the `VAR_NAME` variable, you could use the following code:\n\n```js\nconsole.log(Deno.env.get('VAR_NAME'));\n```\n\nYou can also set environment variables for a single command. To do this, you can list the environment variables before the command, like so:\n\n```\nVAR=hello VAR2=bye deno run main.ts\n```\n\nThis will set the environment variables `VAR` and `V"}, {'text': "\n\nEnvironment variables are a powerful tool for managing settings and configuration in your applications. They can be used to store information such as user preferences, application settings, and even passwords. In this blog post, we'll discuss how to make Deno scripts executable with a hashbang | https://python.langchain.com/en/latest/integrations/vectara/vectara_text_generation.html |
4975365a1e8b-5 | In this blog post, we'll discuss how to make Deno scripts executable with a hashbang (shebang).\n\nA hashbang is a line of code that is placed at the beginning of a script. It tells the system which interpreter to use when running the script. In the case of Deno, the hashbang should be `#!/usr/bin/env -S deno run --allow-env`. This tells the system to use the Deno interpreter and to allow the script to access environment variables.\n\nOnce the hashbang is in place, you may need to give the script execution permissions. On Linux, this can be done with the command `sudo chmod +x hashbang.ts`. After that, you can execute the script by calling it like any other command: `./hashbang.ts`.\n\nIn the example program, we give the context permission to access the environment variables and print the Deno installation path. This is done by using the `Deno.env.get()` function, which returns the value of the specified environment"}] | https://python.langchain.com/en/latest/integrations/vectara/vectara_text_generation.html |
4975365a1e8b-6 | Contents
Prepare Data
Set Up Vector DB
Set Up LLM Chain with Custom Prompt
Generate Text
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/integrations/vectara/vectara_text_generation.html |
588714d360f7-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. | https://python.langchain.com/en/latest/getting_started/getting_started.html |
588714d360f7-1 | LangChain provides many modules that can be used to build language model applications. Modules can be combined to create more complex applications, or be used individually for simple applications.
LLMs: Get predictions from a language model#
The most basic building block of LangChain is calling an LLM on some input.
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: | https://python.langchain.com/en/latest/getting_started/getting_started.html |
588714d360f7-2 | This is easy to do with LangChain!
First lets define the prompt template:
from langchain.prompts import PromptTemplate
prompt = PromptTemplate(
input_variables=["product"],
template="What is a good name for a company that makes {product}?",
)
Let’s now see how this works! We can call the .format method to 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.
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") | https://python.langchain.com/en/latest/getting_started/getting_started.html |
588714d360f7-3 | Now we can run that chain only specifying the product!
chain.run("colorful socks")
# -> '\n\nSocktastic!'
There we go! There’s the first chain - an LLM Chain.
This is one of the simpler types of chains, but understanding how it works will set you up well for working with more complex chains.
For more details, check out 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 | https://python.langchain.com/en/latest/getting_started/getting_started.html |
588714d360f7-4 | pip install google-search-results
And set the appropriate environment variables.
import os
os.environ["SERPAPI_API_KEY"] = "..."
Now we can get started!
from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.llms import OpenAI
# First, 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 | https://python.langchain.com/en/latest/getting_started/getting_started.html |
588714d360f7-5 | Thought: I now know the final answer
Final Answer: The high temperature in SF yesterday in Fahrenheit raised to the .023 power is 1.0974509573251117.
> Finished chain.
Memory: Add State to Chains and Agents#
So far, all the chains and agents we’ve gone through have been stateless. But often, you may want a chain or agent to have some concept of “memory” so that it may remember information about its previous interactions. The clearest and simple example of this is when designing a chatbot - you want it to remember previous messages so it can use context from that to have a better conversation. This would be a type of “short-term memory”. On the more complex side, you could imagine a chain/agent remembering key pieces of information over time - this would be a form of “long-term memory”. For more concrete ideas on the latter, see this awesome paper.
LangChain provides several specially created chains just for this purpose. This notebook walks through using one of those chains (the ConversationChain) with two different types of memory.
By default, the ConversationChain has a simple type of memory that remembers all previous inputs/outputs and adds them to the context that is passed. Let’s take a look at using this chain (setting verbose=True so we can see the prompt).
from langchain import OpenAI, ConversationChain
llm = OpenAI(temperature=0)
conversation = ConversationChain(llm=llm, verbose=True)
output = conversation.predict(input="Hi there!")
print(output)
> Entering new chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.
Current conversation:
Human: Hi there!
AI: | https://python.langchain.com/en/latest/getting_started/getting_started.html |
588714d360f7-6 | Current conversation:
Human: Hi there!
AI:
> Finished chain.
' Hello! How are you today?'
output = conversation.predict(input="I'm doing well! Just having a conversation with an AI.")
print(output)
> Entering new chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.
Current conversation:
Human: Hi there!
AI: Hello! How are you today?
Human: I'm doing well! Just having a conversation with an AI.
AI:
> Finished chain.
" That's great! What would you like to talk about?"
Building a Language Model Application: Chat Models#
Similarly, you can use chat models instead of LLMs. Chat models are a variation on language models. While chat models use language models under the hood, the interface they expose is a bit different: rather than expose a “text in, text out” API, they expose an interface where “chat messages” are the inputs and outputs.
Chat model APIs are fairly new, so we are still figuring out the correct abstractions.
Get Message Completions from a Chat Model#
You can get chat completions by passing one or more messages to the chat model. The response will be a message. The types of messages currently supported in LangChain are AIMessage, HumanMessage, SystemMessage, and ChatMessage – ChatMessage takes in an arbitrary role parameter. Most of the time, you’ll just be dealing with HumanMessage, AIMessage, and SystemMessage.
from langchain.chat_models import ChatOpenAI
from langchain.schema import (
AIMessage,
HumanMessage,
SystemMessage
) | https://python.langchain.com/en/latest/getting_started/getting_started.html |
588714d360f7-7 | AIMessage,
HumanMessage,
SystemMessage
)
chat = ChatOpenAI(temperature=0)
You can get completions by passing in a single message.
chat([HumanMessage(content="Translate this sentence from English to French. I love programming.")])
# -> AIMessage(content="J'aime programmer.", additional_kwargs={})
You can also pass in multiple messages for OpenAI’s gpt-3.5-turbo and gpt-4 models.
messages = [
SystemMessage(content="You are a helpful assistant that translates English to French."),
HumanMessage(content="I love programming.")
]
chat(messages)
# -> AIMessage(content="J'aime programmer.", additional_kwargs={})
You can go one step further and generate completions for multiple sets of messages using generate. This returns an LLMResult with an additional message parameter:
batch_messages = [
[
SystemMessage(content="You are a helpful assistant that translates English to French."),
HumanMessage(content="I love programming.")
],
[
SystemMessage(content="You are a helpful assistant that translates English to French."),
HumanMessage(content="I love artificial intelligence.")
],
]
result = chat.generate(batch_messages)
result
# -> LLMResult(generations=[[ChatGeneration(text="J'aime programmer.", generation_info=None, message=AIMessage(content="J'aime programmer.", additional_kwargs={}))], [ChatGeneration(text="J'aime l'intelligence artificielle.", generation_info=None, message=AIMessage(content="J'aime l'intelligence artificielle.", additional_kwargs={}))]], llm_output={'token_usage': {'prompt_tokens': 57, 'completion_tokens': 20, 'total_tokens': 77}})
You can recover things like token usage from this LLMResult: | https://python.langchain.com/en/latest/getting_started/getting_started.html |
Subsets and Splits