id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
efb94d05503b-1
previous GooseAI next Graphsignal Contents Installation and Setup Usage GPT4All Model File By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/integrations/gpt4all.html
5af0d839d7b8-0
.ipynb .pdf MLflow MLflow# This notebook goes over how to track your LangChain experiments into your MLflow Server !pip install azureml-mlflow !pip install pandas !pip install textstat !pip install spacy !pip install openai !pip install google-search-results !python -m spacy download en_core_web_sm import os os.environ["MLFLOW_TRACKING_URI"] = "" os.environ["OPENAI_API_KEY"] = "" os.environ["SERPAPI_API_KEY"] = "" from langchain.callbacks import MlflowCallbackHandler from langchain.llms import OpenAI """Main function. This function is used to try the callback handler. Scenarios: 1. OpenAI LLM 2. Chain with multiple SubChains on multiple generations 3. Agent with Tools """ mlflow_callback = MlflowCallbackHandler() llm = OpenAI(model_name="gpt-3.5-turbo", temperature=0, callbacks=[mlflow_callback], verbose=True) # SCENARIO 1 - LLM llm_result = llm.generate(["Tell me a joke"]) mlflow_callback.flush_tracker(llm) from langchain.prompts import PromptTemplate from langchain.chains import LLMChain # SCENARIO 2 - Chain template = """You are a playwright. Given the title of play, it is your job to write a synopsis for that title. Title: {title} Playwright: This is a synopsis for the above play:""" prompt_template = PromptTemplate(input_variables=["title"], template=template) synopsis_chain = LLMChain(llm=llm, prompt=prompt_template, callbacks=[mlflow_callback]) test_prompts = [ {
https://python.langchain.com/en/latest/integrations/mlflow_tracking.html
5af0d839d7b8-1
test_prompts = [ { "title": "documentary about good video games that push the boundary of game design" }, ] synopsis_chain.apply(test_prompts) mlflow_callback.flush_tracker(synopsis_chain) from langchain.agents import initialize_agent, load_tools from langchain.agents import AgentType # SCENARIO 3 - Agent with Tools tools = load_tools(["serpapi", "llm-math"], llm=llm, callbacks=[mlflow_callback]) agent = initialize_agent( tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, callbacks=[mlflow_callback], verbose=True, ) agent.run( "Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?" ) mlflow_callback.flush_tracker(agent, finish=True) previous Milvus next Modal By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/integrations/mlflow_tracking.html
4337b932ac0d-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 Docugami next Google Search Contents Installation and Setup Wrappers LLM By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/integrations/forefrontai.html
3ddec5906f42-0
.md .pdf Runhouse Contents Installation and Setup Self-hosted LLMs Self-hosted Embeddings Runhouse# This page covers how to use the Runhouse ecosystem within LangChain. It is broken into three parts: installation and setup, LLMs, and Embeddings. Installation and Setup# Install the Python SDK with pip install runhouse If you’d like to use on-demand cluster, check your cloud credentials with sky check Self-hosted LLMs# For a basic self-hosted LLM, you can use the SelfHostedHuggingFaceLLM class. For more custom LLMs, you can use the SelfHostedPipeline parent class. from langchain.llms import SelfHostedPipeline, SelfHostedHuggingFaceLLM For a more detailed walkthrough of the Self-hosted LLMs, see this notebook Self-hosted Embeddings# There are several ways to use self-hosted embeddings with LangChain via Runhouse. For a basic self-hosted embedding from a Hugging Face Transformers model, you can use the SelfHostedEmbedding class. from langchain.llms import SelfHostedPipeline, SelfHostedHuggingFaceLLM For a more detailed walkthrough of the Self-hosted Embeddings, see this notebook previous Replicate next RWKV-4 Contents Installation and Setup Self-hosted LLMs Self-hosted Embeddings By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/integrations/runhouse.html
757cae7ba2b2-0
.md .pdf Beam Contents Installation and Setup Wrappers LLM Define your Beam app. Deploy your Beam app Call your Beam app Beam# This page covers how to use Beam within LangChain. It is broken into two parts: installation and setup, and then references to specific Beam wrappers. Installation and Setup# Create an account Install the Beam CLI with curl https://raw.githubusercontent.com/slai-labs/get-beam/main/get-beam.sh -sSfL | sh Register API keys with beam configure Set environment variables (BEAM_CLIENT_ID) and (BEAM_CLIENT_SECRET) Install the Beam SDK pip install beam-sdk Wrappers# LLM# There exists a Beam LLM wrapper, which you can access with from langchain.llms.beam import Beam Define your Beam app.# This is the environment you’ll be developing against once you start the app. It’s also used to define the maximum response length from the model. llm = Beam(model_name="gpt2", name="langchain-gpt2-test", cpu=8, memory="32Gi", gpu="A10G", python_version="python3.8", python_packages=[ "diffusers[torch]>=0.10", "transformers", "torch", "pillow", "accelerate", "safetensors", "xformers",], max_length="50", verbose=False) Deploy your Beam app# Once defined, you can deploy your Beam app by calling your model’s _deploy() method. llm._deploy() Call your Beam app# Once a beam model is deployed, it can be called by callying your model’s _call() method.
https://python.langchain.com/en/latest/integrations/beam.html
757cae7ba2b2-1
This returns the GPT2 text response to your prompt. response = llm._call("Running machine learning on a remote GPU") An example script which deploys the model and calls it would be: from langchain.llms.beam import Beam import time llm = Beam(model_name="gpt2", name="langchain-gpt2-test", cpu=8, memory="32Gi", gpu="A10G", python_version="python3.8", python_packages=[ "diffusers[torch]>=0.10", "transformers", "torch", "pillow", "accelerate", "safetensors", "xformers",], max_length="50", verbose=False) llm._deploy() response = llm._call("Running machine learning on a remote GPU") print(response) previous Banana next CerebriumAI Contents Installation and Setup Wrappers LLM Define your Beam app. Deploy your Beam app Call your Beam app By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/integrations/beam.html
14d44c27aa07-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 = VectaraRetriever(vectorstore, alpha=0.025, k=5, filter=None) print(type(vectorstore)) 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
14d44c27aa07-1
qa = ConversationalRetrievalChain.from_llm(llm, retriever, memory=memory) <class 'langchain.vectorstores.vectara.Vectara'> 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, a former top litigator in private practice, and a former federal public defender." 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, a former top litigator in private practice, and a former federal public defender." 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#
https://python.langchain.com/en/latest/integrations/vectara/vectara_chat.html
14d44c27aa07-2
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. 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’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. One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. And 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. A former top litigator in private practice. A former federal public defender.', metadata={'source': '../../modules/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})
https://python.langchain.com/en/latest/integrations/vectara/vectara_chat.html
14d44c27aa07-3
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 did not mention Ketanji Brown Jackson.' 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, 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']
https://python.langchain.com/en/latest/integrations/vectara/vectara_chat.html
14d44c27aa07-4
result = chain({"question": query, "chat_history": chat_history}) result['answer'] ' The president did not mention Ketanji Brown Jackson.\nSOURCES: ../../modules/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 = [] 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, a former top litigator in private practice, and a former federal public defender. chat_history = [(query, result["answer"])]
https://python.langchain.com/en/latest/integrations/vectara/vectara_chat.html
14d44c27aa07-5
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, a former top litigator in private practice, and a former federal public defender." 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 May 28, 2023.
https://python.langchain.com/en/latest/integrations/vectara/vectara_chat.html
9ae3dd258b5a-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 chat_vector_db 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. 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") source_chunks = []
https://python.langchain.com/en/latest/integrations/vectara/vectara_text_generation.html
9ae3dd258b5a-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
9ae3dd258b5a-2
print(chain.apply(inputs)) generate_blog_post("environment variables")
https://python.langchain.com/en/latest/integrations/vectara/vectara_text_generation.html
9ae3dd258b5a-3
[{'text': '\n\nEnvironment variables are an essential part of any development workflow. They provide a way to store and access information that is specific to the environment in which the code is running. This can be especially useful when working with different versions of a language or framework, or when running code on different machines.\n\nThe Deno CLI tasks extension provides a way to easily manage environment variables when running Deno commands. This extension provides a task definition for allowing you to create tasks that execute the `deno` CLI from within the editor. The template for the Deno CLI tasks has the following interface, which can be configured in a `tasks.json` within your workspace:\n\nThe task definition includes the `type` field, which should be set to `deno`, and the `command` field, which is the `deno` command to run (e.g. `run`, `test`, `cache`, etc.). Additionally, you can specify additional arguments to pass on the command line, the current working directory to execute the command, and any environment variables.\n\nUsing environment variables with the
https://python.langchain.com/en/latest/integrations/vectara/vectara_text_generation.html
9ae3dd258b5a-4
and any environment variables.\n\nUsing environment variables with the Deno CLI tasks extension is a great way to ensure that your code is running in the correct environment. For example, if you are running a test suite,'}, {'text': '\n\nEnvironment variables are an important part of any programming language, and they can be used to store and access data in a variety of ways. In this blog post, we\'ll be taking a look at environment variables specifically for the shell.\n\nShell 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\nShell variables can be used to store and access data in a variety of ways. For example, you can use them to store values that you want to re-use, but don\'t want to be available in any spawned processes.\n\nFor example, if you wanted to store a value and then use it in a command, you could do something like this:\n\n```sh\nVAR=hello && echo $VAR && deno eval
https://python.langchain.com/en/latest/integrations/vectara/vectara_text_generation.html
9ae3dd258b5a-5
&& 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\nAs you can see, the value stored in the shell variable is not available in the spawned process.\n\n'}, {'text': '\n\nWhen it comes to developing applications, environment variables are an essential part of the process. Environment variables are used to store information that can be used by applications and scripts to customize their behavior. This is especially important when it comes to developing applications with Deno, as there are several environment variables that can impact the behavior of Deno.\n\nThe most important environment variable for Deno is `DENO_AUTH_TOKENS`. This environment variable is used to store authentication tokens that are used to access remote resources. This is especially important when it comes to accessing remote APIs or databases. Without the proper authentication tokens, Deno will not be able to access the remote resources.\n\nAnother important environment variable for Deno is `DENO_DIR`. This environment variable is used to
https://python.langchain.com/en/latest/integrations/vectara/vectara_text_generation.html
9ae3dd258b5a-6
is `DENO_DIR`. This environment variable is used to store the directory where Deno will store its files. This includes the Deno executable, the Deno cache, and the Deno configuration files. By setting this environment variable, you can ensure that Deno will always be able to find the files it needs.\n\nFinally, there is the `DENO_PLUGINS` environment variable. This environment variable is used to store the list of plugins that Deno will use. This is important for customizing the'}, {'text': '\n\nEnvironment variables are a great way to store and access sensitive information in your Deno applications. Deno offers built-in support for environment variables with `Deno.env`, and you can also use a `.env` file to store and access environment variables. In this blog post, we\'ll explore both of these options and how to use them in your Deno applications.\n\n## Built-in `Deno.env`\n\nThe Deno runtime offers built-in support for environment variables with [`Deno.env`](https://deno.land/[email protected]?s=Deno.env). `Deno.env` has getter and setter methods.
https://python.langchain.com/en/latest/integrations/vectara/vectara_text_generation.html
9ae3dd258b5a-7
`Deno.env` has getter and setter methods. Here is example usage:\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_'}]
https://python.langchain.com/en/latest/integrations/vectara/vectara_text_generation.html
9ae3dd258b5a-8
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 May 28, 2023.
https://python.langchain.com/en/latest/integrations/vectara/vectara_text_generation.html