prompt
stringlengths
43
25.9k
completion
stringlengths
7
362
api
stringlengths
18
90
get_ipython().run_line_magic('pip', 'install --upgrade --quiet scann') from langchain_community.document_loaders import TextLoader from langchain_community.embeddings import HuggingFaceEmbeddings from langchain_community.vectorstores import ScaNN from langchain_text_splitters import CharacterTextSplitter loader = TextLoader("state_of_the_union.txt") documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) docs = text_splitter.split_documents(documents) embeddings =
HuggingFaceEmbeddings()
langchain_community.embeddings.HuggingFaceEmbeddings
from langchain_community.document_loaders import UnstructuredRSTLoader loader =
UnstructuredRSTLoader(file_path="example_data/README.rst", mode="elements")
langchain_community.document_loaders.UnstructuredRSTLoader
from langchain.prompts import ( ChatPromptTemplate, FewShotChatMessagePromptTemplate, ) examples = [ {"input": "2+2", "output": "4"}, {"input": "2+3", "output": "5"}, ] example_prompt = ChatPromptTemplate.from_messages( [ ("human", "{input}"), ("ai", "{output}"), ] ) few_shot_prompt = FewShotChatMessagePromptTemplate( example_prompt=example_prompt, examples=examples, ) print(few_shot_prompt.format()) final_prompt =
ChatPromptTemplate.from_messages( [ ("system", "You are a wondrous wizard of math.")
langchain.prompts.ChatPromptTemplate.from_messages
get_ipython().run_line_magic('pip', 'install -qU langchain langchain-community') from langchain.chains import LLMChain from langchain.prompts import PromptTemplate from langchain.schema.messages import AIMessage from langchain_community.llms.chatglm3 import ChatGLM3 template = """{question}""" prompt =
PromptTemplate.from_template(template)
langchain.prompts.PromptTemplate.from_template
get_ipython().run_line_magic('pip', "install --upgrade --quiet langchain-openai 'deeplake[enterprise]' tiktoken") from langchain_community.vectorstores import DeepLake from langchain_openai import OpenAIEmbeddings from langchain_text_splitters import CharacterTextSplitter import getpass import os os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:") activeloop_token = getpass.getpass("activeloop token:") embeddings = OpenAIEmbeddings() from langchain_community.document_loaders import TextLoader loader =
TextLoader("../../modules/state_of_the_union.txt")
langchain_community.document_loaders.TextLoader
from langchain_community.document_loaders import OBSDirectoryLoader endpoint = "your-endpoint" config = {"ak": "your-access-key", "sk": "your-secret-key"} loader = OBSDirectoryLoader("your-bucket-name", endpoint=endpoint, config=config) loader.load() loader = OBSDirectoryLoader( "your-bucket-name", endpoint=endpoint, config=config, prefix="test_prefix" ) loader.load() config = {"get_token_from_ecs": True} loader =
OBSDirectoryLoader("your-bucket-name", endpoint=endpoint, config=config)
langchain_community.document_loaders.OBSDirectoryLoader
get_ipython().run_line_magic('pip', 'install --upgrade --quiet boto3 nltk') get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain_experimental') get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain pydantic') import os import boto3 comprehend_client = boto3.client("comprehend", region_name="us-east-1") from langchain_experimental.comprehend_moderation import AmazonComprehendModerationChain comprehend_moderation = AmazonComprehendModerationChain( client=comprehend_client, verbose=True, # optional ) from langchain.prompts import PromptTemplate from langchain_community.llms.fake import FakeListLLM from langchain_experimental.comprehend_moderation.base_moderation_exceptions import ( ModerationPiiError, ) template = """Question: {question} Answer:""" prompt = PromptTemplate.from_template(template) responses = [ "Final Answer: A credit card number looks like 1289-2321-1123-2387. A fake SSN number looks like 323-22-9980. John Doe's phone number is (999)253-9876.", "Final Answer: This is a really <expletive> way of constructing a birdhouse. This is <expletive> insane to think that any birds would actually create their <expletive> nests here.", ] llm = FakeListLLM(responses=responses) chain = ( prompt | comprehend_moderation | {"input": (lambda x: x["output"]) | llm} | comprehend_moderation ) try: response = chain.invoke( { "question": "A sample SSN number looks like this 123-22-3345. Can you give me some more samples?" } ) except ModerationPiiError as e: print(str(e)) else: print(response["output"]) from langchain_experimental.comprehend_moderation import ( BaseModerationConfig, ModerationPiiConfig, ModerationPromptSafetyConfig, ModerationToxicityConfig, ) pii_config = ModerationPiiConfig(labels=["SSN"], redact=True, mask_character="X") toxicity_config = ModerationToxicityConfig(threshold=0.5) prompt_safety_config = ModerationPromptSafetyConfig(threshold=0.5) moderation_config = BaseModerationConfig( filters=[pii_config, toxicity_config, prompt_safety_config] ) comp_moderation_with_config = AmazonComprehendModerationChain( moderation_config=moderation_config, # specify the configuration client=comprehend_client, # optionally pass the Boto3 Client verbose=True, ) from langchain.prompts import PromptTemplate from langchain_community.llms.fake import FakeListLLM template = """Question: {question} Answer:""" prompt = PromptTemplate.from_template(template) responses = [ "Final Answer: A credit card number looks like 1289-2321-1123-2387. A fake SSN number looks like 323-22-9980. John Doe's phone number is (999)253-9876.", "Final Answer: This is a really <expletive> way of constructing a birdhouse. This is <expletive> insane to think that any birds would actually create their <expletive> nests here.", ] llm = FakeListLLM(responses=responses) chain = ( prompt | comp_moderation_with_config | {"input": (lambda x: x["output"]) | llm} | comp_moderation_with_config ) try: response = chain.invoke( { "question": "A sample SSN number looks like this 123-45-7890. Can you give me some more samples?" } ) except Exception as e: print(str(e)) else: print(response["output"]) from langchain_experimental.comprehend_moderation import BaseModerationCallbackHandler class MyModCallback(BaseModerationCallbackHandler): async def on_after_pii(self, output_beacon, unique_id): import json moderation_type = output_beacon["moderation_type"] chain_id = output_beacon["moderation_chain_id"] with open(f"output-{moderation_type}-{chain_id}.json", "w") as file: data = {"beacon_data": output_beacon, "unique_id": unique_id} json.dump(data, file) """ async def on_after_toxicity(self, output_beacon, unique_id): pass async def on_after_prompt_safety(self, output_beacon, unique_id): pass """ my_callback = MyModCallback() pii_config = ModerationPiiConfig(labels=["SSN"], redact=True, mask_character="X") toxicity_config = ModerationToxicityConfig(threshold=0.5) moderation_config = BaseModerationConfig(filters=[pii_config, toxicity_config]) comp_moderation_with_config = AmazonComprehendModerationChain( moderation_config=moderation_config, # specify the configuration client=comprehend_client, # optionally pass the Boto3 Client unique_id="john.doe@email.com", # A unique ID moderation_callback=my_callback, # BaseModerationCallbackHandler verbose=True, ) from langchain.prompts import PromptTemplate from langchain_community.llms.fake import FakeListLLM template = """Question: {question} Answer:""" prompt = PromptTemplate.from_template(template) responses = [ "Final Answer: A credit card number looks like 1289-2321-1123-2387. A fake SSN number looks like 323-22-9980. John Doe's phone number is (999)253-9876.", "Final Answer: This is a really <expletive> way of constructing a birdhouse. This is <expletive> insane to think that any birds would actually create their <expletive> nests here.", ] llm = FakeListLLM(responses=responses) chain = ( prompt | comp_moderation_with_config | {"input": (lambda x: x["output"]) | llm} | comp_moderation_with_config ) try: response = chain.invoke( { "question": "A sample SSN number looks like this 123-456-7890. Can you give me some more samples?" } ) except Exception as e: print(str(e)) else: print(response["output"]) get_ipython().run_line_magic('pip', 'install --upgrade --quiet huggingface_hub') import os os.environ["HUGGINGFACEHUB_API_TOKEN"] = "<YOUR HF TOKEN HERE>" repo_id = "google/flan-t5-xxl" from langchain.prompts import PromptTemplate from langchain_community.llms import HuggingFaceHub template = """{question}""" prompt = PromptTemplate.from_template(template) llm = HuggingFaceHub( repo_id=repo_id, model_kwargs={"temperature": 0.5, "max_length": 256} ) pii_config = ModerationPiiConfig( labels=["SSN", "CREDIT_DEBIT_NUMBER"], redact=True, mask_character="X" ) toxicity_config = ModerationToxicityConfig(threshold=0.5) prompt_safety_config = ModerationPromptSafetyConfig(threshold=0.8) moderation_config_1 = BaseModerationConfig( filters=[pii_config, toxicity_config, prompt_safety_config] ) moderation_config_2 =
BaseModerationConfig(filters=[pii_config])
langchain_experimental.comprehend_moderation.BaseModerationConfig
from langchain.agents import AgentType, initialize_agent from langchain.chains import LLMMathChain from langchain_core.pydantic_v1 import BaseModel, Field from langchain_core.tools import Tool from langchain_openai import ChatOpenAI get_ipython().run_line_magic('pip', 'install --upgrade --quiet numexpr') llm = ChatOpenAI(temperature=0, model="gpt-4") llm_math_chain = LLMMathChain.from_llm(llm=llm, verbose=True) primes = {998: 7901, 999: 7907, 1000: 7919} class CalculatorInput(BaseModel): question: str = Field() class PrimeInput(BaseModel): n: int = Field() def is_prime(n: int) -> bool: if n <= 1 or (n % 2 == 0 and n > 2): return False for i in range(3, int(n**0.5) + 1, 2): if n % i == 0: return False return True def get_prime(n: int, primes: dict = primes) -> str: return str(primes.get(int(n))) async def aget_prime(n: int, primes: dict = primes) -> str: return str(primes.get(int(n))) tools = [ Tool( name="GetPrime", func=get_prime, description="A tool that returns the `n`th prime number", args_schema=PrimeInput, coroutine=aget_prime, ), Tool.from_function( func=llm_math_chain.run, name="Calculator", description="Useful for when you need to compute mathematical expressions", args_schema=CalculatorInput, coroutine=llm_math_chain.arun, ), ] from langchain import hub prompt =
hub.pull("hwchase17/openai-functions-agent")
langchain.hub.pull
get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain nuclia') from langchain_community.vectorstores.nucliadb import NucliaDB API_KEY = "YOUR_API_KEY" ndb =
NucliaDB(knowledge_box="YOUR_KB_ID", local=False, api_key=API_KEY)
langchain_community.vectorstores.nucliadb.NucliaDB
import os os.environ["EXA_API_KEY"] = "..." get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain-exa') get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain langchain-openai') from langchain_core.prompts import PromptTemplate from langchain_core.runnables import RunnableParallel, RunnablePassthrough from langchain_exa import ExaSearchRetriever, TextContentsOptions from langchain_openai import ChatOpenAI retriever = ExaSearchRetriever( k=5, text_contents_options=TextContentsOptions(max_length=200) ) prompt = PromptTemplate.from_template( """Answer the following query based on the following context: query: {query} <context> {context} </context""" ) llm = ChatOpenAI() chain = ( RunnableParallel({"context": retriever, "query": RunnablePassthrough()}) | prompt | llm ) chain.invoke("When is the best time to visit japan?") get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain-exa') from exa_py import Exa from langchain.agents import tool exa = Exa(api_key=os.environ["EXA_API_KEY"]) @tool def search(query: str): """Search for a webpage based on the query.""" return exa.search(f"{query}", use_autoprompt=True, num_results=5) @tool def find_similar(url: str): """Search for webpages similar to a given URL. The url passed in should be a URL returned from `search`. """ return exa.find_similar(url, num_results=5) @tool def get_contents(ids: list[str]): """Get the contents of a webpage. The ids passed in should be a list of ids returned from `search`. """ return exa.get_contents(ids) tools = [search, get_contents, find_similar] from langchain.agents import AgentExecutor, OpenAIFunctionsAgent from langchain_core.messages import SystemMessage from langchain_openai import ChatOpenAI llm = ChatOpenAI(temperature=0) system_message = SystemMessage( content="You are a web researcher who answers user questions by looking up information on the internet and retrieving contents of helpful documents. Cite your sources." ) agent_prompt = OpenAIFunctionsAgent.create_prompt(system_message) agent = OpenAIFunctionsAgent(llm=llm, tools=tools, prompt=agent_prompt) agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True) agent_executor.run("Summarize for me a fascinating article about cats.") from exa_py import Exa from langchain.agents import tool exa = Exa(api_key=os.environ["Exa_API_KEY"]) @tool def search(query: str, include_domains=None, start_published_date=None): """Search for a webpage based on the query. Set the optional include_domains (list[str]) parameter to restrict the search to a list of domains. Set the optional start_published_date (str) parameter to restrict the search to documents published after the date (YYYY-MM-DD). """ return exa.search_and_contents( f"{query}", use_autoprompt=True, num_results=5, include_domains=include_domains, start_published_date=start_published_date, ) @tool def find_similar(url: str): """Search for webpages similar to a given URL. The url passed in should be a URL returned from `search`. """ return exa.find_similar_and_contents(url, num_results=5) @tool def get_contents(ids: list[str]): """Get the contents of a webpage. The ids passed in should be a list of ids returned from `search`. """ return exa.get_contents(ids) tools = [search, get_contents, find_similar] from langchain.agents import AgentExecutor, OpenAIFunctionsAgent from langchain_core.messages import SystemMessage from langchain_openai import ChatOpenAI llm = ChatOpenAI(temperature=0, model="gpt-4") system_message = SystemMessage( content="You are a web researcher who answers user questions by looking up information on the internet and retrieving contents of helpful documents. Cite your sources." ) agent_prompt = OpenAIFunctionsAgent.create_prompt(system_message) agent = OpenAIFunctionsAgent(llm=llm, tools=tools, prompt=agent_prompt) agent_executor =
AgentExecutor(agent=agent, tools=tools, verbose=True)
langchain.agents.AgentExecutor
REGION = "us-central1" # @param {type:"string"} INSTANCE = "test-instance" # @param {type:"string"} DB_USER = "sqlserver" # @param {type:"string"} DB_PASS = "password" # @param {type:"string"} DATABASE = "test" # @param {type:"string"} TABLE_NAME = "test-default" # @param {type:"string"} get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain-google-cloud-sql-mssql') from google.colab import auth auth.authenticate_user() PROJECT_ID = "my-project-id" # @param {type:"string"} get_ipython().system('gcloud config set project {PROJECT_ID}') get_ipython().system('gcloud services enable sqladmin.googleapis.com') from langchain_google_cloud_sql_mssql import MSSQLEngine engine = MSSQLEngine.from_instance( project_id=PROJECT_ID, region=REGION, instance=INSTANCE, database=DATABASE, user=DB_USER, password=DB_PASS, ) engine.init_document_table(TABLE_NAME, overwrite_existing=True) from langchain_core.documents import Document from langchain_google_cloud_sql_mssql import MSSQLDocumentSaver test_docs = [ Document( page_content="Apple Granny Smith 150 0.99 1", metadata={"fruit_id": 1}, ), Document( page_content="Banana Cavendish 200 0.59 0", metadata={"fruit_id": 2}, ), Document( page_content="Orange Navel 80 1.29 1", metadata={"fruit_id": 3}, ), ] saver = MSSQLDocumentSaver(engine=engine, table_name=TABLE_NAME) saver.add_documents(test_docs) from langchain_google_cloud_sql_mssql import MSSQLLoader loader =
MSSQLLoader(engine=engine, table_name=TABLE_NAME)
langchain_google_cloud_sql_mssql.MSSQLLoader
get_ipython().system(' nomic login') get_ipython().system(' nomic login token') get_ipython().system(' pip install -U langchain-nomic langchain_community tiktoken langchain-openai chromadb langchain') import os os.environ["LANGCHAIN_TRACING_V2"] = "true" os.environ["LANGCHAIN_ENDPOINT"] = "https://api.smith.langchain.com" os.environ["LANGCHAIN_API_KEY"] = "api_key" from langchain_community.document_loaders import WebBaseLoader urls = [ "https://lilianweng.github.io/posts/2023-06-23-agent/", "https://lilianweng.github.io/posts/2023-03-15-prompt-engineering/", "https://lilianweng.github.io/posts/2023-10-25-adv-attack-llm/", ] docs = [WebBaseLoader(url).load() for url in urls] docs_list = [item for sublist in docs for item in sublist] from langchain_text_splitters import CharacterTextSplitter text_splitter = CharacterTextSplitter.from_tiktoken_encoder( chunk_size=7500, chunk_overlap=100 ) doc_splits = text_splitter.split_documents(docs_list) import tiktoken encoding = tiktoken.get_encoding("cl100k_base") encoding = tiktoken.encoding_for_model("gpt-3.5-turbo") for d in doc_splits: print("The document is %s tokens" % len(encoding.encode(d.page_content))) import os from langchain_community.vectorstores import Chroma from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables import RunnableLambda, RunnablePassthrough from langchain_nomic import NomicEmbeddings from langchain_nomic.embeddings import NomicEmbeddings vectorstore = Chroma.from_documents( documents=doc_splits, collection_name="rag-chroma", embedding=NomicEmbeddings(model="nomic-embed-text-v1"), ) retriever = vectorstore.as_retriever() from langchain_community.chat_models import ChatOllama from langchain_core.prompts import ChatPromptTemplate from langchain_openai import ChatOpenAI template = """Answer the question based only on the following context: {context} Question: {question} """ prompt = ChatPromptTemplate.from_template(template) model = ChatOpenAI(temperature=0, model="gpt-4-1106-preview") ollama_llm = "mistral:instruct" model_local = ChatOllama(model=ollama_llm) chain = ( {"context": retriever, "question": RunnablePassthrough()} | prompt | model_local |
StrOutputParser()
langchain_core.output_parsers.StrOutputParser
SOURCE = "test" # @param {type:"Query"|"CollectionGroup"|"DocumentReference"|"string"} get_ipython().run_line_magic('pip', 'install -upgrade --quiet langchain-google-firestore') PROJECT_ID = "my-project-id" # @param {type:"string"} get_ipython().system('gcloud config set project {PROJECT_ID}') from google.colab import auth auth.authenticate_user() get_ipython().system('gcloud services enable firestore.googleapis.com') from langchain_core.documents.base import Document from langchain_google_firestore import FirestoreSaver saver = FirestoreSaver() data = [
Document(page_content="Hello, World!")
langchain_core.documents.base.Document
get_ipython().run_line_magic('pip', 'install --upgrade --quiet pygithub') import os from langchain.agents import AgentType, initialize_agent from langchain_community.agent_toolkits.github.toolkit import GitHubToolkit from langchain_community.utilities.github import GitHubAPIWrapper from langchain_openai import ChatOpenAI os.environ["GITHUB_APP_ID"] = "123456" os.environ["GITHUB_APP_PRIVATE_KEY"] = "path/to/your/private-key.pem" os.environ["GITHUB_REPOSITORY"] = "username/repo-name" os.environ["GITHUB_BRANCH"] = "bot-branch-name" os.environ["GITHUB_BASE_BRANCH"] = "main" os.environ["OPENAI_API_KEY"] = "" llm = ChatOpenAI(temperature=0, model="gpt-4-1106-preview") github = GitHubAPIWrapper() toolkit = GitHubToolkit.from_github_api_wrapper(github) tools = toolkit.get_tools() agent = initialize_agent( tools, llm, agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True, ) print("Available tools:") for tool in tools: print("\t" + tool.name) agent.run( "You have the software engineering capabilities of a Google Principle engineer. You are tasked with completing issues on a github repository. Please look at the existing issues and complete them." ) from langchain import hub gh_issue_prompt_template = hub.pull("kastanday/new-github-issue") print(gh_issue_prompt_template.template) def format_issue(issue): title = f"Title: {issue.get('title')}." opened_by = f"Opened by user: {issue.get('opened_by')}" body = f"Body: {issue.get('body')}" comments = issue.get("comments") # often too long return "\n".join([title, opened_by, body]) issue = github.get_issue(33) # task to implement a RNA-seq pipeline (bioinformatics) final_gh_issue_prompt = gh_issue_prompt_template.format( issue_description=format_issue(issue) ) print(final_gh_issue_prompt) from langchain.memory.summary_buffer import ConversationSummaryBufferMemory from langchain_core.prompts.chat import MessagesPlaceholder summarizer_llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo") # type: ignore chat_history = MessagesPlaceholder(variable_name="chat_history") memory = ConversationSummaryBufferMemory( memory_key="chat_history", return_messages=True, llm=summarizer_llm, max_token_limit=2_000, ) agent = initialize_agent( tools, llm, agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True, handle_parsing_errors=True, # or pass a function that accepts the error and returns a string max_iterations=30, max_execution_time=None, early_stopping_method="generate", memory=memory, agent_kwargs={ "memory_prompts": [chat_history], "input_variables": ["input", "agent_scratchpad", "chat_history"], "prefix": final_gh_issue_prompt, }, ) from langchain_core.tracers.context import tracing_v2_enabled os.environ["LANGCHAIN_TRACING_V2"] = "true" os.environ["LANGCHAIN_ENDPOINT"] = "https://api.smith.langchain.com" os.environ["LANGCHAIN_API_KEY"] = "ls__......" os.environ["LANGCHAIN_PROJECT"] = "Github_Demo_PR" os.environ["LANGCHAIN_WANDB_TRACING"] = "false" with tracing_v2_enabled(project_name="Github_Demo_PR", tags=["PR_bot"]) as cb: agent.run(final_gh_issue_prompt) from langchain.tools.render import render_text_description_and_args print(render_text_description_and_args(tools)) get_ipython().run_line_magic('pip', 'install --upgrade --quiet duckduckgo-search') from langchain.agents import Tool from langchain.tools import DuckDuckGoSearchRun from langchain_openai import ChatOpenAI tools = [] unwanted_tools = ["Get Issue", "Delete File", "Create File", "Create Pull Request"] for tool in toolkit.get_tools(): if tool.name not in unwanted_tools: tools.append(tool) tools += [ Tool( name="Search", func=DuckDuckGoSearchRun().run, description="useful for when you need to search the web", ) ] agent = initialize_agent( tools=tools, llm=
ChatOpenAI(temperature=0.1)
langchain_openai.ChatOpenAI
from langchain import hub from langchain.agents import AgentExecutor, create_openai_functions_agent from langchain_community.tools import WikipediaQueryRun from langchain_community.utilities import WikipediaAPIWrapper from langchain_openai import ChatOpenAI api_wrapper = WikipediaAPIWrapper(top_k_results=1, doc_content_chars_max=100) tool = WikipediaQueryRun(api_wrapper=api_wrapper) tools = [tool] prompt =
hub.pull("hwchase17/openai-functions-agent")
langchain.hub.pull
from langchain_community.vectorstores import Bagel texts = ["hello bagel", "hello langchain", "I love salad", "my car", "a dog"] cluster = Bagel.from_texts(cluster_name="testing", texts=texts) cluster.similarity_search("bagel", k=3) cluster.similarity_search_with_score("bagel", k=3) cluster.delete_cluster() from langchain_community.document_loaders import TextLoader from langchain_text_splitters import CharacterTextSplitter loader = TextLoader("../../modules/state_of_the_union.txt") documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) docs = text_splitter.split_documents(documents)[:10] cluster = Bagel.from_documents(cluster_name="testing_with_docs", documents=docs) query = "What did the president say about Ketanji Brown Jackson" docs = cluster.similarity_search(query) print(docs[0].page_content[:102]) texts = ["hello bagel", "this is langchain"] cluster = Bagel.from_texts(cluster_name="testing", texts=texts) cluster_data = cluster.get() cluster_data.keys() cluster_data cluster.delete_cluster() texts = ["hello bagel", "this is langchain"] metadatas = [{"source": "notion"}, {"source": "google"}] cluster =
Bagel.from_texts(cluster_name="testing", texts=texts, metadatas=metadatas)
langchain_community.vectorstores.Bagel.from_texts
get_ipython().run_line_magic('pip', 'install --upgrade --quiet amadeus > /dev/null') import os os.environ["AMADEUS_CLIENT_ID"] = "CLIENT_ID" os.environ["AMADEUS_CLIENT_SECRET"] = "CLIENT_SECRET" os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY" from langchain_community.agent_toolkits.amadeus.toolkit import AmadeusToolkit toolkit = AmadeusToolkit() tools = toolkit.get_tools() from langchain_community.llms import HuggingFaceHub os.environ["HUGGINGFACEHUB_API_TOKEN"] = "YOUR_HF_API_TOKEN" llm = HuggingFaceHub( repo_id="tiiuae/falcon-7b-instruct", model_kwargs={"temperature": 0.5, "max_length": 64}, ) toolkit_hf =
AmadeusToolkit(llm=llm)
langchain_community.agent_toolkits.amadeus.toolkit.AmadeusToolkit
meals = [ "Beef Enchiladas with Feta cheese. Mexican-Greek fusion", "Chicken Flatbreads with red sauce. Italian-Mexican fusion", "Veggie sweet potato quesadillas with vegan cheese", "One-Pan Tortelonni bake with peppers and onions", ] from langchain_openai import OpenAI llm = OpenAI(model="gpt-3.5-turbo-instruct") from langchain.prompts import PromptTemplate PROMPT_TEMPLATE = """Here is the description of a meal: "{meal}". Embed the meal into the given text: "{text_to_personalize}". Prepend a personalized message including the user's name "{user}" and their preference "{preference}". Make it sound good. """ PROMPT = PromptTemplate( input_variables=["meal", "text_to_personalize", "user", "preference"], template=PROMPT_TEMPLATE, ) import langchain_experimental.rl_chain as rl_chain chain = rl_chain.PickBest.from_llm(llm=llm, prompt=PROMPT) response = chain.run( meal=rl_chain.ToSelectFrom(meals), user=rl_chain.BasedOn("Tom"), preference=rl_chain.BasedOn(["Vegetarian", "regular dairy is ok"]), text_to_personalize="This is the weeks specialty dish, our master chefs \ believe you will love it!", ) print(response["response"]) for _ in range(5): try: response = chain.run( meal=rl_chain.ToSelectFrom(meals), user=rl_chain.BasedOn("Tom"), preference=rl_chain.BasedOn(["Vegetarian", "regular dairy is ok"]), text_to_personalize="This is the weeks specialty dish, our master chefs believe you will love it!", ) except Exception as e: print(e) print(response["response"]) print() scoring_criteria_template = ( "Given {preference} rank how good or bad this selection is {meal}" ) chain = rl_chain.PickBest.from_llm( llm=llm, prompt=PROMPT, selection_scorer=rl_chain.AutoSelectionScorer( llm=llm, scoring_criteria_template_str=scoring_criteria_template ), ) response = chain.run( meal=rl_chain.ToSelectFrom(meals), user=rl_chain.BasedOn("Tom"), preference=rl_chain.BasedOn(["Vegetarian", "regular dairy is ok"]), text_to_personalize="This is the weeks specialty dish, our master chefs believe you will love it!", ) print(response["response"]) selection_metadata = response["selection_metadata"] print( f"selected index: {selection_metadata.selected.index}, score: {selection_metadata.selected.score}" ) class CustomSelectionScorer(rl_chain.SelectionScorer): def score_response( self, inputs, llm_response: str, event: rl_chain.PickBestEvent ) -> float: print(event.based_on) print(event.to_select_from) selected_meal = event.to_select_from["meal"][event.selected.index] print(f"selected meal: {selected_meal}") if "Tom" in event.based_on["user"]: if "Vegetarian" in event.based_on["preference"]: if "Chicken" in selected_meal or "Beef" in selected_meal: return 0.0 else: return 1.0 else: if "Chicken" in selected_meal or "Beef" in selected_meal: return 1.0 else: return 0.0 else: raise NotImplementedError("I don't know how to score this user") chain = rl_chain.PickBest.from_llm( llm=llm, prompt=PROMPT, selection_scorer=CustomSelectionScorer(), ) response = chain.run( meal=rl_chain.ToSelectFrom(meals), user=rl_chain.BasedOn("Tom"), preference=rl_chain.BasedOn(["Vegetarian", "regular dairy is ok"]), text_to_personalize="This is the weeks specialty dish, our master chefs believe you will love it!", ) class CustomSelectionScorer(rl_chain.SelectionScorer): def score_preference(self, preference, selected_meal): if "Vegetarian" in preference: if "Chicken" in selected_meal or "Beef" in selected_meal: return 0.0 else: return 1.0 else: if "Chicken" in selected_meal or "Beef" in selected_meal: return 1.0 else: return 0.0 def score_response( self, inputs, llm_response: str, event: rl_chain.PickBestEvent ) -> float: selected_meal = event.to_select_from["meal"][event.selected.index] if "Tom" in event.based_on["user"]: return self.score_preference(event.based_on["preference"], selected_meal) elif "Anna" in event.based_on["user"]: return self.score_preference(event.based_on["preference"], selected_meal) else: raise NotImplementedError("I don't know how to score this user") chain = rl_chain.PickBest.from_llm( llm=llm, prompt=PROMPT, selection_scorer=CustomSelectionScorer(), metrics_step=5, metrics_window_size=5, # rolling window average ) random_chain = rl_chain.PickBest.from_llm( llm=llm, prompt=PROMPT, selection_scorer=CustomSelectionScorer(), metrics_step=5, metrics_window_size=5, # rolling window average policy=rl_chain.PickBestRandomPolicy, # set the random policy instead of default ) for _ in range(20): try: chain.run( meal=rl_chain.ToSelectFrom(meals), user=rl_chain.BasedOn("Tom"), preference=rl_chain.BasedOn(["Vegetarian", "regular dairy is ok"]), text_to_personalize="This is the weeks specialty dish, our master chefs believe you will love it!", ) random_chain.run( meal=
rl_chain.ToSelectFrom(meals)
langchain_experimental.rl_chain.ToSelectFrom
from langchain_community.utils.openai_functions import ( convert_pydantic_to_openai_function, ) from langchain_core.prompts import ChatPromptTemplate from langchain_core.pydantic_v1 import BaseModel, Field, validator from langchain_openai import ChatOpenAI class Joke(BaseModel): """Joke to tell user.""" setup: str = Field(description="question to set up a joke") punchline: str = Field(description="answer to resolve the joke") openai_functions = [convert_pydantic_to_openai_function(Joke)] model = ChatOpenAI(temperature=0) prompt = ChatPromptTemplate.from_messages( [("system", "You are helpful assistant"), ("user", "{input}")] ) from langchain.output_parsers.openai_functions import JsonOutputFunctionsParser parser = JsonOutputFunctionsParser() chain = prompt | model.bind(functions=openai_functions) | parser chain.invoke({"input": "tell me a joke"}) for s in chain.stream({"input": "tell me a joke"}): print(s) from typing import List from langchain.output_parsers.openai_functions import JsonKeyOutputFunctionsParser class Jokes(BaseModel): """Jokes to tell user.""" joke: List[Joke] funniness_level: int parser = JsonKeyOutputFunctionsParser(key_name="joke") openai_functions = [convert_pydantic_to_openai_function(Jokes)] chain = prompt | model.bind(functions=openai_functions) | parser chain.invoke({"input": "tell me two jokes"}) for s in chain.stream({"input": "tell me two jokes"}): print(s) from langchain.output_parsers.openai_functions import PydanticOutputFunctionsParser class Joke(BaseModel): """Joke to tell user.""" setup: str = Field(description="question to set up a joke") punchline: str = Field(description="answer to resolve the joke") @validator("setup") def question_ends_with_question_mark(cls, field): if field[-1] != "?": raise ValueError("Badly formed question!") return field parser =
PydanticOutputFunctionsParser(pydantic_schema=Joke)
langchain.output_parsers.openai_functions.PydanticOutputFunctionsParser
get_ipython().run_line_magic('pip', 'install --upgrade --quiet slack_sdk > /dev/null') get_ipython().run_line_magic('pip', 'install --upgrade --quiet beautifulsoup4 > /dev/null # This is optional but is useful for parsing HTML messages') get_ipython().run_line_magic('pip', 'install --upgrade --quiet python-dotenv > /dev/null # This is for loading environmental variables from a .env file') import dotenv dotenv.load_dotenv() from langchain_community.agent_toolkits import SlackToolkit toolkit = SlackToolkit() tools = toolkit.get_tools() tools from langchain import hub from langchain.agents import AgentExecutor, create_react_agent from langchain_openai import ChatOpenAI llm = ChatOpenAI(temperature=0, model="gpt-4") prompt =
hub.pull("hwchase17/react")
langchain.hub.pull
from langchain.chains import LLMSummarizationCheckerChain from langchain_openai import OpenAI llm = OpenAI(temperature=0) checker_chain = LLMSummarizationCheckerChain.from_llm(llm, verbose=True, max_checks=2) text = """ Your 9-year old might like these recent discoveries made by The James Webb Space Telescope (JWST): • In 2023, The JWST spotted a number of galaxies nicknamed "green peas." They were given this name because they are small, round, and green, like peas. • The telescope captured images of galaxies that are over 13 billion years old. This means that the light from these galaxies has been traveling for over 13 billion years to reach us. • JWST took the very first pictures of a planet outside of our own solar system. These distant worlds are called "exoplanets." Exo means "from outside." These discoveries can spark a child's imagination about the infinite wonders of the universe.""" checker_chain.run(text) from langchain.chains import LLMSummarizationCheckerChain from langchain_openai import OpenAI llm =
OpenAI(temperature=0)
langchain_openai.OpenAI
get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain-nvidia-ai-endpoints') import getpass import os if not os.environ.get("NVIDIA_API_KEY", "").startswith("nvapi-"): nvapi_key = getpass.getpass("Enter your NVIDIA API key: ") assert nvapi_key.startswith("nvapi-"), f"{nvapi_key[:5]}... is not a valid key" os.environ["NVIDIA_API_KEY"] = nvapi_key from langchain_nvidia_ai_endpoints import ChatNVIDIA llm =
ChatNVIDIA(model="mixtral_8x7b")
langchain_nvidia_ai_endpoints.ChatNVIDIA
get_ipython().system(' pip install -U langchain openai chromadb langchain-experimental # (newest versions required for multi-modal)') get_ipython().system(' pip install "unstructured[all-docs]" pillow pydantic lxml pillow matplotlib chromadb tiktoken') from langchain_text_splitters import CharacterTextSplitter from unstructured.partition.pdf import partition_pdf def extract_pdf_elements(path, fname): """ Extract images, tables, and chunk text from a PDF file. path: File path, which is used to dump images (.jpg) fname: File name """ return partition_pdf( filename=path + fname, extract_images_in_pdf=False, infer_table_structure=True, chunking_strategy="by_title", max_characters=4000, new_after_n_chars=3800, combine_text_under_n_chars=2000, image_output_dir_path=path, ) def categorize_elements(raw_pdf_elements): """ Categorize extracted elements from a PDF into tables and texts. raw_pdf_elements: List of unstructured.documents.elements """ tables = [] texts = [] for element in raw_pdf_elements: if "unstructured.documents.elements.Table" in str(type(element)): tables.append(str(element)) elif "unstructured.documents.elements.CompositeElement" in str(type(element)): texts.append(str(element)) return texts, tables fpath = "/Users/rlm/Desktop/cj/" fname = "cj.pdf" raw_pdf_elements = extract_pdf_elements(fpath, fname) texts, tables = categorize_elements(raw_pdf_elements) text_splitter = CharacterTextSplitter.from_tiktoken_encoder( chunk_size=4000, chunk_overlap=0 ) joined_texts = " ".join(texts) texts_4k_token = text_splitter.split_text(joined_texts) from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_openai import ChatOpenAI def generate_text_summaries(texts, tables, summarize_texts=False): """ Summarize text elements texts: List of str tables: List of str summarize_texts: Bool to summarize texts """ prompt_text = """You are an assistant tasked with summarizing tables and text for retrieval. \ These summaries will be embedded and used to retrieve the raw text or table elements. \ Give a concise summary of the table or text that is well optimized for retrieval. Table or text: {element} """ prompt = ChatPromptTemplate.from_template(prompt_text) model = ChatOpenAI(temperature=0, model="gpt-4") summarize_chain = {"element": lambda x: x} | prompt | model | StrOutputParser() text_summaries = [] table_summaries = [] if texts and summarize_texts: text_summaries = summarize_chain.batch(texts, {"max_concurrency": 5}) elif texts: text_summaries = texts if tables: table_summaries = summarize_chain.batch(tables, {"max_concurrency": 5}) return text_summaries, table_summaries text_summaries, table_summaries = generate_text_summaries( texts_4k_token, tables, summarize_texts=True ) import base64 import os from langchain_core.messages import HumanMessage def encode_image(image_path): """Getting the base64 string""" with open(image_path, "rb") as image_file: return base64.b64encode(image_file.read()).decode("utf-8") def image_summarize(img_base64, prompt): """Make image summary""" chat = ChatOpenAI(model="gpt-4-vision-preview", max_tokens=1024) msg = chat.invoke( [ HumanMessage( content=[ {"type": "text", "text": prompt}, { "type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{img_base64}"}, }, ] ) ] ) return msg.content def generate_img_summaries(path): """ Generate summaries and base64 encoded strings for images path: Path to list of .jpg files extracted by Unstructured """ img_base64_list = [] image_summaries = [] prompt = """You are an assistant tasked with summarizing images for retrieval. \ These summaries will be embedded and used to retrieve the raw image. \ Give a concise summary of the image that is well optimized for retrieval.""" for img_file in sorted(os.listdir(path)): if img_file.endswith(".jpg"): img_path = os.path.join(path, img_file) base64_image = encode_image(img_path) img_base64_list.append(base64_image) image_summaries.append(image_summarize(base64_image, prompt)) return img_base64_list, image_summaries img_base64_list, image_summaries = generate_img_summaries(fpath) import uuid from langchain.retrievers.multi_vector import MultiVectorRetriever from langchain.storage import InMemoryStore from langchain_community.vectorstores import Chroma from langchain_core.documents import Document from langchain_openai import OpenAIEmbeddings def create_multi_vector_retriever( vectorstore, text_summaries, texts, table_summaries, tables, image_summaries, images ): """ Create retriever that indexes summaries, but returns raw images or texts """ store = InMemoryStore() id_key = "doc_id" retriever = MultiVectorRetriever( vectorstore=vectorstore, docstore=store, id_key=id_key, ) def add_documents(retriever, doc_summaries, doc_contents): doc_ids = [str(uuid.uuid4()) for _ in doc_contents] summary_docs = [ Document(page_content=s, metadata={id_key: doc_ids[i]}) for i, s in enumerate(doc_summaries) ] retriever.vectorstore.add_documents(summary_docs) retriever.docstore.mset(list(zip(doc_ids, doc_contents))) if text_summaries: add_documents(retriever, text_summaries, texts) if table_summaries: add_documents(retriever, table_summaries, tables) if image_summaries: add_documents(retriever, image_summaries, images) return retriever vectorstore = Chroma( collection_name="mm_rag_cj_blog", embedding_function=OpenAIEmbeddings() ) retriever_multi_vector_img = create_multi_vector_retriever( vectorstore, text_summaries, texts, table_summaries, tables, image_summaries, img_base64_list, ) import io import re from IPython.display import HTML, display from langchain_core.runnables import RunnableLambda, RunnablePassthrough from PIL import Image def plt_img_base64(img_base64): """Disply base64 encoded string as image""" image_html = f'<img src="data:image/jpeg;base64,{img_base64}" />' display(HTML(image_html)) def looks_like_base64(sb): """Check if the string looks like base64""" return re.match("^[A-Za-z0-9+/]+[=]{0,2}$", sb) is not None def is_image_data(b64data): """ Check if the base64 data is an image by looking at the start of the data """ image_signatures = { b"\xFF\xD8\xFF": "jpg", b"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A": "png", b"\x47\x49\x46\x38": "gif", b"\x52\x49\x46\x46": "webp", } try: header = base64.b64decode(b64data)[:8] # Decode and get the first 8 bytes for sig, format in image_signatures.items(): if header.startswith(sig): return True return False except Exception: return False def resize_base64_image(base64_string, size=(128, 128)): """ Resize an image encoded as a Base64 string """ img_data = base64.b64decode(base64_string) img = Image.open(io.BytesIO(img_data)) resized_img = img.resize(size, Image.LANCZOS) buffered = io.BytesIO() resized_img.save(buffered, format=img.format) return base64.b64encode(buffered.getvalue()).decode("utf-8") def split_image_text_types(docs): """ Split base64-encoded images and texts """ b64_images = [] texts = [] for doc in docs: if isinstance(doc, Document): doc = doc.page_content if looks_like_base64(doc) and is_image_data(doc): doc = resize_base64_image(doc, size=(1300, 600)) b64_images.append(doc) else: texts.append(doc) return {"images": b64_images, "texts": texts} def img_prompt_func(data_dict): """ Join the context into a single string """ formatted_texts = "\n".join(data_dict["context"]["texts"]) messages = [] if data_dict["context"]["images"]: for image in data_dict["context"]["images"]: image_message = { "type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image}"}, } messages.append(image_message) text_message = { "type": "text", "text": ( "You are financial analyst tasking with providing investment advice.\n" "You will be given a mixed of text, tables, and image(s) usually of charts or graphs.\n" "Use this information to provide investment advice related to the user question. \n" f"User-provided question: {data_dict['question']}\n\n" "Text and / or tables:\n" f"{formatted_texts}" ), } messages.append(text_message) return [HumanMessage(content=messages)] def multi_modal_rag_chain(retriever): """ Multi-modal RAG chain """ model = ChatOpenAI(temperature=0, model="gpt-4-vision-preview", max_tokens=1024) chain = ( { "context": retriever | RunnableLambda(split_image_text_types), "question":
RunnablePassthrough()
langchain_core.runnables.RunnablePassthrough
get_ipython().run_line_magic('pip', 'install --upgrade --quiet wikipedia') from langchain import hub from langchain.agents import AgentExecutor, create_react_agent from langchain_community.tools import WikipediaQueryRun from langchain_community.utilities import WikipediaAPIWrapper from langchain_openai import ChatOpenAI api_wrapper =
WikipediaAPIWrapper(top_k_results=1, doc_content_chars_max=100)
langchain_community.utilities.WikipediaAPIWrapper
from langchain_community.llms.azureml_endpoint import AzureMLOnlineEndpoint from langchain_community.llms.azureml_endpoint import ( AzureMLEndpointApiType, LlamaContentFormatter, ) from langchain_core.messages import HumanMessage llm = AzureMLOnlineEndpoint( endpoint_url="https://<your-endpoint>.<your_region>.inference.ml.azure.com/score", endpoint_api_type=AzureMLEndpointApiType.realtime, endpoint_api_key="my-api-key", content_formatter=
LlamaContentFormatter()
langchain_community.llms.azureml_endpoint.LlamaContentFormatter
from langchain_community.document_loaders import AsyncChromiumLoader from langchain_community.document_transformers import BeautifulSoupTransformer loader = AsyncChromiumLoader(["https://www.wsj.com"]) html = loader.load() bs_transformer =
BeautifulSoupTransformer()
langchain_community.document_transformers.BeautifulSoupTransformer
import re from typing import Union from langchain.agents import ( AgentExecutor, AgentOutputParser, LLMSingleActionAgent, ) from langchain.chains import LLMChain from langchain.prompts import StringPromptTemplate from langchain_community.agent_toolkits import NLAToolkit from langchain_community.tools.plugin import AIPlugin from langchain_core.agents import AgentAction, AgentFinish from langchain_openai import OpenAI llm = OpenAI(temperature=0) urls = [ "https://datasette.io/.well-known/ai-plugin.json", "https://api.speak.com/.well-known/ai-plugin.json", "https://www.wolframalpha.com/.well-known/ai-plugin.json", "https://www.zapier.com/.well-known/ai-plugin.json", "https://www.klarna.com/.well-known/ai-plugin.json", "https://www.joinmilo.com/.well-known/ai-plugin.json", "https://slack.com/.well-known/ai-plugin.json", "https://schooldigger.com/.well-known/ai-plugin.json", ] AI_PLUGINS = [AIPlugin.from_url(url) for url in urls] from langchain_community.vectorstores import FAISS from langchain_core.documents import Document from langchain_openai import OpenAIEmbeddings embeddings = OpenAIEmbeddings() docs = [ Document( page_content=plugin.description_for_model, metadata={"plugin_name": plugin.name_for_model}, ) for plugin in AI_PLUGINS ] vector_store = FAISS.from_documents(docs, embeddings) toolkits_dict = { plugin.name_for_model:
NLAToolkit.from_llm_and_ai_plugin(llm, plugin)
langchain_community.agent_toolkits.NLAToolkit.from_llm_and_ai_plugin
get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain langchain-openai duckduckgo-search') from langchain.tools import DuckDuckGoSearchRun from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_openai import ChatOpenAI search =
DuckDuckGoSearchRun()
langchain.tools.DuckDuckGoSearchRun
from langchain_community.utilities import DuckDuckGoSearchAPIWrapper from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_core.runnables import RunnablePassthrough from langchain_openai import ChatOpenAI template = """Answer the users question based only on the following context: <context> {context} </context> Question: {question} """ prompt = ChatPromptTemplate.from_template(template) model = ChatOpenAI(temperature=0) search = DuckDuckGoSearchAPIWrapper() def retriever(query): return search.run(query) chain = ( {"context": retriever, "question": RunnablePassthrough()} | prompt | model | StrOutputParser() ) simple_query = "what is langchain?" chain.invoke(simple_query) distracted_query = "man that sam bankman fried trial was crazy! what is langchain?" chain.invoke(distracted_query) retriever(distracted_query) template = """Provide a better search query for \ web search engine to answer the given question, end \ the queries with ’**’. Question: \ {x} Answer:""" rewrite_prompt = ChatPromptTemplate.from_template(template) from langchain import hub rewrite_prompt = hub.pull("langchain-ai/rewrite") print(rewrite_prompt.template) def _parse(text): return text.strip("**") rewriter = rewrite_prompt |
ChatOpenAI(temperature=0)
langchain_openai.ChatOpenAI
get_ipython().run_line_magic('pip', 'install --upgrade --quiet pyvespa') from vespa.package import ApplicationPackage, Field, RankProfile app_package = ApplicationPackage(name="testapp") app_package.schema.add_fields( Field( name="text", type="string", indexing=["index", "summary"], index="enable-bm25" ), Field( name="embedding", type="tensor<float>(x[384])", indexing=["attribute", "summary"], attribute=["distance-metric: angular"], ), ) app_package.schema.add_rank_profile( RankProfile( name="default", first_phase="closeness(field, embedding)", inputs=[("query(query_embedding)", "tensor<float>(x[384])")], ) ) from vespa.deployment import VespaDocker vespa_docker = VespaDocker() vespa_app = vespa_docker.deploy(application_package=app_package) from langchain_community.document_loaders import TextLoader from langchain_text_splitters import CharacterTextSplitter loader = TextLoader("../../modules/state_of_the_union.txt") documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) docs = text_splitter.split_documents(documents) from langchain_community.embeddings.sentence_transformer import ( SentenceTransformerEmbeddings, ) embedding_function = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2") vespa_config = dict( page_content_field="text", embedding_field="embedding", input_field="query_embedding", ) from langchain_community.vectorstores import VespaStore db =
VespaStore.from_documents(docs, embedding_function, app=vespa_app, **vespa_config)
langchain_community.vectorstores.VespaStore.from_documents
import os from langchain.agents import AgentExecutor, AgentType, initialize_agent, load_tools from langchain.chains import LLMChain from langchain.memory import ConversationBufferMemory from langchain_community.llms import GradientLLM from getpass import getpass if not os.environ.get("GRADIENT_ACCESS_TOKEN", None): os.environ["GRADIENT_ACCESS_TOKEN"] = getpass("gradient.ai access token:") if not os.environ.get("GRADIENT_WORKSPACE_ID", None): os.environ["GRADIENT_WORKSPACE_ID"] = getpass("gradient.ai workspace id:") if not os.environ.get("GRADIENT_MODEL_ADAPTER_ID", None): os.environ["GRADIENT_MODEL_ID"] = getpass("gradient.ai model id:") llm = GradientLLM( model_id=os.environ["GRADIENT_MODEL_ID"], ) tools =
load_tools(["memorize"], llm=llm)
langchain.agents.load_tools
import zipfile import requests def download_and_unzip(url: str, output_path: str = "file.zip") -> None: file_id = url.split("/")[-2] download_url = f"https://drive.google.com/uc?export=download&id={file_id}" response = requests.get(download_url) if response.status_code != 200: print("Failed to download the file.") return with open(output_path, "wb") as file: file.write(response.content) print(f"File {output_path} downloaded.") with zipfile.ZipFile(output_path, "r") as zip_ref: zip_ref.extractall() print(f"File {output_path} has been unzipped.") url = ( "https://drive.google.com/file/d/1rh1s1o2i7B-Sk1v9o8KNgivLVGwJ-osV/view?usp=sharing" ) download_and_unzip(url) directory_path = "./hogwarts" from langchain_community.chat_loaders.facebook_messenger import ( FolderFacebookMessengerChatLoader, SingleFileFacebookMessengerChatLoader, ) loader = SingleFileFacebookMessengerChatLoader( path="./hogwarts/inbox/HermioneGranger/messages_Hermione_Granger.json", ) chat_session = loader.load()[0] chat_session["messages"][:3] loader = FolderFacebookMessengerChatLoader( path="./hogwarts", ) chat_sessions = loader.load() len(chat_sessions) from langchain_community.chat_loaders.utils import ( map_ai_messages, merge_chat_runs, ) merged_sessions = merge_chat_runs(chat_sessions) alternating_sessions = list(map_ai_messages(merged_sessions, "Harry Potter")) alternating_sessions[0]["messages"][:3] from langchain.adapters.openai import convert_messages_for_finetuning training_data =
convert_messages_for_finetuning(alternating_sessions)
langchain.adapters.openai.convert_messages_for_finetuning
def pretty_print_docs(docs): print( f"\n{'-' * 100}\n".join( [f"Document {i+1}:\n\n" + d.page_content for i, d in enumerate(docs)] ) ) from langchain_community.document_loaders import TextLoader from langchain_community.vectorstores import FAISS from langchain_openai import OpenAIEmbeddings from langchain_text_splitters import CharacterTextSplitter documents = TextLoader("../../state_of_the_union.txt").load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) texts = text_splitter.split_documents(documents) retriever = FAISS.from_documents(texts, OpenAIEmbeddings()).as_retriever() docs = retriever.get_relevant_documents( "What did the president say about Ketanji Brown Jackson" ) pretty_print_docs(docs) from langchain.retrievers import ContextualCompressionRetriever from langchain.retrievers.document_compressors import LLMChainExtractor from langchain_openai import OpenAI llm = OpenAI(temperature=0) compressor = LLMChainExtractor.from_llm(llm) compression_retriever = ContextualCompressionRetriever( base_compressor=compressor, base_retriever=retriever ) compressed_docs = compression_retriever.get_relevant_documents( "What did the president say about Ketanji Jackson Brown" ) pretty_print_docs(compressed_docs) from langchain.retrievers.document_compressors import LLMChainFilter _filter = LLMChainFilter.from_llm(llm) compression_retriever = ContextualCompressionRetriever( base_compressor=_filter, base_retriever=retriever ) compressed_docs = compression_retriever.get_relevant_documents( "What did the president say about Ketanji Jackson Brown" ) pretty_print_docs(compressed_docs) from langchain.retrievers.document_compressors import EmbeddingsFilter from langchain_openai import OpenAIEmbeddings embeddings = OpenAIEmbeddings() embeddings_filter = EmbeddingsFilter(embeddings=embeddings, similarity_threshold=0.76) compression_retriever = ContextualCompressionRetriever( base_compressor=embeddings_filter, base_retriever=retriever ) compressed_docs = compression_retriever.get_relevant_documents( "What did the president say about Ketanji Jackson Brown" ) pretty_print_docs(compressed_docs) from langchain.retrievers.document_compressors import DocumentCompressorPipeline from langchain_community.document_transformers import EmbeddingsRedundantFilter from langchain_text_splitters import CharacterTextSplitter splitter = CharacterTextSplitter(chunk_size=300, chunk_overlap=0, separator=". ") redundant_filter =
EmbeddingsRedundantFilter(embeddings=embeddings)
langchain_community.document_transformers.EmbeddingsRedundantFilter
get_ipython().run_line_magic('pip', 'install --upgrade --quiet boto3 nltk') get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain_experimental') get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain pydantic') import os import boto3 comprehend_client = boto3.client("comprehend", region_name="us-east-1") from langchain_experimental.comprehend_moderation import AmazonComprehendModerationChain comprehend_moderation = AmazonComprehendModerationChain( client=comprehend_client, verbose=True, # optional ) from langchain.prompts import PromptTemplate from langchain_community.llms.fake import FakeListLLM from langchain_experimental.comprehend_moderation.base_moderation_exceptions import ( ModerationPiiError, ) template = """Question: {question} Answer:""" prompt = PromptTemplate.from_template(template) responses = [ "Final Answer: A credit card number looks like 1289-2321-1123-2387. A fake SSN number looks like 323-22-9980. John Doe's phone number is (999)253-9876.", "Final Answer: This is a really <expletive> way of constructing a birdhouse. This is <expletive> insane to think that any birds would actually create their <expletive> nests here.", ] llm =
FakeListLLM(responses=responses)
langchain_community.llms.fake.FakeListLLM
from langchain.retrievers import ParentDocumentRetriever from langchain.storage import InMemoryStore from langchain_community.document_loaders import TextLoader from langchain_community.vectorstores import Chroma from langchain_openai import OpenAIEmbeddings from langchain_text_splitters import RecursiveCharacterTextSplitter loaders = [ TextLoader("../../paul_graham_essay.txt"), TextLoader("../../state_of_the_union.txt"), ] docs = [] for loader in loaders: docs.extend(loader.load()) child_splitter =
RecursiveCharacterTextSplitter(chunk_size=400)
langchain_text_splitters.RecursiveCharacterTextSplitter
get_ipython().run_line_magic('pip', 'install --upgrade --quiet comet_ml langchain langchain-openai google-search-results spacy textstat pandas') get_ipython().system('{sys.executable} -m spacy download en_core_web_sm') import comet_ml comet_ml.init(project_name="comet-example-langchain") import os os.environ["OPENAI_API_KEY"] = "..." os.environ["SERPAPI_API_KEY"] = "..." from langchain.callbacks import CometCallbackHandler, StdOutCallbackHandler from langchain_openai import OpenAI comet_callback = CometCallbackHandler( project_name="comet-example-langchain", complexity_metrics=True, stream_logs=True, tags=["llm"], visualizations=["dep"], ) callbacks = [StdOutCallbackHandler(), comet_callback] llm = OpenAI(temperature=0.9, callbacks=callbacks, verbose=True) llm_result = llm.generate(["Tell me a joke", "Tell me a poem", "Tell me a fact"] * 3) print("LLM result", llm_result) comet_callback.flush_tracker(llm, finish=True) from langchain.callbacks import CometCallbackHandler, StdOutCallbackHandler from langchain.chains import LLMChain from langchain.prompts import PromptTemplate from langchain_openai import OpenAI comet_callback = CometCallbackHandler( complexity_metrics=True, project_name="comet-example-langchain", stream_logs=True, tags=["synopsis-chain"], ) callbacks = [StdOutCallbackHandler(), comet_callback] llm = OpenAI(temperature=0.9, callbacks=callbacks) 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)
langchain.prompts.PromptTemplate
import os os.environ["LANGCHAIN_PROJECT"] = "movie-qa" import pandas as pd df = pd.read_csv("data/imdb_top_1000.csv") df["Released_Year"] = df["Released_Year"].astype(int, errors="ignore") from langchain.schema import Document from langchain_community.vectorstores import Chroma from langchain_openai import OpenAIEmbeddings embeddings = OpenAIEmbeddings() records = df.to_dict("records") documents = [Document(page_content=d["Overview"], metadata=d) for d in records] vectorstore = Chroma.from_documents(documents, embeddings) from langchain.chains.query_constructor.base import AttributeInfo from langchain.retrievers.self_query.base import SelfQueryRetriever from langchain_openai import ChatOpenAI metadata_field_info = [ AttributeInfo( name="Released_Year", description="The year the movie was released", type="int", ), AttributeInfo( name="Series_Title", description="The title of the movie", type="str", ), AttributeInfo( name="Genre", description="The genre of the movie", type="string", ), AttributeInfo( name="IMDB_Rating", description="A 1-10 rating for the movie", type="float" ), ] document_content_description = "Brief summary of a movie" llm = ChatOpenAI(temperature=0) retriever = SelfQueryRetriever.from_llm( llm, vectorstore, document_content_description, metadata_field_info, verbose=True ) from langchain_core.runnables import RunnablePassthrough from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate prompt = ChatPromptTemplate.from_template( """Answer the user's question based on the below information: Information: {info} Question: {question}""" ) generator = (prompt | ChatOpenAI() |
StrOutputParser()
langchain_core.output_parsers.StrOutputParser
from langchain.prompts import ( ChatPromptTemplate, FewShotChatMessagePromptTemplate, ) examples = [ {"input": "2+2", "output": "4"}, {"input": "2+3", "output": "5"}, ] example_prompt = ChatPromptTemplate.from_messages( [ ("human", "{input}"), ("ai", "{output}"), ] ) few_shot_prompt = FewShotChatMessagePromptTemplate( example_prompt=example_prompt, examples=examples, ) print(few_shot_prompt.format()) final_prompt = ChatPromptTemplate.from_messages( [ ("system", "You are a wondrous wizard of math."), few_shot_prompt, ("human", "{input}"), ] ) from langchain_community.chat_models import ChatAnthropic chain = final_prompt | ChatAnthropic(temperature=0.0) chain.invoke({"input": "What's the square of a triangle?"}) from langchain.prompts import SemanticSimilarityExampleSelector from langchain_community.vectorstores import Chroma from langchain_openai import OpenAIEmbeddings examples = [ {"input": "2+2", "output": "4"}, {"input": "2+3", "output": "5"}, {"input": "2+4", "output": "6"}, {"input": "What did the cow say to the moon?", "output": "nothing at all"}, { "input": "Write me a poem about the moon", "output": "One for the moon, and one for me, who are we to talk about the moon?", }, ] to_vectorize = [" ".join(example.values()) for example in examples] embeddings =
OpenAIEmbeddings()
langchain_openai.OpenAIEmbeddings
from langchain.agents import AgentType, initialize_agent, load_tools from langchain_openai import OpenAI llm = OpenAI(temperature=0) tools = load_tools(["google-serper"], llm=llm) agent = initialize_agent( tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True ) agent.run("What is the weather in Pomfret?") tools = load_tools(["searchapi"], llm=llm) agent = initialize_agent( tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True ) agent.run("What is the weather in Pomfret?") tools = load_tools(["serpapi"], llm=llm) agent = initialize_agent( tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True ) agent.run("What is the weather in Pomfret?") tools = load_tools(["google-search"], llm=llm) agent = initialize_agent( tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True ) agent.run("What is the weather in Pomfret?") tools =
load_tools(["searx-search"], searx_host="http://localhost:8888", llm=llm)
langchain.agents.load_tools
get_ipython().system(' pip install -U langchain openai chromadb langchain-experimental # (newest versions required for multi-modal)') get_ipython().system(' pip install "unstructured[all-docs]" pillow pydantic lxml pillow matplotlib chromadb tiktoken') from langchain_text_splitters import CharacterTextSplitter from unstructured.partition.pdf import partition_pdf def extract_pdf_elements(path, fname): """ Extract images, tables, and chunk text from a PDF file. path: File path, which is used to dump images (.jpg) fname: File name """ return partition_pdf( filename=path + fname, extract_images_in_pdf=False, infer_table_structure=True, chunking_strategy="by_title", max_characters=4000, new_after_n_chars=3800, combine_text_under_n_chars=2000, image_output_dir_path=path, ) def categorize_elements(raw_pdf_elements): """ Categorize extracted elements from a PDF into tables and texts. raw_pdf_elements: List of unstructured.documents.elements """ tables = [] texts = [] for element in raw_pdf_elements: if "unstructured.documents.elements.Table" in str(type(element)): tables.append(str(element)) elif "unstructured.documents.elements.CompositeElement" in str(type(element)): texts.append(str(element)) return texts, tables fpath = "/Users/rlm/Desktop/cj/" fname = "cj.pdf" raw_pdf_elements = extract_pdf_elements(fpath, fname) texts, tables = categorize_elements(raw_pdf_elements) text_splitter = CharacterTextSplitter.from_tiktoken_encoder( chunk_size=4000, chunk_overlap=0 ) joined_texts = " ".join(texts) texts_4k_token = text_splitter.split_text(joined_texts) from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_openai import ChatOpenAI def generate_text_summaries(texts, tables, summarize_texts=False): """ Summarize text elements texts: List of str tables: List of str summarize_texts: Bool to summarize texts """ prompt_text = """You are an assistant tasked with summarizing tables and text for retrieval. \ These summaries will be embedded and used to retrieve the raw text or table elements. \ Give a concise summary of the table or text that is well optimized for retrieval. Table or text: {element} """ prompt = ChatPromptTemplate.from_template(prompt_text) model = ChatOpenAI(temperature=0, model="gpt-4") summarize_chain = {"element": lambda x: x} | prompt | model | StrOutputParser() text_summaries = [] table_summaries = [] if texts and summarize_texts: text_summaries = summarize_chain.batch(texts, {"max_concurrency": 5}) elif texts: text_summaries = texts if tables: table_summaries = summarize_chain.batch(tables, {"max_concurrency": 5}) return text_summaries, table_summaries text_summaries, table_summaries = generate_text_summaries( texts_4k_token, tables, summarize_texts=True ) import base64 import os from langchain_core.messages import HumanMessage def encode_image(image_path): """Getting the base64 string""" with open(image_path, "rb") as image_file: return base64.b64encode(image_file.read()).decode("utf-8") def image_summarize(img_base64, prompt): """Make image summary""" chat = ChatOpenAI(model="gpt-4-vision-preview", max_tokens=1024) msg = chat.invoke( [ HumanMessage( content=[ {"type": "text", "text": prompt}, { "type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{img_base64}"}, }, ] ) ] ) return msg.content def generate_img_summaries(path): """ Generate summaries and base64 encoded strings for images path: Path to list of .jpg files extracted by Unstructured """ img_base64_list = [] image_summaries = [] prompt = """You are an assistant tasked with summarizing images for retrieval. \ These summaries will be embedded and used to retrieve the raw image. \ Give a concise summary of the image that is well optimized for retrieval.""" for img_file in sorted(os.listdir(path)): if img_file.endswith(".jpg"): img_path = os.path.join(path, img_file) base64_image = encode_image(img_path) img_base64_list.append(base64_image) image_summaries.append(image_summarize(base64_image, prompt)) return img_base64_list, image_summaries img_base64_list, image_summaries = generate_img_summaries(fpath) import uuid from langchain.retrievers.multi_vector import MultiVectorRetriever from langchain.storage import InMemoryStore from langchain_community.vectorstores import Chroma from langchain_core.documents import Document from langchain_openai import OpenAIEmbeddings def create_multi_vector_retriever( vectorstore, text_summaries, texts, table_summaries, tables, image_summaries, images ): """ Create retriever that indexes summaries, but returns raw images or texts """ store =
InMemoryStore()
langchain.storage.InMemoryStore
get_ipython().run_line_magic('pip', 'install --upgrade --quiet scikit-learn') from langchain_community.retrievers import TFIDFRetriever retriever = TFIDFRetriever.from_texts(["foo", "bar", "world", "hello", "foo bar"]) from langchain_core.documents import Document retriever = TFIDFRetriever.from_documents( [ Document(page_content="foo"), Document(page_content="bar"), Document(page_content="world"),
Document(page_content="hello")
langchain_core.documents.Document
import sentence_transformers from baidubce.auth.bce_credentials import BceCredentials from baidubce.bce_client_configuration import BceClientConfiguration from langchain.chains.retrieval_qa import RetrievalQA from langchain_community.document_loaders.baiducloud_bos_directory import ( BaiduBOSDirectoryLoader, ) from langchain_community.embeddings.huggingface import HuggingFaceEmbeddings from langchain_community.llms.baidu_qianfan_endpoint import QianfanLLMEndpoint from langchain_community.vectorstores import BESVectorStore from langchain_text_splitters import RecursiveCharacterTextSplitter bos_host = "your bos eddpoint" access_key_id = "your bos access ak" secret_access_key = "your bos access sk" config = BceClientConfiguration( credentials=BceCredentials(access_key_id, secret_access_key), endpoint=bos_host ) loader = BaiduBOSDirectoryLoader(conf=config, bucket="llm-test", prefix="llm/") documents = loader.load() text_splitter =
RecursiveCharacterTextSplitter(chunk_size=200, chunk_overlap=0)
langchain_text_splitters.RecursiveCharacterTextSplitter
from langchain.chains import RetrievalQAWithSourcesChain from langchain_community.document_loaders import TextLoader from langchain_community.vectorstores.jaguar import Jaguar from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_core.runnables import RunnablePassthrough from langchain_openai import ChatOpenAI, OpenAI, OpenAIEmbeddings from langchain_text_splitters import CharacterTextSplitter """ Load a text file into a set of documents """ loader = TextLoader("../../modules/state_of_the_union.txt") documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=300) docs = text_splitter.split_documents(documents) """ Instantiate a Jaguar vector store """ url = "http://192.168.5.88:8080/fwww/" embeddings = OpenAIEmbeddings() pod = "vdb" store = "langchain_rag_store" vector_index = "v" vector_type = "cosine_fraction_float" vector_dimension = 1536 vectorstore = Jaguar( pod, store, vector_index, vector_type, vector_dimension, url, embeddings ) """ Login must be performed to authorize the client. The environment variable JAGUAR_API_KEY or file $HOME/.jagrc should contain the API key for accessing JaguarDB servers. """ vectorstore.login() """ Create vector store on the JaguarDB database server. This should be done only once. """ metadata = "category char(16)" text_size = 4096 vectorstore.create(metadata, text_size) """ Add the texts from the text splitter to our vectorstore """ vectorstore.add_documents(docs) """ Get the retriever object """ retriever = vectorstore.as_retriever() template = """You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise. Question: {question} Context: {context} Answer: """ prompt = ChatPromptTemplate.from_template(template) """ Obtain a Large Language Model """ LLM = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0) """ Create a chain for the RAG flow """ rag_chain = ( {"context": retriever, "question":
RunnablePassthrough()
langchain_core.runnables.RunnablePassthrough
REGION = "us-central1" # @param {type:"string"} INSTANCE = "test-instance" # @param {type:"string"} DATABASE = "test" # @param {type:"string"} TABLE_NAME = "test-default" # @param {type:"string"} get_ipython().run_line_magic('pip', 'install -upgrade --quiet langchain-google-cloud-sql-mysql') PROJECT_ID = "my-project-id" # @param {type:"string"} get_ipython().system('gcloud config set project {PROJECT_ID}') from google.colab import auth auth.authenticate_user() get_ipython().system('gcloud services enable sqladmin.googleapis.com') from langchain_google_cloud_sql_mysql import MySQLEngine engine = MySQLEngine.from_instance( project_id=PROJECT_ID, region=REGION, instance=INSTANCE, database=DATABASE ) engine.init_document_table(TABLE_NAME, overwrite_existing=True) from langchain_core.documents import Document from langchain_google_cloud_sql_mysql import MySQLDocumentSaver test_docs = [ Document( page_content="Apple Granny Smith 150 0.99 1", metadata={"fruit_id": 1}, ), Document( page_content="Banana Cavendish 200 0.59 0", metadata={"fruit_id": 2}, ), Document( page_content="Orange Navel 80 1.29 1", metadata={"fruit_id": 3}, ), ] saver = MySQLDocumentSaver(engine=engine, table_name=TABLE_NAME) saver.add_documents(test_docs) from langchain_google_cloud_sql_mysql import MySQLLoader loader =
MySQLLoader(engine=engine, table_name=TABLE_NAME)
langchain_google_cloud_sql_mysql.MySQLLoader
get_ipython().run_line_magic('pip', 'install --upgrade --quiet timescale-vector') get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain-openai') get_ipython().run_line_magic('pip', 'install --upgrade --quiet tiktoken') import os from dotenv import find_dotenv, load_dotenv _ = load_dotenv(find_dotenv()) OPENAI_API_KEY = os.environ["OPENAI_API_KEY"] from typing import Tuple from datetime import datetime, timedelta from langchain.docstore.document import Document from langchain_community.document_loaders import TextLoader from langchain_community.document_loaders.json_loader import JSONLoader from langchain_community.vectorstores.timescalevector import TimescaleVector from langchain_openai import OpenAIEmbeddings from langchain_text_splitters import CharacterTextSplitter loader = TextLoader("../../../extras/modules/state_of_the_union.txt") documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) docs = text_splitter.split_documents(documents) embeddings = OpenAIEmbeddings() SERVICE_URL = os.environ["TIMESCALE_SERVICE_URL"] COLLECTION_NAME = "state_of_the_union_test" db = TimescaleVector.from_documents( embedding=embeddings, documents=docs, collection_name=COLLECTION_NAME, service_url=SERVICE_URL, ) query = "What did the president say about Ketanji Brown Jackson" docs_with_score = db.similarity_search_with_score(query) for doc, score in docs_with_score: print("-" * 80) print("Score: ", score) print(doc.page_content) print("-" * 80) retriever = db.as_retriever() print(retriever) from langchain_openai import ChatOpenAI llm = ChatOpenAI(temperature=0.1, model="gpt-3.5-turbo-16k") from langchain.chains import RetrievalQA qa_stuff = RetrievalQA.from_chain_type( llm=llm, chain_type="stuff", retriever=retriever, verbose=True, ) query = "What did the president say about Ketanji Brown Jackson?" response = qa_stuff.run(query) print(response) from timescale_vector import client def create_uuid(date_string: str): if date_string is None: return None time_format = "%a %b %d %H:%M:%S %Y %z" datetime_obj = datetime.strptime(date_string, time_format) uuid = client.uuid_from_time(datetime_obj) return str(uuid) def split_name(input_string: str) -> Tuple[str, str]: if input_string is None: return None, None start = input_string.find("<") end = input_string.find(">") name = input_string[:start].strip() email = input_string[start + 1 : end].strip() return name, email def create_date(input_string: str) -> datetime: if input_string is None: return None month_dict = { "Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04", "May": "05", "Jun": "06", "Jul": "07", "Aug": "08", "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12", } components = input_string.split() day = components[2] month = month_dict[components[1]] year = components[4] time = components[3] timezone_offset_minutes = int(components[5]) # Convert the offset to minutes timezone_hours = timezone_offset_minutes // 60 # Calculate the hours timezone_minutes = timezone_offset_minutes % 60 # Calculate the remaining minutes timestamp_tz_str = ( f"{year}-{month}-{day} {time}+{timezone_hours:02}{timezone_minutes:02}" ) return timestamp_tz_str def extract_metadata(record: dict, metadata: dict) -> dict: record_name, record_email = split_name(record["author"]) metadata["id"] = create_uuid(record["date"]) metadata["date"] = create_date(record["date"]) metadata["author_name"] = record_name metadata["author_email"] = record_email metadata["commit_hash"] = record["commit"] return metadata get_ipython().system('curl -O https://s3.amazonaws.com/assets.timescale.com/ai/ts_git_log.json') FILE_PATH = "../../../../../ts_git_log.json" loader = JSONLoader( file_path=FILE_PATH, jq_schema=".commit_history[]", text_content=False, metadata_func=extract_metadata, ) documents = loader.load() documents = [doc for doc in documents if doc.metadata["date"] is not None] print(documents[0]) NUM_RECORDS = 500 documents = documents[:NUM_RECORDS] text_splitter = CharacterTextSplitter( chunk_size=1000, chunk_overlap=200, ) docs = text_splitter.split_documents(documents) COLLECTION_NAME = "timescale_commits" embeddings = OpenAIEmbeddings() db = TimescaleVector.from_documents( embedding=embeddings, ids=[doc.metadata["id"] for doc in docs], documents=docs, collection_name=COLLECTION_NAME, service_url=SERVICE_URL, time_partition_interval=timedelta(days=7), ) start_dt = datetime(2023, 8, 1, 22, 10, 35) # Start date = 1 August 2023, 22:10:35 end_dt = datetime(2023, 8, 30, 22, 10, 35) # End date = 30 August 2023, 22:10:35 td = timedelta(days=7) # Time delta = 7 days query = "What's new with TimescaleDB functions?" docs_with_score = db.similarity_search_with_score( query, start_date=start_dt, end_date=end_dt ) for doc, score in docs_with_score: print("-" * 80) print("Score: ", score) print("Date: ", doc.metadata["date"]) print(doc.page_content) print("-" * 80) docs_with_score = db.similarity_search_with_score( query, start_date=start_dt, time_delta=td ) for doc, score in docs_with_score: print("-" * 80) print("Score: ", score) print("Date: ", doc.metadata["date"]) print(doc.page_content) print("-" * 80) docs_with_score = db.similarity_search_with_score(query, end_date=end_dt, time_delta=td) for doc, score in docs_with_score: print("-" * 80) print("Score: ", score) print("Date: ", doc.metadata["date"]) print(doc.page_content) print("-" * 80) docs_with_score = db.similarity_search_with_score(query, start_date=start_dt) for doc, score in docs_with_score: print("-" * 80) print("Score: ", score) print("Date: ", doc.metadata["date"]) print(doc.page_content) print("-" * 80) docs_with_score = db.similarity_search_with_score(query, end_date=end_dt) for doc, score in docs_with_score: print("-" * 80) print("Score: ", score) print("Date: ", doc.metadata["date"]) print(doc.page_content) print("-" * 80) retriever = db.as_retriever(search_kwargs={"start_date": start_dt, "end_date": end_dt}) from langchain_openai import ChatOpenAI llm = ChatOpenAI(temperature=0.1, model="gpt-3.5-turbo-16k") from langchain.chains import RetrievalQA qa_stuff = RetrievalQA.from_chain_type( llm=llm, chain_type="stuff", retriever=retriever, verbose=True, ) query = ( "What's new with the timescaledb functions? Tell me when these changes were made." ) response = qa_stuff.run(query) print(response) COLLECTION_NAME = "timescale_commits" embeddings = OpenAIEmbeddings() db = TimescaleVector( collection_name=COLLECTION_NAME, service_url=SERVICE_URL, embedding_function=embeddings, ) db.create_index() db.drop_index() db.create_index(index_type="tsv", max_alpha=1.0, num_neighbors=50) db.drop_index() db.create_index(index_type="hnsw", m=16, ef_construction=64) db.drop_index() db.create_index(index_type="ivfflat", num_lists=20, num_records=1000) db.drop_index() db.create_index() COLLECTION_NAME = "timescale_commits" vectorstore = TimescaleVector( embedding_function=OpenAIEmbeddings(), collection_name=COLLECTION_NAME, service_url=SERVICE_URL, ) from langchain.chains.query_constructor.base import AttributeInfo from langchain.retrievers.self_query.base import SelfQueryRetriever from langchain_openai import OpenAI metadata_field_info = [ AttributeInfo( name="id", description="A UUID v1 generated from the date of the commit", type="uuid", ), AttributeInfo( name="date", description="The date of the commit in timestamptz format", type="timestamptz", ), AttributeInfo( name="author_name", description="The name of the author of the commit", type="string", ), AttributeInfo( name="author_email", description="The email address of the author of the commit", type="string", ), ] document_content_description = "The git log commit summary containing the commit hash, author, date of commit, change summary and change details" llm =
OpenAI(temperature=0)
langchain_openai.OpenAI
meals = [ "Beef Enchiladas with Feta cheese. Mexican-Greek fusion", "Chicken Flatbreads with red sauce. Italian-Mexican fusion", "Veggie sweet potato quesadillas with vegan cheese", "One-Pan Tortelonni bake with peppers and onions", ] from langchain_openai import OpenAI llm = OpenAI(model="gpt-3.5-turbo-instruct") from langchain.prompts import PromptTemplate PROMPT_TEMPLATE = """Here is the description of a meal: "{meal}". Embed the meal into the given text: "{text_to_personalize}". Prepend a personalized message including the user's name "{user}" and their preference "{preference}". Make it sound good. """ PROMPT = PromptTemplate( input_variables=["meal", "text_to_personalize", "user", "preference"], template=PROMPT_TEMPLATE, ) import langchain_experimental.rl_chain as rl_chain chain = rl_chain.PickBest.from_llm(llm=llm, prompt=PROMPT) response = chain.run( meal=rl_chain.ToSelectFrom(meals), user=rl_chain.BasedOn("Tom"), preference=rl_chain.BasedOn(["Vegetarian", "regular dairy is ok"]), text_to_personalize="This is the weeks specialty dish, our master chefs \ believe you will love it!", ) print(response["response"]) for _ in range(5): try: response = chain.run( meal=rl_chain.ToSelectFrom(meals), user=rl_chain.BasedOn("Tom"), preference=rl_chain.BasedOn(["Vegetarian", "regular dairy is ok"]), text_to_personalize="This is the weeks specialty dish, our master chefs believe you will love it!", ) except Exception as e: print(e) print(response["response"]) print() scoring_criteria_template = ( "Given {preference} rank how good or bad this selection is {meal}" ) chain = rl_chain.PickBest.from_llm( llm=llm, prompt=PROMPT, selection_scorer=rl_chain.AutoSelectionScorer( llm=llm, scoring_criteria_template_str=scoring_criteria_template ), ) response = chain.run( meal=rl_chain.ToSelectFrom(meals), user=
rl_chain.BasedOn("Tom")
langchain_experimental.rl_chain.BasedOn
get_ipython().run_line_magic('pip', 'install --upgrade --quiet lark') get_ipython().run_line_magic('pip', 'install --upgrade --quiet libdeeplake') import getpass import os os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:") os.environ["ACTIVELOOP_TOKEN"] = getpass.getpass("Activeloop token:") from langchain_community.vectorstores import DeepLake from langchain_core.documents import Document from langchain_openai import OpenAIEmbeddings embeddings =
OpenAIEmbeddings()
langchain_openai.OpenAIEmbeddings
from langchain_community.document_loaders import NewsURLLoader urls = [ "https://www.bbc.com/news/world-us-canada-66388172", "https://www.bbc.com/news/entertainment-arts-66384971", ] loader = NewsURLLoader(urls=urls) data = loader.load() print("First article: ", data[0]) print("\nSecond article: ", data[1]) loader =
NewsURLLoader(urls=urls, nlp=True)
langchain_community.document_loaders.NewsURLLoader
from langchain.agents.agent_types import AgentType from langchain_experimental.agents.agent_toolkits import create_pandas_dataframe_agent from langchain_openai import ChatOpenAI import pandas as pd from langchain_openai import OpenAI df = pd.read_csv("titanic.csv") agent = create_pandas_dataframe_agent(OpenAI(temperature=0), df, verbose=True) agent = create_pandas_dataframe_agent(
ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613")
langchain_openai.ChatOpenAI
SOURCE = "test" # @param {type:"Query"|"CollectionGroup"|"DocumentReference"|"string"} get_ipython().run_line_magic('pip', 'install -upgrade --quiet langchain-google-datastore') PROJECT_ID = "my-project-id" # @param {type:"string"} get_ipython().system('gcloud config set project {PROJECT_ID}') from google.colab import auth auth.authenticate_user() get_ipython().system('gcloud services enable datastore.googleapis.com') from langchain_core.documents import Document from langchain_google_datastore import DatastoreSaver data = [Document(page_content="Hello, World!")] saver = DatastoreSaver() saver.upsert_documents(data) saver = DatastoreSaver("Collection") saver.upsert_documents(data) doc_ids = ["AnotherCollection/doc_id", "foo/bar"] saver = DatastoreSaver() saver.upsert_documents(documents=data, document_ids=doc_ids) from langchain_google_datastore import DatastoreLoader loader_collection = DatastoreLoader("Collection") loader_subcollection = DatastoreLoader("Collection/doc/SubCollection") data_collection = loader_collection.load() data_subcollection = loader_subcollection.load() from google.cloud import datastore client = datastore.Client() doc_ref = client.collection("foo").document("bar") loader_document =
DatastoreLoader(doc_ref)
langchain_google_datastore.DatastoreLoader
from langchain.output_parsers import ResponseSchema, StructuredOutputParser from langchain.prompts import PromptTemplate from langchain_openai import ChatOpenAI response_schemas = [ ResponseSchema(name="answer", description="answer to the user's question"), ResponseSchema( name="source", description="source used to answer the user's question, should be a website.", ), ] output_parser =
StructuredOutputParser.from_response_schemas(response_schemas)
langchain.output_parsers.StructuredOutputParser.from_response_schemas
import os import pprint os.environ["SERPER_API_KEY"] = "" from langchain_community.utilities import GoogleSerperAPIWrapper search = GoogleSerperAPIWrapper() search.run("Obama's first name?") os.environ["OPENAI_API_KEY"] = "" from langchain.agents import AgentType, Tool, initialize_agent from langchain_community.utilities import GoogleSerperAPIWrapper from langchain_openai import OpenAI 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?" ) search = GoogleSerperAPIWrapper() results = search.results("Apple Inc.") pprint.pp(results) search = GoogleSerperAPIWrapper(type="images") results = search.results("Lion") pprint.pp(results) search = GoogleSerperAPIWrapper(type="news") results = search.results("Tesla Inc.") pprint.pp(results) search =
GoogleSerperAPIWrapper(type="news", tbs="qdr:h")
langchain_community.utilities.GoogleSerperAPIWrapper
get_ipython().run_line_magic('pip', 'install --upgrade --quiet slack_sdk > /dev/null') get_ipython().run_line_magic('pip', 'install --upgrade --quiet beautifulsoup4 > /dev/null # This is optional but is useful for parsing HTML messages') get_ipython().run_line_magic('pip', 'install --upgrade --quiet python-dotenv > /dev/null # This is for loading environmental variables from a .env file') import dotenv dotenv.load_dotenv() from langchain_community.agent_toolkits import SlackToolkit toolkit = SlackToolkit() tools = toolkit.get_tools() tools from langchain import hub from langchain.agents import AgentExecutor, create_react_agent from langchain_openai import ChatOpenAI llm =
ChatOpenAI(temperature=0, model="gpt-4")
langchain_openai.ChatOpenAI
from langchain_community.utilities import DuckDuckGoSearchAPIWrapper from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_core.runnables import RunnablePassthrough from langchain_openai import ChatOpenAI template = """Answer the users question based only on the following context: <context> {context} </context> Question: {question} """ prompt =
ChatPromptTemplate.from_template(template)
langchain_core.prompts.ChatPromptTemplate.from_template
import os from getpass import getpass os.environ["OPENAI_API_KEY"] = getpass() activeloop_token = getpass("Activeloop Token:") os.environ["ACTIVELOOP_TOKEN"] = activeloop_token get_ipython().system('ls "../../../../../../libs"') from langchain_community.document_loaders import TextLoader root_dir = "../../../../../../libs" docs = [] for dirpath, dirnames, filenames in os.walk(root_dir): for file in filenames: if file.endswith(".py") and "*venv/" not in dirpath: try: loader = TextLoader(os.path.join(dirpath, file), encoding="utf-8") docs.extend(loader.load_and_split()) except Exception: pass print(f"{len(docs)}") from langchain_text_splitters import CharacterTextSplitter text_splitter =
CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
langchain_text_splitters.CharacterTextSplitter
get_ipython().run_line_magic('', 'pip install --upgrade --quiet flashrank') get_ipython().run_line_magic('', 'pip install --upgrade --quiet faiss') get_ipython().run_line_magic('', 'pip install --upgrade --quiet faiss_cpu') def pretty_print_docs(docs): print( f"\n{'-' * 100}\n".join( [f"Document {i+1}:\n\n" + d.page_content for i, d in enumerate(docs)] ) ) import getpass import os os.environ["OPENAI_API_KEY"] = getpass.getpass() from langchain_community.document_loaders import TextLoader from langchain_community.vectorstores import FAISS from langchain_openai import OpenAIEmbeddings from langchain_text_splitters import RecursiveCharacterTextSplitter documents = TextLoader( "../../modules/state_of_the_union.txt", ).load() text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100) texts = text_splitter.split_documents(documents) embedding = OpenAIEmbeddings(model="text-embedding-ada-002") retriever = FAISS.from_documents(texts, embedding).as_retriever(search_kwargs={"k": 20}) query = "What did the president say about Ketanji Brown Jackson" docs = retriever.get_relevant_documents(query) pretty_print_docs(docs) from langchain.retrievers import ContextualCompressionRetriever from langchain.retrievers.document_compressors import FlashrankRerank from langchain_openai import ChatOpenAI llm = ChatOpenAI(temperature=0) compressor =
FlashrankRerank()
langchain.retrievers.document_compressors.FlashrankRerank
from langchain.retrievers.multi_vector import MultiVectorRetriever from langchain.storage import InMemoryByteStore from langchain_community.document_loaders import TextLoader from langchain_community.vectorstores import Chroma from langchain_openai import OpenAIEmbeddings from langchain_text_splitters import RecursiveCharacterTextSplitter loaders = [ TextLoader("../../paul_graham_essay.txt"), TextLoader("../../state_of_the_union.txt"), ] docs = [] for loader in loaders: docs.extend(loader.load()) text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000) docs = text_splitter.split_documents(docs) vectorstore = Chroma( collection_name="full_documents", embedding_function=OpenAIEmbeddings() ) store = InMemoryByteStore() id_key = "doc_id" retriever = MultiVectorRetriever( vectorstore=vectorstore, byte_store=store, id_key=id_key, ) import uuid doc_ids = [str(uuid.uuid4()) for _ in docs] child_text_splitter = RecursiveCharacterTextSplitter(chunk_size=400) sub_docs = [] for i, doc in enumerate(docs): _id = doc_ids[i] _sub_docs = child_text_splitter.split_documents([doc]) for _doc in _sub_docs: _doc.metadata[id_key] = _id sub_docs.extend(_sub_docs) retriever.vectorstore.add_documents(sub_docs) retriever.docstore.mset(list(zip(doc_ids, docs))) retriever.vectorstore.similarity_search("justice breyer")[0] len(retriever.get_relevant_documents("justice breyer")[0].page_content) from langchain.retrievers.multi_vector import SearchType retriever.search_type = SearchType.mmr len(retriever.get_relevant_documents("justice breyer")[0].page_content) import uuid from langchain_core.documents import Document from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_openai import ChatOpenAI chain = ( {"doc": lambda x: x.page_content} | ChatPromptTemplate.from_template("Summarize the following document:\n\n{doc}") | ChatOpenAI(max_retries=0) | StrOutputParser() ) summaries = chain.batch(docs, {"max_concurrency": 5}) vectorstore = Chroma(collection_name="summaries", embedding_function=OpenAIEmbeddings()) store = InMemoryByteStore() id_key = "doc_id" retriever = MultiVectorRetriever( vectorstore=vectorstore, byte_store=store, id_key=id_key, ) doc_ids = [str(uuid.uuid4()) for _ in docs] summary_docs = [ Document(page_content=s, metadata={id_key: doc_ids[i]}) for i, s in enumerate(summaries) ] retriever.vectorstore.add_documents(summary_docs) retriever.docstore.mset(list(zip(doc_ids, docs))) sub_docs = vectorstore.similarity_search("justice breyer") sub_docs[0] retrieved_docs = retriever.get_relevant_documents("justice breyer") len(retrieved_docs[0].page_content) functions = [ { "name": "hypothetical_questions", "description": "Generate hypothetical questions", "parameters": { "type": "object", "properties": { "questions": { "type": "array", "items": {"type": "string"}, }, }, "required": ["questions"], }, } ] from langchain.output_parsers.openai_functions import JsonKeyOutputFunctionsParser chain = ( {"doc": lambda x: x.page_content} | ChatPromptTemplate.from_template( "Generate a list of exactly 3 hypothetical questions that the below document could be used to answer:\n\n{doc}" ) | ChatOpenAI(max_retries=0, model="gpt-4").bind( functions=functions, function_call={"name": "hypothetical_questions"} ) | JsonKeyOutputFunctionsParser(key_name="questions") ) chain.invoke(docs[0]) hypothetical_questions = chain.batch(docs, {"max_concurrency": 5}) vectorstore = Chroma( collection_name="hypo-questions", embedding_function=OpenAIEmbeddings() ) store =
InMemoryByteStore()
langchain.storage.InMemoryByteStore
get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain langchain-openai argilla') import os os.environ["ARGILLA_API_URL"] = "..." os.environ["ARGILLA_API_KEY"] = "..." os.environ["OPENAI_API_KEY"] = "..." import argilla as rg from packaging.version import parse as parse_version if parse_version(rg.__version__) < parse_version("1.8.0"): raise RuntimeError( "`FeedbackDataset` is only available in Argilla v1.8.0 or higher, please " "upgrade `argilla` as `pip install argilla --upgrade`." ) dataset = rg.FeedbackDataset( fields=[ rg.TextField(name="prompt"), rg.TextField(name="response"), ], questions=[ rg.RatingQuestion( name="response-rating", description="How would you rate the quality of the response?", values=[1, 2, 3, 4, 5], required=True, ), rg.TextQuestion( name="response-feedback", description="What feedback do you have for the response?", required=False, ), ], guidelines="You're asked to rate the quality of the response and provide feedback.", ) rg.init( api_url=os.environ["ARGILLA_API_URL"], api_key=os.environ["ARGILLA_API_KEY"], ) dataset.push_to_argilla("langchain-dataset") from langchain.callbacks import ArgillaCallbackHandler argilla_callback = ArgillaCallbackHandler( dataset_name="langchain-dataset", api_url=os.environ["ARGILLA_API_URL"], api_key=os.environ["ARGILLA_API_KEY"], ) from langchain.callbacks import ArgillaCallbackHandler, StdOutCallbackHandler from langchain_openai import OpenAI argilla_callback = ArgillaCallbackHandler( dataset_name="langchain-dataset", api_url=os.environ["ARGILLA_API_URL"], api_key=os.environ["ARGILLA_API_KEY"], ) callbacks = [StdOutCallbackHandler(), argilla_callback] llm = OpenAI(temperature=0.9, callbacks=callbacks) llm.generate(["Tell me a joke", "Tell me a poem"] * 3) from langchain.callbacks import ArgillaCallbackHandler, StdOutCallbackHandler from langchain.chains import LLMChain from langchain.prompts import PromptTemplate from langchain_openai import OpenAI argilla_callback = ArgillaCallbackHandler( dataset_name="langchain-dataset", api_url=os.environ["ARGILLA_API_URL"], api_key=os.environ["ARGILLA_API_KEY"], ) callbacks = [StdOutCallbackHandler(), argilla_callback] llm = OpenAI(temperature=0.9, callbacks=callbacks) template = """You are a playwright. Given the title of play, it is your job to write a synopsis for that title. Title: {title} Playwright: This is a synopsis for the above play:""" prompt_template = PromptTemplate(input_variables=["title"], template=template) synopsis_chain = LLMChain(llm=llm, prompt=prompt_template, callbacks=callbacks) test_prompts = [{"title": "Documentary about Bigfoot in Paris"}] synopsis_chain.apply(test_prompts) from langchain.agents import AgentType, initialize_agent, load_tools from langchain.callbacks import ArgillaCallbackHandler, StdOutCallbackHandler from langchain_openai import OpenAI argilla_callback = ArgillaCallbackHandler( dataset_name="langchain-dataset", api_url=os.environ["ARGILLA_API_URL"], api_key=os.environ["ARGILLA_API_KEY"], ) callbacks = [StdOutCallbackHandler(), argilla_callback] llm = OpenAI(temperature=0.9, callbacks=callbacks) tools =
load_tools(["serpapi"], llm=llm, callbacks=callbacks)
langchain.agents.load_tools
from langchain.retrievers.multi_vector import MultiVectorRetriever from langchain.storage import InMemoryByteStore from langchain_community.document_loaders import TextLoader from langchain_community.vectorstores import Chroma from langchain_openai import OpenAIEmbeddings from langchain_text_splitters import RecursiveCharacterTextSplitter loaders = [
TextLoader("../../paul_graham_essay.txt")
langchain_community.document_loaders.TextLoader
import getpass import os os.environ["OPENAI_API_KEY"] = getpass.getpass() import dspy colbertv2 = dspy.ColBERTv2(url="http://20.102.90.50:2017/wiki17_abstracts") from langchain.cache import SQLiteCache from langchain.globals import set_llm_cache from langchain_openai import OpenAI set_llm_cache(SQLiteCache(database_path="cache.db")) llm = OpenAI(model_name="gpt-3.5-turbo-instruct", temperature=0) def retrieve(inputs): return [doc["text"] for doc in colbertv2(inputs["question"], k=5)] colbertv2("cycling") from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import PromptTemplate from langchain_core.runnables import RunnablePassthrough prompt = PromptTemplate.from_template( "Given {context}, answer the question `{question}` as a tweet." ) vanilla_chain = ( RunnablePassthrough.assign(context=retrieve) | prompt | llm | StrOutputParser() ) from dspy.predict.langchain import LangChainModule, LangChainPredict zeroshot_chain = ( RunnablePassthrough.assign(context=retrieve) | LangChainPredict(prompt, llm) |
StrOutputParser()
langchain_core.output_parsers.StrOutputParser
from ragatouille import RAGPretrainedModel RAG = RAGPretrainedModel.from_pretrained("colbert-ir/colbertv2.0") import requests def get_wikipedia_page(title: str): """ Retrieve the full text content of a Wikipedia page. :param title: str - Title of the Wikipedia page. :return: str - Full text content of the page as raw string. """ URL = "https://en.wikipedia.org/w/api.php" params = { "action": "query", "format": "json", "titles": title, "prop": "extracts", "explaintext": True, } headers = {"User-Agent": "RAGatouille_tutorial/0.0.1 (ben@clavie.eu)"} response = requests.get(URL, params=params, headers=headers) data = response.json() page = next(iter(data["query"]["pages"].values())) return page["extract"] if "extract" in page else None full_document = get_wikipedia_page("Hayao_Miyazaki") RAG.index( collection=[full_document], index_name="Miyazaki-123", max_document_length=180, split_documents=True, ) results = RAG.search(query="What animation studio did Miyazaki found?", k=3) results retriever = RAG.as_langchain_retriever(k=3) retriever.invoke("What animation studio did Miyazaki found?") from langchain.chains import create_retrieval_chain from langchain.chains.combine_documents import create_stuff_documents_chain from langchain_core.prompts import ChatPromptTemplate from langchain_openai import ChatOpenAI prompt =
ChatPromptTemplate.from_template( """Answer the following question based only on the provided context: <context> {context} </context> Question: {input}""" )
langchain_core.prompts.ChatPromptTemplate.from_template
get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain langchain-openai') from langchain.prompts import PromptTemplate from langchain_core.runnables import ConfigurableField from langchain_openai import ChatOpenAI model = ChatOpenAI(temperature=0).configurable_fields( temperature=ConfigurableField( id="llm_temperature", name="LLM Temperature", description="The temperature of the LLM", ) ) model.invoke("pick a random number") model.with_config(configurable={"llm_temperature": 0.9}).invoke("pick a random number") prompt = PromptTemplate.from_template("Pick a random number above {x}") chain = prompt | model chain.invoke({"x": 0}) chain.with_config(configurable={"llm_temperature": 0.9}).invoke({"x": 0}) from langchain.runnables.hub import HubRunnable prompt = HubRunnable("rlm/rag-prompt").configurable_fields( owner_repo_commit=ConfigurableField( id="hub_commit", name="Hub Commit", description="The Hub commit to pull from", ) ) prompt.invoke({"question": "foo", "context": "bar"}) prompt.with_config(configurable={"hub_commit": "rlm/rag-prompt-llama"}).invoke( {"question": "foo", "context": "bar"} ) from langchain.prompts import PromptTemplate from langchain_community.chat_models import ChatAnthropic from langchain_core.runnables import ConfigurableField from langchain_openai import ChatOpenAI llm = ChatAnthropic(temperature=0).configurable_alternatives( ConfigurableField(id="llm"), default_key="anthropic", openai=ChatOpenAI(), gpt4=ChatOpenAI(model="gpt-4"), ) prompt = PromptTemplate.from_template("Tell me a joke about {topic}") chain = prompt | llm chain.invoke({"topic": "bears"}) chain.with_config(configurable={"llm": "openai"}).invoke({"topic": "bears"}) chain.with_config(configurable={"llm": "anthropic"}).invoke({"topic": "bears"}) llm =
ChatAnthropic(temperature=0)
langchain_community.chat_models.ChatAnthropic
get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain langchain-openai') from langchain_community.chat_models import ChatAnthropic from langchain_openai import ChatOpenAI from unittest.mock import patch import httpx from openai import RateLimitError request = httpx.Request("GET", "/") response = httpx.Response(200, request=request) error = RateLimitError("rate limit", response=response, body="") openai_llm = ChatOpenAI(max_retries=0) anthropic_llm = ChatAnthropic() llm = openai_llm.with_fallbacks([anthropic_llm]) with patch("openai.resources.chat.completions.Completions.create", side_effect=error): try: print(openai_llm.invoke("Why did the chicken cross the road?")) except RateLimitError: print("Hit error") with patch("openai.resources.chat.completions.Completions.create", side_effect=error): try: print(llm.invoke("Why did the chicken cross the road?")) except RateLimitError: print("Hit error") from langchain_core.prompts import ChatPromptTemplate prompt = ChatPromptTemplate.from_messages( [ ( "system", "You're a nice assistant who always includes a compliment in your response", ), ("human", "Why did the {animal} cross the road"), ] ) chain = prompt | llm with patch("openai.resources.chat.completions.Completions.create", side_effect=error): try: print(chain.invoke({"animal": "kangaroo"})) except RateLimitError: print("Hit error") from langchain_core.output_parsers import StrOutputParser chat_prompt = ChatPromptTemplate.from_messages( [ ( "system", "You're a nice assistant who always includes a compliment in your response", ), ("human", "Why did the {animal} cross the road"), ] ) chat_model = ChatOpenAI(model_name="gpt-fake") bad_chain = chat_prompt | chat_model | StrOutputParser() from langchain.prompts import PromptTemplate from langchain_openai import OpenAI prompt_template = """Instructions: You should always include a compliment in your response. Question: Why did the {animal} cross the road?""" prompt = PromptTemplate.from_template(prompt_template) llm = OpenAI() good_chain = prompt | llm chain = bad_chain.with_fallbacks([good_chain]) chain.invoke({"animal": "turtle"}) short_llm =
ChatOpenAI()
langchain_openai.ChatOpenAI
get_ipython().run_line_magic('pip', 'install --upgrade --quiet boto3 nltk') get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain_experimental') get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain pydantic') import os import boto3 comprehend_client = boto3.client("comprehend", region_name="us-east-1") from langchain_experimental.comprehend_moderation import AmazonComprehendModerationChain comprehend_moderation = AmazonComprehendModerationChain( client=comprehend_client, verbose=True, # optional ) from langchain.prompts import PromptTemplate from langchain_community.llms.fake import FakeListLLM from langchain_experimental.comprehend_moderation.base_moderation_exceptions import ( ModerationPiiError, ) template = """Question: {question} Answer:""" prompt = PromptTemplate.from_template(template) responses = [ "Final Answer: A credit card number looks like 1289-2321-1123-2387. A fake SSN number looks like 323-22-9980. John Doe's phone number is (999)253-9876.", "Final Answer: This is a really <expletive> way of constructing a birdhouse. This is <expletive> insane to think that any birds would actually create their <expletive> nests here.", ] llm = FakeListLLM(responses=responses) chain = ( prompt | comprehend_moderation | {"input": (lambda x: x["output"]) | llm} | comprehend_moderation ) try: response = chain.invoke( { "question": "A sample SSN number looks like this 123-22-3345. Can you give me some more samples?" } ) except ModerationPiiError as e: print(str(e)) else: print(response["output"]) from langchain_experimental.comprehend_moderation import ( BaseModerationConfig, ModerationPiiConfig, ModerationPromptSafetyConfig, ModerationToxicityConfig, ) pii_config = ModerationPiiConfig(labels=["SSN"], redact=True, mask_character="X") toxicity_config = ModerationToxicityConfig(threshold=0.5) prompt_safety_config = ModerationPromptSafetyConfig(threshold=0.5) moderation_config = BaseModerationConfig( filters=[pii_config, toxicity_config, prompt_safety_config] ) comp_moderation_with_config = AmazonComprehendModerationChain( moderation_config=moderation_config, # specify the configuration client=comprehend_client, # optionally pass the Boto3 Client verbose=True, ) from langchain.prompts import PromptTemplate from langchain_community.llms.fake import FakeListLLM template = """Question: {question} Answer:""" prompt = PromptTemplate.from_template(template) responses = [ "Final Answer: A credit card number looks like 1289-2321-1123-2387. A fake SSN number looks like 323-22-9980. John Doe's phone number is (999)253-9876.", "Final Answer: This is a really <expletive> way of constructing a birdhouse. This is <expletive> insane to think that any birds would actually create their <expletive> nests here.", ] llm =
FakeListLLM(responses=responses)
langchain_community.llms.fake.FakeListLLM
get_ipython().run_line_magic('pip', 'install --upgrade --quiet duckdb') from langchain_community.document_loaders import DuckDBLoader get_ipython().run_cell_magic('file', 'example.csv', 'Team,Payroll\nNationals,81.34\nReds,82.20\n') loader = DuckDBLoader("SELECT * FROM read_csv_auto('example.csv')") data = loader.load() print(data) loader =
DuckDBLoader( "SELECT * FROM read_csv_auto('example.csv')
langchain_community.document_loaders.DuckDBLoader
get_ipython().run_line_magic('pip', 'install --upgrade --quiet O365') get_ipython().run_line_magic('pip', 'install --upgrade --quiet beautifulsoup4 # This is optional but is useful for parsing HTML messages') from langchain_community.agent_toolkits import O365Toolkit toolkit = O365Toolkit() tools = toolkit.get_tools() tools from langchain.agents import AgentType, initialize_agent from langchain_openai import OpenAI llm =
OpenAI(temperature=0)
langchain_openai.OpenAI
get_ipython().run_line_magic('pip', 'install --upgrade --quiet pymilvus') import getpass import os os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:") from langchain_community.document_loaders import TextLoader from langchain_community.vectorstores import Milvus from langchain_openai import OpenAIEmbeddings from langchain_text_splitters import CharacterTextSplitter from langchain_community.document_loaders import TextLoader loader =
TextLoader("../../modules/state_of_the_union.txt")
langchain_community.document_loaders.TextLoader
get_ipython().system('pip install databricks-sql-connector') from langchain_community.utilities import SQLDatabase db =
SQLDatabase.from_databricks(catalog="samples", schema="nyctaxi")
langchain_community.utilities.SQLDatabase.from_databricks
from langchain_community.utils.openai_functions import ( convert_pydantic_to_openai_function, ) from langchain_core.prompts import ChatPromptTemplate from langchain_core.pydantic_v1 import BaseModel, Field, validator from langchain_openai import ChatOpenAI class Joke(BaseModel): """Joke to tell user.""" setup: str =
Field(description="question to set up a joke")
langchain_core.pydantic_v1.Field
get_ipython().run_line_magic('pip', "install --upgrade --quiet faiss-gpu # For CUDA 7.5+ Supported GPU's.") get_ipython().run_line_magic('pip', 'install --upgrade --quiet faiss-cpu # For CPU Installation') import getpass import os os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:") from langchain_community.document_loaders import TextLoader from langchain_community.vectorstores import FAISS from langchain_openai import OpenAIEmbeddings from langchain_text_splitters import CharacterTextSplitter loader = TextLoader("../../../extras/modules/state_of_the_union.txt") documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) docs = text_splitter.split_documents(documents) embeddings = OpenAIEmbeddings() db = await FAISS.afrom_documents(docs, embeddings) query = "What did the president say about Ketanji Brown Jackson" docs = await db.asimilarity_search(query) print(docs[0].page_content) docs_and_scores = await db.asimilarity_search_with_score(query) docs_and_scores[0] embedding_vector = await embeddings.aembed_query(query) docs_and_scores = await db.asimilarity_search_by_vector(embedding_vector) db.save_local("faiss_index") new_db = FAISS.load_local("faiss_index", embeddings, asynchronous=True) docs = await new_db.asimilarity_search(query) docs[0] from langchain_community.embeddings.huggingface import HuggingFaceEmbeddings pkl = db.serialize_to_bytes() # serializes the faiss index embeddings =
HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
langchain_community.embeddings.huggingface.HuggingFaceEmbeddings
get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain-nvidia-ai-endpoints') import getpass import os if not os.environ.get("NVIDIA_API_KEY", "").startswith("nvapi-"): nvapi_key = getpass.getpass("Enter your NVIDIA API key: ") assert nvapi_key.startswith("nvapi-"), f"{nvapi_key[:5]}... is not a valid key" os.environ["NVIDIA_API_KEY"] = nvapi_key from langchain_nvidia_ai_endpoints import ChatNVIDIA llm = ChatNVIDIA(model="mixtral_8x7b") result = llm.invoke("Write a ballad about LangChain.") print(result.content) print(llm.batch(["What's 2*3?", "What's 2*6?"])) for chunk in llm.stream("How far can a seagull fly in one day?"): print(chunk.content, end="|") async for chunk in llm.astream( "How long does it take for monarch butterflies to migrate?" ): print(chunk.content, end="|") ChatNVIDIA.get_available_models() from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_nvidia_ai_endpoints import ChatNVIDIA prompt = ChatPromptTemplate.from_messages( [("system", "You are a helpful AI assistant named Fred."), ("user", "{input}")] ) chain = prompt | ChatNVIDIA(model="llama2_13b") | StrOutputParser() for txt in chain.stream({"input": "What's your name?"}): print(txt, end="") prompt = ChatPromptTemplate.from_messages( [ ( "system", "You are an expert coding AI. Respond only in valid python; no narration whatsoever.", ), ("user", "{input}"), ] ) chain = prompt | ChatNVIDIA(model="llama2_code_70b") | StrOutputParser() for txt in chain.stream({"input": "How do I solve this fizz buzz problem?"}): print(txt, end="") from langchain_nvidia_ai_endpoints import ChatNVIDIA llm = ChatNVIDIA(model="nemotron_steerlm_8b") complex_result = llm.invoke( "What's a PB&J?", labels={"creativity": 0, "complexity": 3, "verbosity": 0} ) print("Un-creative\n") print(complex_result.content) print("\n\nCreative\n") creative_result = llm.invoke( "What's a PB&J?", labels={"creativity": 9, "complexity": 3, "verbosity": 9} ) print(creative_result.content) from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_nvidia_ai_endpoints import ChatNVIDIA prompt = ChatPromptTemplate.from_messages( [("system", "You are a helpful AI assistant named Fred."), ("user", "{input}")] ) chain = ( prompt | ChatNVIDIA(model="nemotron_steerlm_8b").bind( labels={"creativity": 9, "complexity": 0, "verbosity": 9} ) | StrOutputParser() ) for txt in chain.stream({"input": "Why is a PB&J?"}): print(txt, end="") import IPython import requests image_url = "https://www.nvidia.com/content/dam/en-zz/Solutions/research/ai-playground/nvidia-picasso-3c33-p@2x.jpg" ## Large Image image_content = requests.get(image_url).content IPython.display.Image(image_content) from langchain_nvidia_ai_endpoints import ChatNVIDIA llm = ChatNVIDIA(model="playground_neva_22b") from langchain_core.messages import HumanMessage llm.invoke( [ HumanMessage( content=[ {"type": "text", "text": "Describe this image:"}, {"type": "image_url", "image_url": {"url": image_url}}, ] ) ] ) from langchain_core.messages import HumanMessage llm.invoke( [ HumanMessage( content=[ {"type": "text", "text": "Describe this image:"}, {"type": "image_url", "image_url": {"url": image_url}}, ] ) ], labels={"creativity": 0, "quality": 9, "complexity": 0, "verbosity": 0}, ) import IPython import requests image_url = "https://picsum.photos/seed/kitten/300/200" image_content = requests.get(image_url).content IPython.display.Image(image_content) import base64 from langchain_core.messages import HumanMessage b64_string = base64.b64encode(image_content).decode("utf-8") llm.invoke( [ HumanMessage( content=[ {"type": "text", "text": "Describe this image:"}, { "type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64_string}"}, }, ] ) ] ) base64_with_mime_type = f"data:image/png;base64,{b64_string}" llm.invoke(f'What\'s in this image?\n<img src="{base64_with_mime_type}" />') from langchain_nvidia_ai_endpoints import ChatNVIDIA kosmos = ChatNVIDIA(model="kosmos_2") from langchain_core.messages import HumanMessage def drop_streaming_key(d): """Takes in payload dictionary, outputs new payload dictionary""" if "stream" in d: d.pop("stream") return d kosmos = ChatNVIDIA(model="kosmos_2") kosmos.client.payload_fn = drop_streaming_key kosmos.invoke( [ HumanMessage( content=[ {"type": "text", "text": "Describe this image:"}, {"type": "image_url", "image_url": {"url": image_url}}, ] ) ] ) import base64 from io import BytesIO from PIL import Image img_gen = ChatNVIDIA(model="sdxl_turbo") def to_sdxl_payload(d): if d: d = {"prompt": d.get("messages", [{}])[0].get("content")} d["inference_steps"] = 4 ## why not add another argument? return d img_gen.client.payload_fn = to_sdxl_payload def to_pil_img(d): return Image.open(BytesIO(base64.b64decode(d))) (img_gen | StrOutputParser() | to_pil_img).invoke("white cat playing") from langchain_core.messages import ChatMessage from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_nvidia_ai_endpoints import ChatNVIDIA prompt = ChatPromptTemplate.from_messages( [ ChatMessage( role="context", content="Parrots and Cats have signed the peace accord." ), ("user", "{input}"), ] ) llm = ChatNVIDIA(model="nemotron_qa_8b") chain = prompt | llm |
StrOutputParser()
langchain_core.output_parsers.StrOutputParser
get_ipython().run_line_magic('pip', 'install --upgrade --quiet titan-iris') from langchain_community.llms import TitanTakeoff llm = TitanTakeoff( base_url="http://localhost:8000", generate_max_length=128, temperature=1.0 ) prompt = "What is the largest planet in the solar system?" llm(prompt) from langchain.callbacks.manager import CallbackManager from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler llm = TitanTakeoff( callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]), streaming=True ) prompt = "What is the capital of France?" llm(prompt) from langchain.chains import LLMChain from langchain.prompts import PromptTemplate llm = TitanTakeoff() template = "What is the capital of {country}" prompt = PromptTemplate.from_template(template) llm_chain =
LLMChain(llm=llm, prompt=prompt)
langchain.chains.LLMChain
from langchain.agents import Tool from langchain_community.tools.file_management.read import ReadFileTool from langchain_community.tools.file_management.write import WriteFileTool from langchain_community.utilities import SerpAPIWrapper search = SerpAPIWrapper() tools = [ Tool( name="search", func=search.run, description="useful for when you need to answer questions about current events. You should ask targeted questions", ), WriteFileTool(),
ReadFileTool()
langchain_community.tools.file_management.read.ReadFileTool
get_ipython().run_line_magic('pip', 'install --upgrade --quiet arxiv') from langchain import hub from langchain.agents import AgentExecutor, create_react_agent, load_tools from langchain_openai import ChatOpenAI llm =
ChatOpenAI(temperature=0.0)
langchain_openai.ChatOpenAI
get_ipython().run_line_magic('pip', 'install --upgrade --quiet aphrodite-engine==0.4.2') from langchain_community.llms import Aphrodite llm = Aphrodite( model="PygmalionAI/pygmalion-2-7b", trust_remote_code=True, # mandatory for hf models max_tokens=128, temperature=1.2, min_p=0.05, mirostat_mode=0, # change to 2 to use mirostat mirostat_tau=5.0, mirostat_eta=0.1, ) print( llm( '<|system|>Enter RP mode. You are Ayumu "Osaka" Kasuga.<|user|>Hey Osaka. Tell me about yourself.<|model|>' ) ) from langchain.chains import LLMChain from langchain.prompts import PromptTemplate template = """Question: {question} Answer: Let's think step by step.""" prompt =
PromptTemplate.from_template(template)
langchain.prompts.PromptTemplate.from_template
get_ipython().system(' nomic login') get_ipython().system(' nomic login token') get_ipython().system(' pip install -U langchain-nomic langchain_community tiktoken langchain-openai chromadb langchain') import os os.environ["LANGCHAIN_TRACING_V2"] = "true" os.environ["LANGCHAIN_ENDPOINT"] = "https://api.smith.langchain.com" os.environ["LANGCHAIN_API_KEY"] = "api_key" from langchain_community.document_loaders import WebBaseLoader urls = [ "https://lilianweng.github.io/posts/2023-06-23-agent/", "https://lilianweng.github.io/posts/2023-03-15-prompt-engineering/", "https://lilianweng.github.io/posts/2023-10-25-adv-attack-llm/", ] docs = [WebBaseLoader(url).load() for url in urls] docs_list = [item for sublist in docs for item in sublist] from langchain_text_splitters import CharacterTextSplitter text_splitter = CharacterTextSplitter.from_tiktoken_encoder( chunk_size=7500, chunk_overlap=100 ) doc_splits = text_splitter.split_documents(docs_list) import tiktoken encoding = tiktoken.get_encoding("cl100k_base") encoding = tiktoken.encoding_for_model("gpt-3.5-turbo") for d in doc_splits: print("The document is %s tokens" % len(encoding.encode(d.page_content))) import os from langchain_community.vectorstores import Chroma from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables import RunnableLambda, RunnablePassthrough from langchain_nomic import NomicEmbeddings from langchain_nomic.embeddings import NomicEmbeddings vectorstore = Chroma.from_documents( documents=doc_splits, collection_name="rag-chroma", embedding=NomicEmbeddings(model="nomic-embed-text-v1"), ) retriever = vectorstore.as_retriever() from langchain_community.chat_models import ChatOllama from langchain_core.prompts import ChatPromptTemplate from langchain_openai import ChatOpenAI template = """Answer the question based only on the following context: {context} Question: {question} """ prompt = ChatPromptTemplate.from_template(template) model = ChatOpenAI(temperature=0, model="gpt-4-1106-preview") ollama_llm = "mistral:instruct" model_local = ChatOllama(model=ollama_llm) chain = ( {"context": retriever, "question":
RunnablePassthrough()
langchain_core.runnables.RunnablePassthrough
get_ipython().run_line_magic('pip', 'install --upgrade --quiet dashvector dashscope') import getpass import os os.environ["DASHVECTOR_API_KEY"] = getpass.getpass("DashVector API Key:") os.environ["DASHSCOPE_API_KEY"] = getpass.getpass("DashScope API Key:") from langchain_community.embeddings.dashscope import DashScopeEmbeddings from langchain_community.vectorstores import DashVector from langchain_text_splitters import CharacterTextSplitter from langchain_community.document_loaders import TextLoader loader = TextLoader("../../modules/state_of_the_union.txt") documents = loader.load() text_splitter =
CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
langchain_text_splitters.CharacterTextSplitter
import os import pprint os.environ["SERPER_API_KEY"] = "" from langchain_community.utilities import GoogleSerperAPIWrapper search = GoogleSerperAPIWrapper() search.run("Obama's first name?") os.environ["OPENAI_API_KEY"] = "" from langchain.agents import AgentType, Tool, initialize_agent from langchain_community.utilities import GoogleSerperAPIWrapper from langchain_openai import OpenAI 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?" ) search = GoogleSerperAPIWrapper() results = search.results("Apple Inc.") pprint.pp(results) search = GoogleSerperAPIWrapper(type="images") results = search.results("Lion") pprint.pp(results) search = GoogleSerperAPIWrapper(type="news") results = search.results("Tesla Inc.") pprint.pp(results) search = GoogleSerperAPIWrapper(type="news", tbs="qdr:h") results = search.results("Tesla Inc.") pprint.pp(results) search =
GoogleSerperAPIWrapper(type="places")
langchain_community.utilities.GoogleSerperAPIWrapper
get_ipython().run_line_magic('pip', 'install --upgrade --quiet lark') get_ipython().run_line_magic('pip', 'install --upgrade --quiet chromadb') import getpass import os os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:") from langchain_community.vectorstores import Chroma from langchain_core.documents import Document from langchain_openai import OpenAIEmbeddings embeddings = OpenAIEmbeddings() docs = [ Document( page_content="A bunch of scientists bring back dinosaurs and mayhem breaks loose", metadata={"year": 1993, "rating": 7.7, "genre": "science fiction"}, ), Document( page_content="Leo DiCaprio gets lost in a dream within a dream within a dream within a ...", metadata={"year": 2010, "director": "Christopher Nolan", "rating": 8.2}, ), Document( page_content="A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea", metadata={"year": 2006, "director": "Satoshi Kon", "rating": 8.6}, ), Document( page_content="A bunch of normal-sized women are supremely wholesome and some men pine after them", metadata={"year": 2019, "director": "Greta Gerwig", "rating": 8.3}, ), Document( page_content="Toys come alive and have a blast doing so", metadata={"year": 1995, "genre": "animated"}, ), Document( page_content="Three men walk into the Zone, three men walk out of the Zone", metadata={ "year": 1979, "director": "Andrei Tarkovsky", "genre": "science fiction", "rating": 9.9, }, ), ] vectorstore =
Chroma.from_documents(docs, embeddings)
langchain_community.vectorstores.Chroma.from_documents
from langchain.agents import Tool from langchain_community.tools.file_management.read import ReadFileTool from langchain_community.tools.file_management.write import WriteFileTool from langchain_community.utilities import SerpAPIWrapper search = SerpAPIWrapper() tools = [ Tool( name="search", func=search.run, description="useful for when you need to answer questions about current events. You should ask targeted questions", ), WriteFileTool(), ReadFileTool(), ] from langchain.docstore import InMemoryDocstore from langchain_community.vectorstores import FAISS from langchain_openai import OpenAIEmbeddings embeddings_model = OpenAIEmbeddings() import faiss embedding_size = 1536 index = faiss.IndexFlatL2(embedding_size) vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {}) from langchain_experimental.autonomous_agents import AutoGPT from langchain_openai import ChatOpenAI agent = AutoGPT.from_llm_and_tools( ai_name="Tom", ai_role="Assistant", tools=tools, llm=ChatOpenAI(temperature=0), memory=vectorstore.as_retriever(), ) agent.chain.verbose = True agent.run(["write a weather report for SF today"]) from langchain_community.chat_message_histories import FileChatMessageHistory agent = AutoGPT.from_llm_and_tools( ai_name="Tom", ai_role="Assistant", tools=tools, llm=
ChatOpenAI(temperature=0)
langchain_openai.ChatOpenAI
from langchain_community.document_transformers.openai_functions import ( create_metadata_tagger, ) from langchain_core.documents import Document from langchain_openai import ChatOpenAI schema = { "properties": { "movie_title": {"type": "string"}, "critic": {"type": "string"}, "tone": {"type": "string", "enum": ["positive", "negative"]}, "rating": { "type": "integer", "description": "The number of stars the critic rated the movie", }, }, "required": ["movie_title", "critic", "tone"], } llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613") document_transformer =
create_metadata_tagger(metadata_schema=schema, llm=llm)
langchain_community.document_transformers.openai_functions.create_metadata_tagger
from langchain_community.llms import Ollama llm =
Ollama(model="llama2")
langchain_community.llms.Ollama
get_ipython().system(' pip install langchain unstructured[all-docs] pydantic lxml') from typing import Any from pydantic import BaseModel from unstructured.partition.pdf import partition_pdf path = "/Users/rlm/Desktop/Papers/LLaVA/" raw_pdf_elements = partition_pdf( filename=path + "LLaVA.pdf", extract_images_in_pdf=True, infer_table_structure=True, chunking_strategy="by_title", max_characters=4000, new_after_n_chars=3800, combine_text_under_n_chars=2000, image_output_dir_path=path, ) category_counts = {} for element in raw_pdf_elements: category = str(type(element)) if category in category_counts: category_counts[category] += 1 else: category_counts[category] = 1 unique_categories = set(category_counts.keys()) category_counts class Element(BaseModel): type: str text: Any categorized_elements = [] for element in raw_pdf_elements: if "unstructured.documents.elements.Table" in str(type(element)): categorized_elements.append(Element(type="table", text=str(element))) elif "unstructured.documents.elements.CompositeElement" in str(type(element)): categorized_elements.append(Element(type="text", text=str(element))) table_elements = [e for e in categorized_elements if e.type == "table"] print(len(table_elements)) text_elements = [e for e in categorized_elements if e.type == "text"] print(len(text_elements)) from langchain_community.chat_models import ChatOllama from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate prompt_text = """You are an assistant tasked with summarizing tables and text. \ Give a concise summary of the table or text. Table or text chunk: {element} """ prompt = ChatPromptTemplate.from_template(prompt_text) model = ChatOllama(model="llama2:13b-chat") summarize_chain = {"element": lambda x: x} | prompt | model | StrOutputParser() texts = [i.text for i in text_elements if i.text != ""] text_summaries = summarize_chain.batch(texts, {"max_concurrency": 5}) tables = [i.text for i in table_elements] table_summaries = summarize_chain.batch(tables, {"max_concurrency": 5}) get_ipython().run_cell_magic('bash', '', '\n# Define the directory containing the images\nIMG_DIR=~/Desktop/Papers/LLaVA/\n\n# Loop through each image in the directory\nfor img in "${IMG_DIR}"*.jpg; do\n # Extract the base name of the image without extension\n base_name=$(basename "$img" .jpg)\n\n # Define the output file name based on the image name\n output_file="${IMG_DIR}${base_name}.txt"\n\n # Execute the command and save the output to the defined output file\n /Users/rlm/Desktop/Code/llama.cpp/bin/llava -m ../models/llava-7b/ggml-model-q5_k.gguf --mmproj ../models/llava-7b/mmproj-model-f16.gguf --temp 0.1 -p "Describe the image in detail. Be specific about graphs, such as bar plots." --image "$img" > "$output_file"\n\ndone\n') import glob import os file_paths = glob.glob(os.path.expanduser(os.path.join(path, "*.txt"))) img_summaries = [] for file_path in file_paths: with open(file_path, "r") as file: img_summaries.append(file.read()) cleaned_img_summary = [ s.split("clip_model_load: total allocated memory: 201.27 MB\n\n", 1)[1].strip() for s in img_summaries ] import uuid from langchain.retrievers.multi_vector import MultiVectorRetriever from langchain.storage import InMemoryStore from langchain_community.embeddings import GPT4AllEmbeddings from langchain_community.vectorstores import Chroma from langchain_core.documents import Document vectorstore = Chroma( collection_name="summaries", embedding_function=GPT4AllEmbeddings() ) store = InMemoryStore() # <- Can we extend this to images id_key = "doc_id" retriever = MultiVectorRetriever( vectorstore=vectorstore, docstore=store, id_key=id_key, ) doc_ids = [str(uuid.uuid4()) for _ in texts] summary_texts = [ Document(page_content=s, metadata={id_key: doc_ids[i]}) for i, s in enumerate(text_summaries) ] retriever.vectorstore.add_documents(summary_texts) retriever.docstore.mset(list(zip(doc_ids, texts))) table_ids = [str(uuid.uuid4()) for _ in tables] summary_tables = [
Document(page_content=s, metadata={id_key: table_ids[i]})
langchain_core.documents.Document
get_ipython().run_line_magic('pip', 'install --upgrade --quiet neo4j') get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain-openai') get_ipython().run_line_magic('pip', 'install --upgrade --quiet tiktoken') import getpass import os os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:") from langchain.docstore.document import Document from langchain_community.document_loaders import TextLoader from langchain_community.vectorstores import Neo4jVector from langchain_openai import OpenAIEmbeddings from langchain_text_splitters import CharacterTextSplitter loader =
TextLoader("../../modules/state_of_the_union.txt")
langchain_community.document_loaders.TextLoader
get_ipython().run_line_magic('pip', 'install --upgrade --quiet sagemaker') get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain-openai') get_ipython().run_line_magic('pip', 'install --upgrade --quiet google-search-results') import os os.environ["OPENAI_API_KEY"] = "<ADD-KEY-HERE>" os.environ["SERPAPI_API_KEY"] = "<ADD-KEY-HERE>" from langchain.agents import initialize_agent, load_tools from langchain.callbacks import SageMakerCallbackHandler from langchain.chains import LLMChain, SimpleSequentialChain from langchain.prompts import PromptTemplate from langchain_openai import OpenAI from sagemaker.analytics import ExperimentAnalytics from sagemaker.experiments.run import Run from sagemaker.session import Session HPARAMS = { "temperature": 0.1, "model_name": "gpt-3.5-turbo-instruct", } BUCKET_NAME = None EXPERIMENT_NAME = "langchain-sagemaker-tracker" session = Session(default_bucket=BUCKET_NAME) RUN_NAME = "run-scenario-1" PROMPT_TEMPLATE = "tell me a joke about {topic}" INPUT_VARIABLES = {"topic": "fish"} with Run( experiment_name=EXPERIMENT_NAME, run_name=RUN_NAME, sagemaker_session=session ) as run: sagemaker_callback = SageMakerCallbackHandler(run) llm = OpenAI(callbacks=[sagemaker_callback], **HPARAMS) prompt = PromptTemplate.from_template(template=PROMPT_TEMPLATE) chain = LLMChain(llm=llm, prompt=prompt, callbacks=[sagemaker_callback]) chain.run(**INPUT_VARIABLES) sagemaker_callback.flush_tracker() RUN_NAME = "run-scenario-2" PROMPT_TEMPLATE_1 = """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_2 = """You are a play critic from the New York Times. Given the synopsis of play, it is your job to write a review for that play. Play Synopsis: {synopsis} Review from a New York Times play critic of the above play:""" INPUT_VARIABLES = { "input": "documentary about good video games that push the boundary of game design" } with Run( experiment_name=EXPERIMENT_NAME, run_name=RUN_NAME, sagemaker_session=session ) as run: sagemaker_callback = SageMakerCallbackHandler(run) prompt_template1 = PromptTemplate.from_template(template=PROMPT_TEMPLATE_1) prompt_template2 = PromptTemplate.from_template(template=PROMPT_TEMPLATE_2) llm = OpenAI(callbacks=[sagemaker_callback], **HPARAMS) chain1 = LLMChain(llm=llm, prompt=prompt_template1, callbacks=[sagemaker_callback]) chain2 = LLMChain(llm=llm, prompt=prompt_template2, callbacks=[sagemaker_callback]) overall_chain = SimpleSequentialChain( chains=[chain1, chain2], callbacks=[sagemaker_callback] ) overall_chain.run(**INPUT_VARIABLES) sagemaker_callback.flush_tracker() RUN_NAME = "run-scenario-3" PROMPT_TEMPLATE = "Who is the oldest person alive? And what is their current age raised to the power of 1.51?" with Run( experiment_name=EXPERIMENT_NAME, run_name=RUN_NAME, sagemaker_session=session ) as run: sagemaker_callback = SageMakerCallbackHandler(run) llm =
OpenAI(callbacks=[sagemaker_callback], **HPARAMS)
langchain_openai.OpenAI
get_ipython().run_line_magic('pip', 'install --upgrade --quiet neo4j') get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain-openai') get_ipython().run_line_magic('pip', 'install --upgrade --quiet tiktoken') import getpass import os os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:") from langchain.docstore.document import Document from langchain_community.document_loaders import TextLoader from langchain_community.vectorstores import Neo4jVector from langchain_openai import OpenAIEmbeddings from langchain_text_splitters import CharacterTextSplitter loader = TextLoader("../../modules/state_of_the_union.txt") documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) docs = text_splitter.split_documents(documents) embeddings =
OpenAIEmbeddings()
langchain_openai.OpenAIEmbeddings
get_ipython().run_line_magic('pip', 'install --upgrade --quiet "docarray"') from langchain_community.document_loaders import TextLoader from langchain_community.vectorstores import DocArrayInMemorySearch from langchain_openai import OpenAIEmbeddings from langchain_text_splitters import CharacterTextSplitter documents =
TextLoader("../../modules/state_of_the_union.txt")
langchain_community.document_loaders.TextLoader
from langchain.prompts import ChatMessagePromptTemplate prompt = "May the {subject} be with you" chat_message_prompt = ChatMessagePromptTemplate.from_template( role="Jedi", template=prompt ) chat_message_prompt.format(subject="force") from langchain.prompts import ( ChatPromptTemplate, HumanMessagePromptTemplate, MessagesPlaceholder, ) human_prompt = "Summarize our conversation so far in {word_count} words." human_message_template = HumanMessagePromptTemplate.from_template(human_prompt) chat_prompt = ChatPromptTemplate.from_messages( [MessagesPlaceholder(variable_name="conversation"), human_message_template] ) from langchain_core.messages import AIMessage, HumanMessage human_message =
HumanMessage(content="What is the best way to learn programming?")
langchain_core.messages.HumanMessage
get_ipython().run_line_magic('pip', 'install --upgrade --quiet rellm > /dev/null') import logging logging.basicConfig(level=logging.ERROR) prompt = """Human: "What's the capital of the United States?" AI Assistant:{ "action": "Final Answer", "action_input": "The capital of the United States is Washington D.C." } Human: "What's the capital of Pennsylvania?" AI Assistant:{ "action": "Final Answer", "action_input": "The capital of Pennsylvania is Harrisburg." } Human: "What 2 + 5?" AI Assistant:{ "action": "Final Answer", "action_input": "2 + 5 = 7." } Human: 'What's the capital of Maryland?' AI Assistant:""" from langchain_community.llms import HuggingFacePipeline from transformers import pipeline hf_model = pipeline( "text-generation", model="cerebras/Cerebras-GPT-590M", max_new_tokens=200 ) original_model =
HuggingFacePipeline(pipeline=hf_model)
langchain_community.llms.HuggingFacePipeline
get_ipython().run_line_magic('pip', 'install --upgrade --quiet feedparser newspaper3k listparser') from langchain_community.document_loaders import RSSFeedLoader urls = ["https://news.ycombinator.com/rss"] loader = RSSFeedLoader(urls=urls) data = loader.load() print(len(data)) print(data[0].page_content) loader =
RSSFeedLoader(urls=urls, nlp=True)
langchain_community.document_loaders.RSSFeedLoader
from langchain.agents import Tool from langchain_community.tools.file_management.read import ReadFileTool from langchain_community.tools.file_management.write import WriteFileTool from langchain_community.utilities import SerpAPIWrapper search = SerpAPIWrapper() tools = [ Tool( name="search", func=search.run, description="useful for when you need to answer questions about current events. You should ask targeted questions", ), WriteFileTool(), ReadFileTool(), ] from langchain.docstore import InMemoryDocstore from langchain_community.vectorstores import FAISS from langchain_openai import OpenAIEmbeddings embeddings_model = OpenAIEmbeddings() import faiss embedding_size = 1536 index = faiss.IndexFlatL2(embedding_size) vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {}) from langchain_experimental.autonomous_agents import AutoGPT from langchain_openai import ChatOpenAI agent = AutoGPT.from_llm_and_tools( ai_name="Tom", ai_role="Assistant", tools=tools, llm=
ChatOpenAI(temperature=0)
langchain_openai.ChatOpenAI
import os os.environ["LANGCHAIN_WANDB_TRACING"] = "true" os.environ["WANDB_PROJECT"] = "langchain-tracing" from langchain.agents import AgentType, initialize_agent, load_tools from langchain.callbacks import wandb_tracing_enabled from langchain_openai import OpenAI llm =
OpenAI(temperature=0)
langchain_openai.OpenAI
from langchain_experimental.llm_bash.base import LLMBashChain from langchain_openai import OpenAI llm =
OpenAI(temperature=0)
langchain_openai.OpenAI
get_ipython().run_line_magic('pip', 'install --upgrade --quiet pyvespa') from vespa.package import ApplicationPackage, Field, RankProfile app_package = ApplicationPackage(name="testapp") app_package.schema.add_fields( Field( name="text", type="string", indexing=["index", "summary"], index="enable-bm25" ), Field( name="embedding", type="tensor<float>(x[384])", indexing=["attribute", "summary"], attribute=["distance-metric: angular"], ), ) app_package.schema.add_rank_profile( RankProfile( name="default", first_phase="closeness(field, embedding)", inputs=[("query(query_embedding)", "tensor<float>(x[384])")], ) ) from vespa.deployment import VespaDocker vespa_docker = VespaDocker() vespa_app = vespa_docker.deploy(application_package=app_package) from langchain_community.document_loaders import TextLoader from langchain_text_splitters import CharacterTextSplitter loader =
TextLoader("../../modules/state_of_the_union.txt")
langchain_community.document_loaders.TextLoader
from langchain.callbacks import FileCallbackHandler from langchain.chains import LLMChain from langchain.prompts import PromptTemplate from langchain_openai import OpenAI from loguru import logger logfile = "output.log" logger.add(logfile, colorize=True, enqueue=True) handler = FileCallbackHandler(logfile) llm = OpenAI() prompt =
PromptTemplate.from_template("1 + {number} = ")
langchain.prompts.PromptTemplate.from_template
from langchain_community.document_loaders import TextLoader from langchain_community.embeddings.sentence_transformer import ( SentenceTransformerEmbeddings, ) from langchain_community.vectorstores import Chroma from langchain_text_splitters import CharacterTextSplitter loader = TextLoader("../../modules/state_of_the_union.txt") documents = loader.load() text_splitter =
CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
langchain_text_splitters.CharacterTextSplitter
from langchain_openai import ChatOpenAI model = ChatOpenAI(temperature=0, model="gpt-4-turbo-preview") from langchain import hub from langchain_core.prompts import PromptTemplate select_prompt = hub.pull("hwchase17/self-discovery-select") select_prompt.pretty_print() adapt_prompt = hub.pull("hwchase17/self-discovery-adapt") adapt_prompt.pretty_print() structured_prompt = hub.pull("hwchase17/self-discovery-structure") structured_prompt.pretty_print() reasoning_prompt = hub.pull("hwchase17/self-discovery-reasoning") reasoning_prompt.pretty_print() reasoning_prompt from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables import RunnablePassthrough select_chain = select_prompt | model | StrOutputParser() adapt_chain = adapt_prompt | model | StrOutputParser() structure_chain = structured_prompt | model |
StrOutputParser()
langchain_core.output_parsers.StrOutputParser
from langchain.memory import ConversationTokenBufferMemory from langchain_openai import OpenAI llm = OpenAI() memory =
ConversationTokenBufferMemory(llm=llm, max_token_limit=10)
langchain.memory.ConversationTokenBufferMemory
import os os.environ["EXA_API_KEY"] = "..." get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain-exa') get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain langchain-openai') from langchain_core.prompts import PromptTemplate from langchain_core.runnables import RunnableParallel, RunnablePassthrough from langchain_exa import ExaSearchRetriever, TextContentsOptions from langchain_openai import ChatOpenAI retriever = ExaSearchRetriever( k=5, text_contents_options=TextContentsOptions(max_length=200) ) prompt = PromptTemplate.from_template( """Answer the following query based on the following context: query: {query} <context> {context} </context""" ) llm = ChatOpenAI() chain = ( RunnableParallel({"context": retriever, "query": RunnablePassthrough()}) | prompt | llm ) chain.invoke("When is the best time to visit japan?") get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain-exa') from exa_py import Exa from langchain.agents import tool exa = Exa(api_key=os.environ["EXA_API_KEY"]) @tool def search(query: str): """Search for a webpage based on the query.""" return exa.search(f"{query}", use_autoprompt=True, num_results=5) @tool def find_similar(url: str): """Search for webpages similar to a given URL. The url passed in should be a URL returned from `search`. """ return exa.find_similar(url, num_results=5) @tool def get_contents(ids: list[str]): """Get the contents of a webpage. The ids passed in should be a list of ids returned from `search`. """ return exa.get_contents(ids) tools = [search, get_contents, find_similar] from langchain.agents import AgentExecutor, OpenAIFunctionsAgent from langchain_core.messages import SystemMessage from langchain_openai import ChatOpenAI llm =
ChatOpenAI(temperature=0)
langchain_openai.ChatOpenAI
get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain langchain-community langchainhub gpt4all chromadb') from langchain_community.document_loaders import WebBaseLoader from langchain_text_splitters import RecursiveCharacterTextSplitter loader =
WebBaseLoader("https://lilianweng.github.io/posts/2023-06-23-agent/")
langchain_community.document_loaders.WebBaseLoader