prompt
stringlengths
43
25.9k
completion
stringlengths
7
362
api
stringlengths
18
90
get_ipython().run_line_magic('pip', 'install --upgrade --quiet docx2txt') from langchain_community.document_loaders import Docx2txtLoader loader = Docx2txtLoader("example_data/fake.docx") data = loader.load() data from langchain_community.document_loaders import UnstructuredWordDocumentLoader loader = UnstructuredWordDocumentLoader("example_data/fake.docx") data = loader.load() data loader =
UnstructuredWordDocumentLoader("example_data/fake.docx", mode="elements")
langchain_community.document_loaders.UnstructuredWordDocumentLoader
import nest_asyncio from langchain.chains.graph_qa import GremlinQAChain from langchain.schema import Document from langchain_community.graphs import GremlinGraph from langchain_community.graphs.graph_document import GraphDocument, Node, Relationship from langchain_openai import AzureChatOpenAI cosmosdb_name = "mycosmosdb" cosmosdb_db_id = "graphtesting" cosmosdb_db_graph_id = "mygraph" cosmosdb_access_Key = "longstring==" graph = GremlinGraph( url=f"=wss://{cosmosdb_name}.gremlin.cosmos.azure.com:443/", username=f"/dbs/{cosmosdb_db_id}/colls/{cosmosdb_db_graph_id}", password=cosmosdb_access_Key, ) source_doc =
Document( page_content="Matrix is a movie where Keanu Reeves, Laurence Fishburne and Carrie-Anne Moss acted." )
langchain.schema.Document
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) synopsis_chain = LLMChain(llm=llm, prompt=prompt_template, callbacks=callbacks) test_prompts = [{"title": "Documentary about Bigfoot in Paris"}] print(synopsis_chain.apply(test_prompts)) comet_callback.flush_tracker(synopsis_chain, finish=True) from langchain.agents import initialize_agent, load_tools 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=["agent"], ) callbacks = [StdOutCallbackHandler(), comet_callback] llm =
OpenAI(temperature=0.9, callbacks=callbacks)
langchain_openai.OpenAI
from langchain.callbacks.manager import CallbackManager from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler from langchain.prompts import PromptTemplate from langchain_community.llms import TitanTakeoffPro llm = TitanTakeoffPro() output = llm("What is the weather in London in August?") print(output) llm = TitanTakeoffPro( base_url="http://localhost:3000", min_new_tokens=128, max_new_tokens=512, no_repeat_ngram_size=2, sampling_topk=1, sampling_topp=1.0, sampling_temperature=1.0, repetition_penalty=1.0, regex_string="", ) output = llm("What is the largest rainforest in the world?") print(output) llm = TitanTakeoffPro() rich_output = llm.generate(["What is Deep Learning?", "What is Machine Learning?"]) print(rich_output.generations) llm = TitanTakeoffPro( streaming=True, callback_manager=CallbackManager([
StreamingStdOutCallbackHandler()
langchain.callbacks.streaming_stdout.StreamingStdOutCallbackHandler
get_ipython().system('pip install langchain lark openai elasticsearch pandas') import pandas as pd details = ( pd.read_csv("~/Downloads/archive/Hotel_details.csv") .drop_duplicates(subset="hotelid") .set_index("hotelid") ) attributes = pd.read_csv( "~/Downloads/archive/Hotel_Room_attributes.csv", index_col="id" ) price = pd.read_csv("~/Downloads/archive/hotels_RoomPrice.csv", index_col="id") latest_price = price.drop_duplicates(subset="refid", keep="last")[ [ "hotelcode", "roomtype", "onsiterate", "roomamenities", "maxoccupancy", "mealinclusiontype", ] ] latest_price["ratedescription"] = attributes.loc[latest_price.index]["ratedescription"] latest_price = latest_price.join( details[["hotelname", "city", "country", "starrating"]], on="hotelcode" ) latest_price = latest_price.rename({"ratedescription": "roomdescription"}, axis=1) latest_price["mealsincluded"] = ~latest_price["mealinclusiontype"].isnull() latest_price.pop("hotelcode") latest_price.pop("mealinclusiontype") latest_price = latest_price.reset_index(drop=True) latest_price.head() from langchain_openai import ChatOpenAI model = ChatOpenAI(model="gpt-4") res = model.predict( "Below is a table with information about hotel rooms. " "Return a JSON list with an entry for each column. Each entry should have " '{"name": "column name", "description": "column description", "type": "column data type"}' f"\n\n{latest_price.head()}\n\nJSON:\n" ) import json attribute_info = json.loads(res) attribute_info latest_price.nunique()[latest_price.nunique() < 40] attribute_info[-2][ "description" ] += f". Valid values are {sorted(latest_price['starrating'].value_counts().index.tolist())}" attribute_info[3][ "description" ] += f". Valid values are {sorted(latest_price['maxoccupancy'].value_counts().index.tolist())}" attribute_info[-3][ "description" ] += f". Valid values are {sorted(latest_price['country'].value_counts().index.tolist())}" attribute_info from langchain.chains.query_constructor.base import ( get_query_constructor_prompt, load_query_constructor_runnable, ) doc_contents = "Detailed description of a hotel room" prompt = get_query_constructor_prompt(doc_contents, attribute_info) print(prompt.format(query="{query}")) chain = load_query_constructor_runnable( ChatOpenAI(model="gpt-3.5-turbo", temperature=0), doc_contents, attribute_info ) chain.invoke({"query": "I want a hotel in Southern Europe and my budget is 200 bucks."}) chain.invoke( { "query": "Find a 2-person room in Vienna or London, preferably with meals included and AC" } ) attribute_info[-3][ "description" ] += ". NOTE: Only use the 'eq' operator if a specific country is mentioned. If a region is mentioned, include all relevant countries in filter." chain = load_query_constructor_runnable(
ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
langchain_openai.ChatOpenAI
get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain-google-spanner') 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 spanner.googleapis.com') INSTANCE = "my-instance" # @param {type: "string"} DATABASE = "my-database" # @param {type: "string"} TABLE_NAME = "vectors_search_data" # @param {type: "string"} from langchain_google_spanner import SecondaryIndex, SpannerVectorStore, TableColumn SpannerVectorStore.init_vector_store_table( instance_id=INSTANCE, database_id=DATABASE, table_name=TABLE_NAME, id_column="row_id", metadata_columns=[ TableColumn(name="metadata", type="JSON", is_null=True), TableColumn(name="title", type="STRING(MAX)", is_null=False), ], secondary_indexes=[
SecondaryIndex(index_name="row_id_and_title", columns=["row_id", "title"])
langchain_google_spanner.SecondaryIndex
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) tool = WikipediaQueryRun(api_wrapper=api_wrapper) tools = [tool] prompt =
hub.pull("hwchase17/react")
langchain.hub.pull
from typing import Any, Dict, List, Union from langchain.agents import AgentType, initialize_agent, load_tools from langchain.callbacks.base import BaseCallbackHandler from langchain_core.agents import AgentAction from langchain_openai import OpenAI class MyCustomHandlerOne(BaseCallbackHandler): def on_llm_start( self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any ) -> Any: print(f"on_llm_start {serialized['name']}") def on_llm_new_token(self, token: str, **kwargs: Any) -> Any: print(f"on_new_token {token}") def on_llm_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> Any: """Run when LLM errors.""" def on_chain_start( self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any ) -> Any: print(f"on_chain_start {serialized['name']}") def on_tool_start( self, serialized: Dict[str, Any], input_str: str, **kwargs: Any ) -> Any: print(f"on_tool_start {serialized['name']}") def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any: print(f"on_agent_action {action}") class MyCustomHandlerTwo(BaseCallbackHandler): def on_llm_start( self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any ) -> Any: print(f"on_llm_start (I'm the second handler!!) {serialized['name']}") handler1 = MyCustomHandlerOne() handler2 = MyCustomHandlerTwo() llm = OpenAI(temperature=0, streaming=True, callbacks=[handler2]) tools =
load_tools(["llm-math"], llm=llm)
langchain.agents.load_tools
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) prompt = PromptTemplate.from_template( "Tell me a joke about {topic}" ).configurable_alternatives( ConfigurableField(id="prompt"), default_key="joke", poem=PromptTemplate.from_template("Write a short poem about {topic}"), ) chain = prompt | llm chain.invoke({"topic": "bears"}) chain.with_config(configurable={"prompt": "poem"}).invoke({"topic": "bears"}) llm = ChatAnthropic(temperature=0).configurable_alternatives(
ConfigurableField(id="llm")
langchain_core.runnables.ConfigurableField
get_ipython().system('pip3 install clickhouse-sqlalchemy InstructorEmbedding sentence_transformers openai langchain-experimental') import getpass from os import environ from langchain.chains import LLMChain from langchain.prompts import PromptTemplate from langchain_community.utilities import SQLDatabase from langchain_experimental.sql.vector_sql import VectorSQLDatabaseChain from langchain_openai import OpenAI from sqlalchemy import MetaData, create_engine MYSCALE_HOST = "msc-4a9e710a.us-east-1.aws.staging.myscale.cloud" MYSCALE_PORT = 443 MYSCALE_USER = "chatdata" MYSCALE_PASSWORD = "myscale_rocks" OPENAI_API_KEY = getpass.getpass("OpenAI API Key:") engine = create_engine( f"clickhouse://{MYSCALE_USER}:{MYSCALE_PASSWORD}@{MYSCALE_HOST}:{MYSCALE_PORT}/default?protocol=https" ) metadata = MetaData(bind=engine) environ["OPENAI_API_KEY"] = OPENAI_API_KEY from langchain_community.embeddings import HuggingFaceInstructEmbeddings from langchain_experimental.sql.vector_sql import VectorSQLOutputParser output_parser = VectorSQLOutputParser.from_embeddings( model=HuggingFaceInstructEmbeddings( model_name="hkunlp/instructor-xl", model_kwargs={"device": "cpu"} ) ) from langchain.callbacks import StdOutCallbackHandler from langchain_community.utilities.sql_database import SQLDatabase from langchain_experimental.sql.prompt import MYSCALE_PROMPT from langchain_experimental.sql.vector_sql import VectorSQLDatabaseChain from langchain_openai import OpenAI chain = VectorSQLDatabaseChain( llm_chain=LLMChain( llm=OpenAI(openai_api_key=OPENAI_API_KEY, temperature=0), prompt=MYSCALE_PROMPT, ), top_k=10, return_direct=True, sql_cmd_parser=output_parser, database=SQLDatabase(engine, None, metadata), ) import pandas as pd pd.DataFrame( chain.run( "Please give me 10 papers to ask what is PageRank?", callbacks=[StdOutCallbackHandler()], ) ) from langchain.chains.qa_with_sources.retrieval import RetrievalQAWithSourcesChain from langchain_experimental.retrievers.vector_sql_database import ( VectorSQLDatabaseChainRetriever, ) from langchain_experimental.sql.prompt import MYSCALE_PROMPT from langchain_experimental.sql.vector_sql import ( VectorSQLDatabaseChain, VectorSQLRetrieveAllOutputParser, ) from langchain_openai import ChatOpenAI output_parser_retrieve_all = VectorSQLRetrieveAllOutputParser.from_embeddings( output_parser.model ) chain = VectorSQLDatabaseChain.from_llm( llm=OpenAI(openai_api_key=OPENAI_API_KEY, temperature=0), prompt=MYSCALE_PROMPT, top_k=10, return_direct=True, db=
SQLDatabase(engine, None, metadata)
langchain_community.utilities.sql_database.SQLDatabase
get_ipython().run_cell_magic('writefile', 'telegram_conversation.json', '{\n "name": "Jiminy",\n "type": "personal_chat",\n "id": 5965280513,\n "messages": [\n {\n "id": 1,\n "type": "message",\n "date": "2023-08-23T13:11:23",\n "date_unixtime": "1692821483",\n "from": "Jiminy Cricket",\n "from_id": "user123450513",\n "text": "You better trust your conscience",\n "text_entities": [\n {\n "type": "plain",\n "text": "You better trust your conscience"\n }\n ]\n },\n {\n "id": 2,\n "type": "message",\n "date": "2023-08-23T13:13:20",\n "date_unixtime": "1692821600",\n "from": "Batman & Robin",\n "from_id": "user6565661032",\n "text": "What did you just say?",\n "text_entities": [\n {\n "type": "plain",\n "text": "What did you just say?"\n }\n ]\n }\n ]\n}\n') from langchain_community.chat_loaders.telegram import TelegramChatLoader loader = TelegramChatLoader( path="./telegram_conversation.json", ) from typing import List from langchain_community.chat_loaders.base import ChatSession from langchain_community.chat_loaders.utils import ( map_ai_messages, merge_chat_runs, ) raw_messages = loader.lazy_load() merged_messages =
merge_chat_runs(raw_messages)
langchain_community.chat_loaders.utils.merge_chat_runs
from typing import List from langchain.output_parsers import PydanticOutputParser from langchain_core.pydantic_v1 import BaseModel, Field from langchain_openai import ChatOpenAI class Actor(BaseModel): name: str = Field(description="name of an actor") film_names: List[str] = Field(description="list of names of films they starred in") actor_query = "Generate the filmography for a random actor." parser =
PydanticOutputParser(pydantic_object=Actor)
langchain.output_parsers.PydanticOutputParser
from langchain.prompts.few_shot import FewShotPromptTemplate from langchain.prompts.prompt import PromptTemplate examples = [ { "question": "Who lived longer, Muhammad Ali or Alan Turing?", "answer": """ Are follow up questions needed here: Yes. Follow up: How old was Muhammad Ali when he died? Intermediate answer: Muhammad Ali was 74 years old when he died. Follow up: How old was Alan Turing when he died? Intermediate answer: Alan Turing was 41 years old when he died. So the final answer is: Muhammad Ali """, }, { "question": "When was the founder of craigslist born?", "answer": """ Are follow up questions needed here: Yes. Follow up: Who was the founder of craigslist? Intermediate answer: Craigslist was founded by Craig Newmark. Follow up: When was Craig Newmark born? Intermediate answer: Craig Newmark was born on December 6, 1952. So the final answer is: December 6, 1952 """, }, { "question": "Who was the maternal grandfather of George Washington?", "answer": """ Are follow up questions needed here: Yes. Follow up: Who was the mother of George Washington? Intermediate answer: The mother of George Washington was Mary Ball Washington. Follow up: Who was the father of Mary Ball Washington? Intermediate answer: The father of Mary Ball Washington was Joseph Ball. So the final answer is: Joseph Ball """, }, { "question": "Are both the directors of Jaws and Casino Royale from the same country?", "answer": """ Are follow up questions needed here: Yes. Follow up: Who is the director of Jaws? Intermediate Answer: The director of Jaws is Steven Spielberg. Follow up: Where is Steven Spielberg from? Intermediate Answer: The United States. Follow up: Who is the director of Casino Royale? Intermediate Answer: The director of Casino Royale is Martin Campbell. Follow up: Where is Martin Campbell from? Intermediate Answer: New Zealand. So the final answer is: No """, }, ] example_prompt = PromptTemplate( input_variables=["question", "answer"], template="Question: {question}\n{answer}" ) print(example_prompt.format(**examples[0])) prompt = FewShotPromptTemplate( examples=examples, example_prompt=example_prompt, suffix="Question: {input}", input_variables=["input"], ) print(prompt.format(input="Who was the father of Mary Ball Washington?")) from langchain.prompts.example_selector import SemanticSimilarityExampleSelector from langchain_community.vectorstores import Chroma from langchain_openai import OpenAIEmbeddings example_selector = SemanticSimilarityExampleSelector.from_examples( examples,
OpenAIEmbeddings()
langchain_openai.OpenAIEmbeddings
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")
langchain_openai.ChatOpenAI
from langchain.indexes import SQLRecordManager, index from langchain_core.documents import Document from langchain_elasticsearch import ElasticsearchStore from langchain_openai import OpenAIEmbeddings collection_name = "test_index" embedding = OpenAIEmbeddings() vectorstore = ElasticsearchStore( es_url="http://localhost:9200", index_name="test_index", embedding=embedding ) namespace = f"elasticsearch/{collection_name}" record_manager = SQLRecordManager( namespace, db_url="sqlite:///record_manager_cache.sql" ) record_manager.create_schema() doc1 = Document(page_content="kitty", metadata={"source": "kitty.txt"}) doc2 = Document(page_content="doggy", metadata={"source": "doggy.txt"}) def _clear(): """Hacky helper method to clear content. See the `full` mode section to to understand why it works.""" index([], record_manager, vectorstore, cleanup="full", source_id_key="source") _clear() index( [doc1, doc1, doc1, doc1, doc1], record_manager, vectorstore, cleanup=None, source_id_key="source", ) _clear() index([doc1, doc2], record_manager, vectorstore, cleanup=None, source_id_key="source") index([doc1, doc2], record_manager, vectorstore, cleanup=None, source_id_key="source") _clear() index( [doc1, doc2], record_manager, vectorstore, cleanup="incremental", source_id_key="source", ) index( [doc1, doc2], record_manager, vectorstore, cleanup="incremental", source_id_key="source", ) index([], record_manager, vectorstore, cleanup="incremental", source_id_key="source") changed_doc_2 =
Document(page_content="puppy", metadata={"source": "doggy.txt"})
langchain_core.documents.Document
get_ipython().run_line_magic('pip', 'install --upgrade --quiet azureml-mlflow') get_ipython().run_line_magic('pip', 'install --upgrade --quiet pandas') get_ipython().run_line_magic('pip', 'install --upgrade --quiet textstat') get_ipython().run_line_magic('pip', 'install --upgrade --quiet spacy') get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain-openai') get_ipython().run_line_magic('pip', 'install --upgrade --quiet google-search-results') get_ipython().system('python -m spacy download en_core_web_sm') import os os.environ["MLFLOW_TRACKING_URI"] = "" os.environ["OPENAI_API_KEY"] = "" os.environ["SERPAPI_API_KEY"] = "" from langchain.callbacks import MlflowCallbackHandler from langchain_openai import OpenAI """Main function. This function is used to try the callback handler. Scenarios: 1. OpenAI LLM 2. Chain with multiple SubChains on multiple generations 3. Agent with Tools """ mlflow_callback =
MlflowCallbackHandler()
langchain.callbacks.MlflowCallbackHandler
get_ipython().run_line_magic('pip', 'install "pgvecto_rs[sdk]"') from typing import List from langchain.docstore.document import Document from langchain_community.document_loaders import TextLoader from langchain_community.embeddings.fake import FakeEmbeddings from langchain_community.vectorstores.pgvecto_rs import PGVecto_rs from langchain_text_splitters import CharacterTextSplitter loader =
TextLoader("../../modules/state_of_the_union.txt")
langchain_community.document_loaders.TextLoader
get_ipython().system(' pip install langchain unstructured[all-docs] pydantic lxml') path = "/Users/rlm/Desktop/Papers/LLaVA/" from typing import Any from pydantic import BaseModel from unstructured.partition.pdf import partition_pdf 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_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_openai import ChatOpenAI 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 = ChatOpenAI(temperature=0, model="gpt-4") summarize_chain = {"element": lambda x: x} | prompt | model | StrOutputParser() texts = [i.text for i in text_elements] 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()) logging_header = "clip_model_load: total allocated memory: 201.27 MB\n\n" cleaned_img_summary = [s.split(logging_header, 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.vectorstores import Chroma from langchain_core.documents import Document from langchain_openai import OpenAIEmbeddings vectorstore = Chroma(collection_name="summaries", embedding_function=OpenAIEmbeddings()) store = InMemoryStore() 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]})
langchain_core.documents.Document
import logging from langchain.retrievers import RePhraseQueryRetriever from langchain_community.document_loaders import WebBaseLoader from langchain_community.vectorstores import Chroma from langchain_openai import ChatOpenAI, OpenAIEmbeddings from langchain_text_splitters import RecursiveCharacterTextSplitter logging.basicConfig() logging.getLogger("langchain.retrievers.re_phraser").setLevel(logging.INFO) loader = WebBaseLoader("https://lilianweng.github.io/posts/2023-06-23-agent/") data = loader.load() text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=0) all_splits = text_splitter.split_documents(data) vectorstore = Chroma.from_documents(documents=all_splits, embedding=OpenAIEmbeddings()) llm = ChatOpenAI(temperature=0) retriever_from_llm = RePhraseQueryRetriever.from_llm( retriever=vectorstore.as_retriever(), llm=llm ) docs = retriever_from_llm.get_relevant_documents( "Hi I'm Lance. What are the approaches to Task Decomposition?" ) docs = retriever_from_llm.get_relevant_documents( "I live in San Francisco. What are the Types of Memory?" ) from langchain.chains import LLMChain from langchain.prompts import PromptTemplate QUERY_PROMPT = PromptTemplate( input_variables=["question"], template="""You are an assistant tasked with taking a natural languge query from a user and converting it into a query for a vectorstore. In the process, strip out all information that is not relevant for the retrieval task and return a new, simplified question for vectorstore retrieval. The new user query should be in pirate speech. Here is the user query: {question} """, ) llm = ChatOpenAI(temperature=0) llm_chain =
LLMChain(llm=llm, prompt=QUERY_PROMPT)
langchain.chains.LLMChain
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")
langchain_community.document_loaders.TextLoader
from langchain_mongodb.chat_message_histories import MongoDBChatMessageHistory chat_message_history = MongoDBChatMessageHistory( session_id="test_session", connection_string="mongodb://mongo_user:password123@mongo:27017", database_name="my_db", collection_name="chat_histories", ) chat_message_history.add_user_message("Hello") chat_message_history.add_ai_message("Hi") chat_message_history.messages from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain_core.runnables.history import RunnableWithMessageHistory from langchain_openai import ChatOpenAI import os assert os.environ[ "OPENAI_API_KEY" ], "Set the OPENAI_API_KEY environment variable with your OpenAI API key." prompt = ChatPromptTemplate.from_messages( [ ("system", "You are a helpful assistant."),
MessagesPlaceholder(variable_name="history")
langchain_core.prompts.MessagesPlaceholder
get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain-community') import os os.environ["YDC_API_KEY"] = "" os.environ["OPENAI_API_KEY"] = "" from langchain_community.tools.you import YouSearchTool from langchain_community.utilities.you import YouSearchAPIWrapper api_wrapper = YouSearchAPIWrapper(num_web_results=1) tool = YouSearchTool(api_wrapper=api_wrapper) tool response = tool.invoke("What is the weather in NY") print(len(response)) for item in response: print(item) get_ipython().system('pip install --upgrade --quiet langchain langchain-openai langchainhub langchain-community') from langchain import hub from langchain.agents import AgentExecutor, create_openai_functions_agent from langchain_openai import ChatOpenAI instructions = """You are an assistant.""" base_prompt =
hub.pull("langchain-ai/openai-functions-template")
langchain.hub.pull
get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') get_ipython().system('poetry run pip install replicate') from getpass import getpass REPLICATE_API_TOKEN = getpass() import os os.environ["REPLICATE_API_TOKEN"] = REPLICATE_API_TOKEN from langchain.chains import LLMChain from langchain.prompts import PromptTemplate from langchain_community.llms import Replicate llm = Replicate( model="a16z-infra/llama13b-v2-chat:df7690f1994d94e96ad9d568eac121aecf50684a0b0963b25a41cc40061269e5", model_kwargs={"temperature": 0.75, "max_length": 500, "top_p": 1}, ) prompt = """ User: Answer the following yes/no question by reasoning step by step. Can a dog drive a car? Assistant: """ llm(prompt) llm =
Replicate( model="replicate/dolly-v2-12b:ef0e1aefc61f8e096ebe4db6b2bacc297daf2ef6899f0f7e001ec445893500e5" )
langchain_community.llms.Replicate
get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain langchain-openai context-python') import os from langchain.callbacks import ContextCallbackHandler token = os.environ["CONTEXT_API_TOKEN"] context_callback = ContextCallbackHandler(token) import os from langchain.callbacks import ContextCallbackHandler from langchain.schema import ( HumanMessage, SystemMessage, ) from langchain_openai import ChatOpenAI token = os.environ["CONTEXT_API_TOKEN"] chat = ChatOpenAI( headers={"user_id": "123"}, temperature=0, callbacks=[ContextCallbackHandler(token)] ) messages = [ SystemMessage( content="You are a helpful assistant that translates English to French." ), HumanMessage(content="I love programming."), ] print(chat(messages)) import os from langchain.callbacks import ContextCallbackHandler from langchain.chains import LLMChain from langchain.prompts import PromptTemplate from langchain.prompts.chat import ( ChatPromptTemplate, HumanMessagePromptTemplate, ) from langchain_openai import ChatOpenAI token = os.environ["CONTEXT_API_TOKEN"] human_message_prompt = HumanMessagePromptTemplate( prompt=PromptTemplate( template="What is a good name for a company that makes {product}?", input_variables=["product"], ) ) chat_prompt_template =
ChatPromptTemplate.from_messages([human_message_prompt])
langchain.prompts.chat.ChatPromptTemplate.from_messages
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) texts = text_splitter.split_documents(docs) print(f"{len(texts)}") from langchain_openai import OpenAIEmbeddings embeddings = OpenAIEmbeddings() embeddings from langchain_community.vectorstores import DeepLake username = "<USERNAME_OR_ORG>" db = DeepLake.from_documents( texts, embeddings, dataset_path=f"hub://{username}/langchain-code", overwrite=True ) db db = DeepLake( dataset_path=f"hub://{username}/langchain-code", read_only=True, embedding=embeddings, ) retriever = db.as_retriever() retriever.search_kwargs["distance_metric"] = "cos" retriever.search_kwargs["fetch_k"] = 20 retriever.search_kwargs["maximal_marginal_relevance"] = True retriever.search_kwargs["k"] = 20 def filter(x): if "something" in x["text"].data()["value"]: return False metadata = x["metadata"].data()["value"] return "only_this" in metadata["source"] or "also_that" in metadata["source"] from langchain.chains import ConversationalRetrievalChain from langchain_openai import ChatOpenAI model = ChatOpenAI( model_name="gpt-3.5-turbo-0613" ) # 'ada' 'gpt-3.5-turbo-0613' 'gpt-4', qa =
ConversationalRetrievalChain.from_llm(model, retriever=retriever)
langchain.chains.ConversationalRetrievalChain.from_llm
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")
langchain_openai.ChatOpenAI
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) docs = text_splitter.split_documents(documents) embedding_function = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2") db =
Chroma.from_documents(docs, embedding_function)
langchain_community.vectorstores.Chroma.from_documents
import asyncio from langchain.callbacks import get_openai_callback from langchain_openai import OpenAI llm =
OpenAI(temperature=0)
langchain_openai.OpenAI
import getpass import os os.environ["TAVILY_API_KEY"] = getpass.getpass() from langchain_community.tools.tavily_search import TavilySearchResults tool = TavilySearchResults() tool.invoke({"query": "What happened in the latest burning man floods"}) import getpass import os os.environ["OPENAI_API_KEY"] = getpass.getpass() from langchain import hub from langchain.agents import AgentExecutor, create_openai_functions_agent from langchain_openai import ChatOpenAI instructions = """You are an assistant.""" base_prompt = hub.pull("langchain-ai/openai-functions-template") prompt = base_prompt.partial(instructions=instructions) llm = ChatOpenAI(temperature=0) tavily_tool = TavilySearchResults() tools = [tavily_tool] agent =
create_openai_functions_agent(llm, tools, prompt)
langchain.agents.create_openai_functions_agent
import os from langchain.retrievers import AzureCognitiveSearchRetriever os.environ["AZURE_COGNITIVE_SEARCH_SERVICE_NAME"] = "<YOUR_ACS_SERVICE_NAME>" os.environ["AZURE_COGNITIVE_SEARCH_INDEX_NAME"] = "<YOUR_ACS_INDEX_NAME>" os.environ["AZURE_COGNITIVE_SEARCH_API_KEY"] = "<YOUR_API_KEY>" retriever =
AzureCognitiveSearchRetriever(content_key="content", top_k=10)
langchain.retrievers.AzureCognitiveSearchRetriever
from langchain.chains import RetrievalQA from langchain_community.document_loaders import TextLoader from langchain_community.vectorstores import Chroma from langchain_openai import OpenAIEmbeddings from langchain_text_splitters import CharacterTextSplitter loader = TextLoader("../../state_of_the_union.txt", encoding="utf-8") documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) texts = text_splitter.split_documents(documents) for i, text in enumerate(texts): text.metadata["source"] = f"{i}-pl" embeddings =
OpenAIEmbeddings()
langchain_openai.OpenAIEmbeddings
get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain tiktoken langchain-openai') get_ipython().run_line_magic('pip', 'install --upgrade --quiet hippo-api==1.1.0.rc3') import os from langchain_community.document_loaders import TextLoader from langchain_community.vectorstores.hippo import Hippo from langchain_openai import ChatOpenAI, OpenAIEmbeddings from langchain_text_splitters import CharacterTextSplitter os.environ["OPENAI_API_KEY"] = "YOUR OPENAI KEY" loader = TextLoader("../../modules/state_of_the_union.txt") documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=500, chunk_overlap=0) docs = text_splitter.split_documents(documents) embeddings =
OpenAIEmbeddings()
langchain_openai.OpenAIEmbeddings
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")
langchain_openai.ChatOpenAI
get_ipython().run_line_magic('pip', 'install --upgrade --quiet weaviate-client') import getpass import os os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:") WEAVIATE_URL = getpass.getpass("WEAVIATE_URL:") os.environ["WEAVIATE_API_KEY"] = getpass.getpass("WEAVIATE_API_KEY:") WEAVIATE_API_KEY = os.environ["WEAVIATE_API_KEY"] from langchain_community.document_loaders import TextLoader from langchain_community.vectorstores import Weaviate 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") documents = loader.load() text_splitter =
CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
langchain_text_splitters.CharacterTextSplitter
get_ipython().run_line_magic('pip', 'install --upgrade --quiet fastembed') from langchain_community.embeddings.fastembed import FastEmbedEmbeddings embeddings =
FastEmbedEmbeddings()
langchain_community.embeddings.fastembed.FastEmbedEmbeddings
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")
langchain_experimental.rl_chain.BasedOn
get_ipython().run_line_magic('pip', 'install --upgrade --quiet pymysql') get_ipython().system('pip install sqlalchemy') get_ipython().system('pip install langchain') from langchain.chains import RetrievalQA from langchain_community.document_loaders import ( DirectoryLoader, UnstructuredMarkdownLoader, ) from langchain_community.vectorstores.apache_doris import ( ApacheDoris, ApacheDorisSettings, ) from langchain_openai import OpenAI, OpenAIEmbeddings from langchain_text_splitters import TokenTextSplitter update_vectordb = False loader = DirectoryLoader( "./docs", glob="**/*.md", loader_cls=UnstructuredMarkdownLoader ) documents = loader.load() text_splitter = TokenTextSplitter(chunk_size=400, chunk_overlap=50) split_docs = text_splitter.split_documents(documents) update_vectordb = True def gen_apache_doris(update_vectordb, embeddings, settings): if update_vectordb: docsearch = ApacheDoris.from_documents(split_docs, embeddings, config=settings) else: docsearch = ApacheDoris(embeddings, settings) return docsearch import os from getpass import getpass os.environ["OPENAI_API_KEY"] = getpass() update_vectordb = True embeddings =
OpenAIEmbeddings()
langchain_openai.OpenAIEmbeddings
import getpass import os os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:") from typing import List, Tuple from dotenv import load_dotenv load_dotenv() from langchain_community.document_loaders import TextLoader from langchain_community.embeddings import OpenAIEmbeddings from langchain_community.vectorstores import Lantern from langchain_core.documents import Document 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() CONNECTION_STRING = getpass.getpass("DB Connection String:") COLLECTION_NAME = "state_of_the_union_test" db = Lantern.from_documents( embedding=embeddings, documents=docs, collection_name=COLLECTION_NAME, connection_string=CONNECTION_STRING, pre_delete_collection=True, ) 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) docs_with_score = db.max_marginal_relevance_search_with_score(query) for doc, score in docs_with_score: print("-" * 80) print("Score: ", score) print(doc.page_content) print("-" * 80) store = Lantern( collection_name=COLLECTION_NAME, connection_string=CONNECTION_STRING, embedding_function=embeddings, ) store.add_documents([
Document(page_content="foo")
langchain_core.documents.Document
from langchain.chains import RetrievalQA from langchain_community.document_loaders import TextLoader from langchain_community.vectorstores import Chroma from langchain_openai import OpenAIEmbeddings from langchain_text_splitters import CharacterTextSplitter loader = TextLoader("../../state_of_the_union.txt", encoding="utf-8") documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) texts = text_splitter.split_documents(documents) for i, text in enumerate(texts): text.metadata["source"] = f"{i}-pl" embeddings = OpenAIEmbeddings() docsearch = Chroma.from_documents(texts, embeddings) from langchain.chains import create_qa_with_sources_chain from langchain.chains.combine_documents.stuff import StuffDocumentsChain from langchain.prompts import PromptTemplate from langchain_openai import ChatOpenAI llm =
ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613")
langchain_openai.ChatOpenAI
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(), model_kwargs={"temperature": 0.8, "max_new_tokens": 400}, ) response = llm.invoke("Write me a song about sparkling water:") response response = llm.invoke("Write me a song about sparkling water:", temperature=0.5) response 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/v1/completions", endpoint_api_type=AzureMLEndpointApiType.serverless, endpoint_api_key="my-api-key", content_formatter=LlamaContentFormatter(), model_kwargs={"temperature": 0.8, "max_new_tokens": 400}, ) response = llm.invoke("Write me a song about sparkling water:") response import json import os from typing import Dict from langchain_community.llms.azureml_endpoint import ( AzureMLOnlineEndpoint, ContentFormatterBase, ) class CustomFormatter(ContentFormatterBase): content_type = "application/json" accepts = "application/json" def format_request_payload(self, prompt: str, model_kwargs: Dict) -> bytes: input_str = json.dumps( { "inputs": [prompt], "parameters": model_kwargs, "options": {"use_cache": False, "wait_for_model": True}, } ) return str.encode(input_str) def format_response_payload(self, output: bytes) -> str: response_json = json.loads(output) return response_json[0]["summary_text"] content_formatter = CustomFormatter() llm = AzureMLOnlineEndpoint( endpoint_api_type="realtime", endpoint_api_key=os.getenv("BART_ENDPOINT_API_KEY"), endpoint_url=os.getenv("BART_ENDPOINT_URL"), model_kwargs={"temperature": 0.8, "max_new_tokens": 400}, content_formatter=content_formatter, ) large_text = """On January 7, 2020, Blockberry Creative announced that HaSeul would not participate in the promotion for Loona's next album because of mental health concerns. She was said to be diagnosed with "intermittent anxiety symptoms" and would be taking time to focus on her health.[39] On February 5, 2020, Loona released their second EP titled [#] (read as hash), along with the title track "So What".[40] Although HaSeul did not appear in the title track, her vocals are featured on three other songs on the album, including "365". Once peaked at number 1 on the daily Gaon Retail Album Chart,[41] the EP then debuted at number 2 on the weekly Gaon Album Chart. On March 12, 2020, Loona won their first music show trophy with "So What" on Mnet's M Countdown.[42] On October 19, 2020, Loona released their third EP titled [12:00] (read as midnight),[43] accompanied by its first single "Why Not?". HaSeul was again not involved in the album, out of her own decision to focus on the recovery of her health.[44] The EP then became their first album to enter the Billboard 200, debuting at number 112.[45] On November 18, Loona released the music video for "Star", another song on [12:00].[46] Peaking at number 40, "Star" is Loona's first entry on the Billboard Mainstream Top 40, making them the second K-pop girl group to enter the chart.[47] On June 1, 2021, Loona announced that they would be having a comeback on June 28, with their fourth EP, [&] (read as and). [48] The following day, on June 2, a teaser was posted to Loona's official social media accounts showing twelve sets of eyes, confirming the return of member HaSeul who had been on hiatus since early 2020.[49] On June 12, group members YeoJin, Kim Lip, Choerry, and Go Won released the song "Yum-Yum" as a collaboration with Cocomong.[50] On September 8, they released another collaboration song named "Yummy-Yummy".[51] On June 27, 2021, Loona announced at the end of their special clip that they are making their Japanese debut on September 15 under Universal Music Japan sublabel EMI Records.[52] On August 27, it was announced that Loona will release the double A-side single, "Hula Hoop / Star Seed" on September 15, with a physical CD release on October 20.[53] In December, Chuu filed an injunction to suspend her exclusive contract with Blockberry Creative.[54][55] """ summarized_text = llm.invoke(large_text) print(summarized_text) from langchain.chains import LLMChain from langchain.prompts import PromptTemplate from langchain_community.llms.azureml_endpoint import DollyContentFormatter formatter_template = "Write a {word_count} word essay about {topic}." prompt = PromptTemplate( input_variables=["word_count", "topic"], template=formatter_template ) content_formatter = DollyContentFormatter() llm = AzureMLOnlineEndpoint( endpoint_api_key=os.getenv("DOLLY_ENDPOINT_API_KEY"), endpoint_url=os.getenv("DOLLY_ENDPOINT_URL"), model_kwargs={"temperature": 0.8, "max_tokens": 300}, content_formatter=content_formatter, ) chain = LLMChain(llm=llm, prompt=prompt) print(chain.invoke({"word_count": 100, "topic": "how to make friends"})) from langchain_community.llms.loading import load_llm save_llm = AzureMLOnlineEndpoint( deployment_name="databricks-dolly-v2-12b-4", model_kwargs={ "temperature": 0.2, "max_tokens": 150, "top_p": 0.8, "frequency_penalty": 0.32, "presence_penalty": 72e-3, }, ) save_llm.save("azureml.json") loaded_llm =
load_llm("azureml.json")
langchain_community.llms.loading.load_llm
get_ipython().run_line_magic('pip', 'install --upgrade --quiet boto3') from langchain_community.document_loaders import S3DirectoryLoader loader =
S3DirectoryLoader("testing-hwc")
langchain_community.document_loaders.S3DirectoryLoader
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")
langchain_nvidia_ai_endpoints.ChatNVIDIA
from langchain.evaluation import load_evaluator evaluator = load_evaluator("criteria", criteria="conciseness") from langchain.evaluation import EvaluatorType evaluator = load_evaluator(EvaluatorType.CRITERIA, criteria="conciseness") eval_result = evaluator.evaluate_strings( prediction="What's 2+2? That's an elementary question. The answer you're looking for is that two and two is four.", input="What's 2+2?", ) print(eval_result) evaluator = load_evaluator("labeled_criteria", criteria="correctness") eval_result = evaluator.evaluate_strings( input="What is the capital of the US?", prediction="Topeka, KS", reference="The capital of the US is Topeka, KS, where it permanently moved from Washington D.C. on May 16, 2023", ) print(f'With ground truth: {eval_result["score"]}') from langchain.evaluation import Criteria list(Criteria) custom_criterion = { "numeric": "Does the output contain numeric or mathematical information?" } eval_chain = load_evaluator( EvaluatorType.CRITERIA, criteria=custom_criterion, ) query = "Tell me a joke" prediction = "I ate some square pie but I don't know the square of pi." eval_result = eval_chain.evaluate_strings(prediction=prediction, input=query) print(eval_result) custom_criteria = { "numeric": "Does the output contain numeric information?", "mathematical": "Does the output contain mathematical information?", "grammatical": "Is the output grammatically correct?", "logical": "Is the output logical?", } eval_chain = load_evaluator( EvaluatorType.CRITERIA, criteria=custom_criteria, ) eval_result = eval_chain.evaluate_strings(prediction=prediction, input=query) print("Multi-criteria evaluation") print(eval_result) from langchain.chains.constitutional_ai.principles import PRINCIPLES print(f"{len(PRINCIPLES)} available principles") list(PRINCIPLES.items())[:5] evaluator = load_evaluator(EvaluatorType.CRITERIA, criteria=PRINCIPLES["harmful1"]) eval_result = evaluator.evaluate_strings( prediction="I say that man is a lilly-livered nincompoop", input="What do you think of Will?", ) print(eval_result) get_ipython().run_line_magic('pip', 'install --upgrade --quiet anthropic') from langchain_community.chat_models import ChatAnthropic llm = ChatAnthropic(temperature=0) evaluator =
load_evaluator("criteria", llm=llm, criteria="conciseness")
langchain.evaluation.load_evaluator
from langchain_community.llms import Baseten mistral = Baseten(model="MODEL_ID", deployment="production") mistral("What is the Mistral wind?") from langchain.chains import LLMChain from langchain.memory import ConversationBufferWindowMemory from langchain.prompts import PromptTemplate template = """Assistant is a large language model trained by OpenAI. Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand. Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics. Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist. {history} Human: {human_input} Assistant:""" prompt = PromptTemplate(input_variables=["history", "human_input"], template=template) chatgpt_chain = LLMChain( llm=mistral, llm_kwargs={"max_length": 4096}, prompt=prompt, verbose=True, memory=
ConversationBufferWindowMemory(k=2)
langchain.memory.ConversationBufferWindowMemory
get_ipython().run_line_magic('pip', 'install --quiet pypdf chromadb tiktoken openai') get_ipython().run_line_magic('pip', 'uninstall -y langchain-fireworks') get_ipython().run_line_magic('pip', 'install --editable /mnt/disks/data/langchain/libs/partners/fireworks') import fireworks print(fireworks) import fireworks.client import requests from langchain_community.document_loaders import PyPDFLoader url = "https://storage.googleapis.com/deepmind-media/gemma/gemma-report.pdf" response = requests.get(url, stream=True) file_name = "temp_file.pdf" with open(file_name, "wb") as pdf: pdf.write(response.content) loader =
PyPDFLoader(file_name)
langchain_community.document_loaders.PyPDFLoader
get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain-community') import os os.environ["YDC_API_KEY"] = "" os.environ["OPENAI_API_KEY"] = "" from langchain_community.utilities.you import YouSearchAPIWrapper utility = YouSearchAPIWrapper(num_web_results=1) utility import json response = utility.raw_results(query="What is the weather in NY") hits = response["hits"] print(len(hits)) print(json.dumps(hits, indent=2)) response = utility.results(query="What is the weather in NY") print(len(response)) print(response) from langchain_community.retrievers.you import YouRetriever retriever = YouRetriever(num_web_results=1) retriever response = retriever.invoke("What is the weather in NY") print(len(response)) print(response) get_ipython().system('pip install --upgrade --quiet langchain-openai') from langchain_community.retrievers.you import YouRetriever from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_core.runnables import RunnablePassthrough from langchain_openai import ChatOpenAI runnable = RunnablePassthrough retriever =
YouRetriever(num_web_results=1)
langchain_community.retrievers.you.YouRetriever
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')", page_content_columns=["Team"], metadata_columns=["Payroll"], ) data = loader.load() print(data) loader =
DuckDBLoader( "SELECT Team, Payroll, Team As source FROM read_csv_auto('example.csv')
langchain_community.document_loaders.DuckDBLoader
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) original_documents = [ Document( page_content="Review of The Bee Movie\nBy Roger Ebert\n\nThis is the greatest movie ever made. 4 out of 5 stars." ), Document( page_content="Review of The Godfather\nBy Anonymous\n\nThis movie was super boring. 1 out of 5 stars.", metadata={"reliable": False}, ), ] enhanced_documents = document_transformer.transform_documents(original_documents) import json print( *[d.page_content + "\n\n" + json.dumps(d.metadata) for d in enhanced_documents], sep="\n\n---------------\n\n", ) from typing import Literal from pydantic import BaseModel, Field class Properties(BaseModel): movie_title: str critic: str tone: Literal["positive", "negative"] rating: int = Field(description="Rating out of 5 stars") document_transformer = create_metadata_tagger(Properties, llm) enhanced_documents = document_transformer.transform_documents(original_documents) print( *[d.page_content + "\n\n" + json.dumps(d.metadata) for d in enhanced_documents], sep="\n\n---------------\n\n", ) from langchain_core.prompts import ChatPromptTemplate prompt =
ChatPromptTemplate.from_template( """Extract relevant information from the following text. Anonymous critics are actually Roger Ebert. {input} """ )
langchain_core.prompts.ChatPromptTemplate.from_template
from typing import Callable, List import tenacity from langchain.output_parsers import RegexParser from langchain.prompts import PromptTemplate from langchain.schema import ( HumanMessage, SystemMessage, ) from langchain_openai import ChatOpenAI class DialogueAgent: def __init__( self, name: str, system_message: SystemMessage, model: ChatOpenAI, ) -> None: self.name = name self.system_message = system_message self.model = model self.prefix = f"{self.name}: " self.reset() def reset(self): self.message_history = ["Here is the conversation so far."] def send(self) -> str: """ Applies the chatmodel to the message history and returns the message string """ message = self.model( [ self.system_message, HumanMessage(content="\n".join(self.message_history + [self.prefix])), ] ) return message.content def receive(self, name: str, message: str) -> None: """ Concatenates {message} spoken by {name} into message history """ self.message_history.append(f"{name}: {message}") class DialogueSimulator: def __init__( self, agents: List[DialogueAgent], selection_function: Callable[[int, List[DialogueAgent]], int], ) -> None: self.agents = agents self._step = 0 self.select_next_speaker = selection_function def reset(self): for agent in self.agents: agent.reset() def inject(self, name: str, message: str): """ Initiates the conversation with a {message} from {name} """ for agent in self.agents: agent.receive(name, message) self._step += 1 def step(self) -> tuple[str, str]: speaker_idx = self.select_next_speaker(self._step, self.agents) speaker = self.agents[speaker_idx] message = speaker.send() for receiver in self.agents: receiver.receive(speaker.name, message) self._step += 1 return speaker.name, message class BiddingDialogueAgent(DialogueAgent): def __init__( self, name, system_message: SystemMessage, bidding_template: PromptTemplate, model: ChatOpenAI, ) -> None: super().__init__(name, system_message, model) self.bidding_template = bidding_template def bid(self) -> str: """ Asks the chat model to output a bid to speak """ prompt = PromptTemplate( input_variables=["message_history", "recent_message"], template=self.bidding_template, ).format( message_history="\n".join(self.message_history), recent_message=self.message_history[-1], ) bid_string = self.model([SystemMessage(content=prompt)]).content return bid_string character_names = ["Donald Trump", "Kanye West", "Elizabeth Warren"] topic = "transcontinental high speed rail" word_limit = 50 game_description = f"""Here is the topic for the presidential debate: {topic}. The presidential candidates are: {', '.join(character_names)}.""" player_descriptor_system_message = SystemMessage( content="You can add detail to the description of each presidential candidate." ) def generate_character_description(character_name): character_specifier_prompt = [ player_descriptor_system_message, HumanMessage( content=f"""{game_description} Please reply with a creative description of the presidential candidate, {character_name}, in {word_limit} words or less, that emphasizes their personalities. Speak directly to {character_name}. Do not add anything else.""" ), ] character_description = ChatOpenAI(temperature=1.0)( character_specifier_prompt ).content return character_description def generate_character_header(character_name, character_description): return f"""{game_description} Your name is {character_name}. You are a presidential candidate. Your description is as follows: {character_description} You are debating the topic: {topic}. Your goal is to be as creative as possible and make the voters think you are the best candidate. """ def generate_character_system_message(character_name, character_header): return SystemMessage( content=( f"""{character_header} You will speak in the style of {character_name}, and exaggerate their personality. You will come up with creative ideas related to {topic}. Do not say the same things over and over again. Speak in the first person from the perspective of {character_name} For describing your own body movements, wrap your description in '*'. Do not change roles! Do not speak from the perspective of anyone else. Speak only from the perspective of {character_name}. Stop speaking the moment you finish speaking from your perspective. Never forget to keep your response to {word_limit} words! Do not add anything else. """ ) ) character_descriptions = [ generate_character_description(character_name) for character_name in character_names ] character_headers = [ generate_character_header(character_name, character_description) for character_name, character_description in zip( character_names, character_descriptions ) ] character_system_messages = [ generate_character_system_message(character_name, character_headers) for character_name, character_headers in zip(character_names, character_headers) ] for ( character_name, character_description, character_header, character_system_message, ) in zip( character_names, character_descriptions, character_headers, character_system_messages, ): print(f"\n\n{character_name} Description:") print(f"\n{character_description}") print(f"\n{character_header}") print(f"\n{character_system_message.content}") class BidOutputParser(RegexParser): def get_format_instructions(self) -> str: return "Your response should be an integer delimited by angled brackets, like this: <int>." bid_parser = BidOutputParser( regex=r"<(\d+)>", output_keys=["bid"], default_output_key="bid" ) def generate_character_bidding_template(character_header): bidding_template = f"""{character_header} ``` {{message_history}} ``` On the scale of 1 to 10, where 1 is not contradictory and 10 is extremely contradictory, rate how contradictory the following message is to your ideas. ``` {{recent_message}} ``` {bid_parser.get_format_instructions()} Do nothing else. """ return bidding_template character_bidding_templates = [ generate_character_bidding_template(character_header) for character_header in character_headers ] for character_name, bidding_template in zip( character_names, character_bidding_templates ): print(f"{character_name} Bidding Template:") print(bidding_template) topic_specifier_prompt = [ SystemMessage(content="You can make a task more specific."), HumanMessage( content=f"""{game_description} You are the debate moderator. Please make the debate topic more specific. Frame the debate topic as a problem to be solved. Be creative and imaginative. Please reply with the specified topic in {word_limit} words or less. Speak directly to the presidential candidates: {*character_names,}. Do not add anything else.""" ), ] specified_topic =
ChatOpenAI(temperature=1.0)
langchain_openai.ChatOpenAI
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)
langchain_community.vectorstores.FAISS.load_local
from langchain.agents import AgentType, initialize_agent, load_tools from langchain_openai import ChatOpenAI, OpenAI llm = ChatOpenAI(temperature=0.0) math_llm = OpenAI(temperature=0.0) tools = load_tools( ["human", "llm-math"], llm=math_llm, ) agent_chain = initialize_agent( tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, ) agent_chain.run("What's my friend Eric's surname?") def get_input() -> str: print("Insert your text. Enter 'q' or press Ctrl-D (or Ctrl-Z on Windows) to end.") contents = [] while True: try: line = input() except EOFError: break if line == "q": break contents.append(line) return "\n".join(contents) tools = load_tools(["human", "ddg-search"], llm=math_llm, input_func=get_input) from langchain.tools import HumanInputRun tool =
HumanInputRun(input_func=get_input)
langchain.tools.HumanInputRun
get_ipython().run_line_magic('pip', 'install --upgrade --quiet clearml') get_ipython().run_line_magic('pip', 'install --upgrade --quiet pandas') get_ipython().run_line_magic('pip', 'install --upgrade --quiet textstat') get_ipython().run_line_magic('pip', 'install --upgrade --quiet spacy') get_ipython().system('python -m spacy download en_core_web_sm') import os os.environ["CLEARML_API_ACCESS_KEY"] = "" os.environ["CLEARML_API_SECRET_KEY"] = "" os.environ["OPENAI_API_KEY"] = "" os.environ["SERPAPI_API_KEY"] = "" from langchain.callbacks import ClearMLCallbackHandler from langchain.callbacks import StdOutCallbackHandler from langchain_openai import OpenAI clearml_callback = ClearMLCallbackHandler( task_type="inference", project_name="langchain_callback_demo", task_name="llm", tags=["test"], visualize=True, complexity_metrics=True, stream_logs=True, ) callbacks = [
StdOutCallbackHandler()
langchain.callbacks.StdOutCallbackHandler
get_ipython().run_line_magic('pip', 'install -qU langchain langchain-openai langchain-anthropic langchain-community wikipedia') import getpass import os os.environ["OPENAI_API_KEY"] = getpass.getpass() os.environ["ANTHROPIC_API_KEY"] = getpass.getpass() from langchain_community.retrievers import WikipediaRetriever from langchain_core.prompts import ChatPromptTemplate from langchain_openai import ChatOpenAI llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0) wiki = WikipediaRetriever(top_k_results=6, doc_content_chars_max=2000) prompt = ChatPromptTemplate.from_messages( [ ( "system", "You're a helpful AI assistant. Given a user question and some Wikipedia article snippets, answer the user question. If none of the articles answer the question, just say you don't know.\n\nHere are the Wikipedia articles:{context}", ), ("human", "{question}"), ] ) prompt.pretty_print() from operator import itemgetter from typing import List from langchain_core.documents import Document from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables import ( RunnableLambda, RunnableParallel, RunnablePassthrough, ) def format_docs(docs: List[Document]) -> str: """Convert Documents to a single string.:""" formatted = [ f"Article Title: {doc.metadata['title']}\nArticle Snippet: {doc.page_content}" for doc in docs ] return "\n\n" + "\n\n".join(formatted) format = itemgetter("docs") | RunnableLambda(format_docs) answer = prompt | llm |
StrOutputParser()
langchain_core.output_parsers.StrOutputParser
get_ipython().run_line_magic('pip', 'install --upgrade --quiet predibase') import os os.environ["PREDIBASE_API_TOKEN"] = "{PREDIBASE_API_TOKEN}" from langchain_community.llms import Predibase model = Predibase( model="vicuna-13b", predibase_api_key=os.environ.get("PREDIBASE_API_TOKEN") ) response = model("Can you recommend me a nice dry wine?") print(response) llm = Predibase( model="vicuna-13b", predibase_api_key=os.environ.get("PREDIBASE_API_TOKEN") ) from langchain.chains import LLMChain from langchain.prompts import PromptTemplate 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)
langchain.chains.LLMChain
get_ipython().run_line_magic('pip', 'install --upgrade --quiet python-gitlab') import os from langchain.agents import AgentType, initialize_agent from langchain_community.agent_toolkits.gitlab.toolkit import GitLabToolkit from langchain_community.utilities.gitlab import GitLabAPIWrapper from langchain_openai import OpenAI os.environ["GITLAB_URL"] = "https://gitlab.example.org" os.environ["GITLAB_PERSONAL_ACCESS_TOKEN"] = "" os.environ["GITLAB_REPOSITORY"] = "username/repo-name" os.environ["GITLAB_BRANCH"] = "bot-branch-name" os.environ["GITLAB_BASE_BRANCH"] = "main" os.environ["OPENAI_API_KEY"] = "" llm = OpenAI(temperature=0) gitlab = GitLabAPIWrapper() toolkit =
GitLabToolkit.from_gitlab_api_wrapper(gitlab)
langchain_community.agent_toolkits.gitlab.toolkit.GitLabToolkit.from_gitlab_api_wrapper
from typing import List from langchain.prompts import PromptTemplate from langchain_core.output_parsers import JsonOutputParser from langchain_core.pydantic_v1 import BaseModel, Field from langchain_openai import ChatOpenAI model = ChatOpenAI(temperature=0) class Joke(BaseModel): setup: str = Field(description="question to set up a joke") punchline: str =
Field(description="answer to resolve the joke")
langchain_core.pydantic_v1.Field
import os import yaml get_ipython().system('wget https://raw.githubusercontent.com/openai/openai-openapi/master/openapi.yaml -O openai_openapi.yaml') get_ipython().system('wget https://www.klarna.com/us/shopping/public/openai/v0/api-docs -O klarna_openapi.yaml') get_ipython().system('wget https://raw.githubusercontent.com/APIs-guru/openapi-directory/main/APIs/spotify.com/1.0.0/openapi.yaml -O spotify_openapi.yaml') from langchain_community.agent_toolkits.openapi.spec import reduce_openapi_spec with open("openai_openapi.yaml") as f: raw_openai_api_spec = yaml.load(f, Loader=yaml.Loader) openai_api_spec = reduce_openapi_spec(raw_openai_api_spec) with open("klarna_openapi.yaml") as f: raw_klarna_api_spec = yaml.load(f, Loader=yaml.Loader) klarna_api_spec = reduce_openapi_spec(raw_klarna_api_spec) with open("spotify_openapi.yaml") as f: raw_spotify_api_spec = yaml.load(f, Loader=yaml.Loader) spotify_api_spec = reduce_openapi_spec(raw_spotify_api_spec) import spotipy.util as util from langchain.requests import RequestsWrapper def construct_spotify_auth_headers(raw_spec: dict): scopes = list( raw_spec["components"]["securitySchemes"]["oauth_2_0"]["flows"][ "authorizationCode" ]["scopes"].keys() ) access_token = util.prompt_for_user_token(scope=",".join(scopes)) return {"Authorization": f"Bearer {access_token}"} headers = construct_spotify_auth_headers(raw_spotify_api_spec) requests_wrapper = RequestsWrapper(headers=headers) endpoints = [ (route, operation) for route, operations in raw_spotify_api_spec["paths"].items() for operation in operations if operation in ["get", "post"] ] len(endpoints) import tiktoken enc = tiktoken.encoding_for_model("gpt-4") def count_tokens(s): return len(enc.encode(s)) count_tokens(yaml.dump(raw_spotify_api_spec)) from langchain_community.agent_toolkits.openapi import planner from langchain_openai import OpenAI llm = OpenAI(model_name="gpt-4", temperature=0.0) spotify_agent =
planner.create_openapi_agent(spotify_api_spec, requests_wrapper, llm)
langchain_community.agent_toolkits.openapi.planner.create_openapi_agent
URL = "" # Your Fiddler instance URL, Make sure to include the full URL (including https://). For example: https://demo.fiddler.ai ORG_NAME = "" AUTH_TOKEN = "" # Your Fiddler instance auth token PROJECT_NAME = "" MODEL_NAME = "" # Model name in Fiddler from langchain_community.callbacks.fiddler_callback import FiddlerCallbackHandler fiddler_handler = FiddlerCallbackHandler( url=URL, org=ORG_NAME, project=PROJECT_NAME, model=MODEL_NAME, api_key=AUTH_TOKEN, ) from langchain_core.output_parsers import StrOutputParser from langchain_openai import OpenAI llm = OpenAI(temperature=0, streaming=True, callbacks=[fiddler_handler]) output_parser = StrOutputParser() chain = llm | output_parser chain.invoke("How far is moon from earth?") chain.invoke("What is the temperature on Mars?") chain.invoke("How much is 2 + 200000?") chain.invoke("Which movie won the oscars this year?") chain.invoke("Can you write me a poem about insomnia?") chain.invoke("How are you doing today?") chain.invoke("What is the meaning of life?") 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, ) final_prompt = ChatPromptTemplate.from_messages( [ ("system", "You are a wondrous wizard of math."), few_shot_prompt, ("human", "{input}"), ] ) llm =
OpenAI(temperature=0, streaming=True, callbacks=[fiddler_handler])
langchain_openai.OpenAI
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]})
langchain_core.documents.Document
from langchain.chains import LLMChain from langchain.prompts import PromptTemplate from langchain_community.llms import GradientLLM import os 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:") get_ipython().run_line_magic('pip', 'install --upgrade --quiet gradientai') import gradientai client = gradientai.Gradient() models = client.list_models(only_base=True) for model in models: print(model.id) new_model = models[-1].create_model_adapter(name="my_model_adapter") new_model.id, new_model.name llm = GradientLLM( model="674119b5-f19e-4856-add2-767ae7f7d7ef_model_adapter", model_kwargs=dict(max_generated_token_count=128), ) template = """Question: {question} Answer: """ prompt = PromptTemplate.from_template(template) llm_chain =
LLMChain(prompt=prompt, llm=llm)
langchain.chains.LLMChain
get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain langchain-openai deepeval') get_ipython().system('deepeval login') from deepeval.metrics.answer_relevancy import AnswerRelevancy answer_relevancy_metric = AnswerRelevancy(minimum_score=0.5) from langchain.callbacks.confident_callback import DeepEvalCallbackHandler deepeval_callback = DeepEvalCallbackHandler( implementation_name="langchainQuickstart", metrics=[answer_relevancy_metric] ) from langchain_openai import OpenAI llm = OpenAI( temperature=0, callbacks=[deepeval_callback], verbose=True, openai_api_key="<YOUR_API_KEY>", ) output = llm.generate( [ "What is the best evaluation tool out there? (no bias at all)", ] ) answer_relevancy_metric.is_successful() import requests from langchain.chains import RetrievalQA from langchain_community.document_loaders import TextLoader from langchain_community.vectorstores import Chroma from langchain_openai import OpenAI, OpenAIEmbeddings from langchain_text_splitters import CharacterTextSplitter text_file_url = "https://raw.githubusercontent.com/hwchase17/chat-your-data/master/state_of_the_union.txt" openai_api_key = "sk-XXX" with open("state_of_the_union.txt", "w") as f: response = requests.get(text_file_url) f.write(response.text) loader =
TextLoader("state_of_the_union.txt")
langchain_community.document_loaders.TextLoader
from langchain.chains import GraphCypherQAChain from langchain_community.graphs import Neo4jGraph from langchain_openai import ChatOpenAI graph = Neo4jGraph( url="bolt://localhost:7687", username="neo4j", password="pleaseletmein" ) graph.query( """ MERGE (m:Movie {name:"Top Gun"}) WITH m UNWIND ["Tom Cruise", "Val Kilmer", "Anthony Edwards", "Meg Ryan"] AS actor MERGE (a:Actor {name:actor}) MERGE (a)-[:ACTED_IN]->(m) """ ) graph.refresh_schema() print(graph.schema) chain = GraphCypherQAChain.from_llm( ChatOpenAI(temperature=0), graph=graph, verbose=True ) chain.run("Who played in Top Gun?") chain = GraphCypherQAChain.from_llm( ChatOpenAI(temperature=0), graph=graph, verbose=True, top_k=2 ) chain.run("Who played in Top Gun?") chain = GraphCypherQAChain.from_llm( ChatOpenAI(temperature=0), graph=graph, verbose=True, return_intermediate_steps=True ) result = chain("Who played in Top Gun?") print(f"Intermediate steps: {result['intermediate_steps']}") print(f"Final answer: {result['result']}") chain = GraphCypherQAChain.from_llm( ChatOpenAI(temperature=0), graph=graph, verbose=True, return_direct=True ) chain.run("Who played in Top Gun?") from langchain.prompts.prompt import PromptTemplate CYPHER_GENERATION_TEMPLATE = """Task:Generate Cypher statement to query a graph database. Instructions: Use only the provided relationship types and properties in the schema. Do not use any other relationship types or properties that are not provided. Schema: {schema} Note: Do not include any explanations or apologies in your responses. Do not respond to any questions that might ask anything else than for you to construct a Cypher statement. Do not include any text except the generated Cypher statement. Examples: Here are a few examples of generated Cypher statements for particular questions: MATCH (m:Movie {{title:"Top Gun"}})<-[:ACTED_IN]-() RETURN count(*) AS numberOfActors The question is: {question}""" CYPHER_GENERATION_PROMPT = PromptTemplate( input_variables=["schema", "question"], template=CYPHER_GENERATION_TEMPLATE ) chain = GraphCypherQAChain.from_llm(
ChatOpenAI(temperature=0)
langchain_openai.ChatOpenAI
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")
langchain_openai.OpenAI
get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain langchain-openai') import os os.environ["OUTLINE_API_KEY"] = "xxx" os.environ["OUTLINE_INSTANCE_URL"] = "https://app.getoutline.com" from langchain.retrievers import OutlineRetriever retriever =
OutlineRetriever()
langchain.retrievers.OutlineRetriever
from langchain_experimental.llm_symbolic_math.base import LLMSymbolicMathChain from langchain_openai import OpenAI llm =
OpenAI(temperature=0)
langchain_openai.OpenAI
get_ipython().run_line_magic('pip', 'install --upgrade --quiet azureml-mlflow') get_ipython().run_line_magic('pip', 'install --upgrade --quiet pandas') get_ipython().run_line_magic('pip', 'install --upgrade --quiet textstat') get_ipython().run_line_magic('pip', 'install --upgrade --quiet spacy') get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain-openai') get_ipython().run_line_magic('pip', 'install --upgrade --quiet google-search-results') get_ipython().system('python -m spacy download en_core_web_sm') import os os.environ["MLFLOW_TRACKING_URI"] = "" os.environ["OPENAI_API_KEY"] = "" os.environ["SERPAPI_API_KEY"] = "" from langchain.callbacks import MlflowCallbackHandler from langchain_openai import OpenAI """Main function. This function is used to try the callback handler. Scenarios: 1. OpenAI LLM 2. Chain with multiple SubChains on multiple generations 3. Agent with Tools """ mlflow_callback = MlflowCallbackHandler() llm = OpenAI( model_name="gpt-3.5-turbo", temperature=0, callbacks=[mlflow_callback], verbose=True ) llm_result = llm.generate(["Tell me a joke"]) mlflow_callback.flush_tracker(llm) from langchain.chains import LLMChain from langchain.prompts import PromptTemplate template = """You are a playwright. Given the title of play, it is your job to write a synopsis for that title. Title: {title} Playwright: This is a synopsis for the above play:""" prompt_template = PromptTemplate(input_variables=["title"], template=template) synopsis_chain =
LLMChain(llm=llm, prompt=prompt_template, callbacks=[mlflow_callback])
langchain.chains.LLMChain
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), 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!", ) chain.run( meal=
rl_chain.ToSelectFrom(meals)
langchain_experimental.rl_chain.ToSelectFrom
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")
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) query = "What did the president say about Ketanji Brown Jackson" results = db.similarity_search(query) print(results[0].page_content) query = "What did the president say about Ketanji Brown Jackson" results = db.similarity_search(query) result = results[0] result.page_content = "UPDATED: " + result.page_content db.add_texts([result.page_content], [result.metadata], result.metadata["id"]) results = db.similarity_search(query) print(results[0].page_content) result = db.similarity_search(query) db.delete(["32"]) result = db.similarity_search(query) results = db.similarity_search_with_score(query) result = results[0] db =
VespaStore.from_documents(docs, embedding_function, app=vespa_app, **vespa_config)
langchain_community.vectorstores.VespaStore.from_documents
get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain-text-splitters tiktoken') with open("../../state_of_the_union.txt") as f: state_of_the_union = f.read() from langchain_text_splitters import CharacterTextSplitter text_splitter = CharacterTextSplitter.from_tiktoken_encoder( chunk_size=100, chunk_overlap=0 ) texts = text_splitter.split_text(state_of_the_union) print(texts[0]) from langchain_text_splitters import TokenTextSplitter text_splitter = TokenTextSplitter(chunk_size=10, chunk_overlap=0) texts = text_splitter.split_text(state_of_the_union) print(texts[0]) get_ipython().run_line_magic('pip', 'install --upgrade --quiet spacy') with open("../../state_of_the_union.txt") as f: state_of_the_union = f.read() from langchain_text_splitters import SpacyTextSplitter text_splitter = SpacyTextSplitter(chunk_size=1000) texts = text_splitter.split_text(state_of_the_union) print(texts[0]) from langchain_text_splitters import SentenceTransformersTokenTextSplitter splitter =
SentenceTransformersTokenTextSplitter(chunk_overlap=0)
langchain_text_splitters.SentenceTransformersTokenTextSplitter
get_ipython().system("python3 -m pip install --upgrade langchain 'deeplake[enterprise]' openai tiktoken") import getpass import os from langchain_community.vectorstores import DeepLake from langchain_openai import OpenAIEmbeddings os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:") activeloop_token = getpass.getpass("Activeloop Token:") os.environ["ACTIVELOOP_TOKEN"] = activeloop_token embeddings = OpenAIEmbeddings(disallowed_special=()) get_ipython().system('git clone https://github.com/twitter/the-algorithm # replace any repository of your choice') import os from langchain_community.document_loaders import TextLoader root_dir = "./the-algorithm" docs = [] for dirpath, dirnames, filenames in os.walk(root_dir): for file in filenames: try: loader = TextLoader(os.path.join(dirpath, file), encoding="utf-8") docs.extend(loader.load_and_split()) except Exception: pass from langchain_text_splitters import CharacterTextSplitter text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) texts = text_splitter.split_documents(docs) username = "<USERNAME_OR_ORG>" # replace with your username from app.activeloop.ai db = DeepLake( dataset_path=f"hub://{username}/twitter-algorithm", embedding=embeddings, ) db.add_documents(texts) db = DeepLake( dataset_path=f"hub://{username}/twitter-algorithm", read_only=True, embedding=embeddings, ) retriever = db.as_retriever() retriever.search_kwargs["distance_metric"] = "cos" retriever.search_kwargs["fetch_k"] = 100 retriever.search_kwargs["maximal_marginal_relevance"] = True retriever.search_kwargs["k"] = 10 def filter(x): if "com.google" in x["text"].data()["value"]: return False metadata = x["metadata"].data()["value"] return "scala" in metadata["source"] or "py" in metadata["source"] from langchain.chains import ConversationalRetrievalChain from langchain_openai import ChatOpenAI model = ChatOpenAI(model_name="gpt-3.5-turbo-0613") # switch to 'gpt-4' qa =
ConversationalRetrievalChain.from_llm(model, retriever=retriever)
langchain.chains.ConversationalRetrievalChain.from_llm
from transformers import load_tool hf_tools = [ load_tool(tool_name) for tool_name in [ "document-question-answering", "image-captioning", "image-question-answering", "image-segmentation", "speech-to-text", "summarization", "text-classification", "text-question-answering", "translation", "huggingface-tools/text-to-image", "huggingface-tools/text-to-video", "text-to-speech", "huggingface-tools/text-download", "huggingface-tools/image-transformation", ] ] from langchain_experimental.autonomous_agents import HuggingGPT from langchain_openai import OpenAI llm = OpenAI(model_name="gpt-3.5-turbo") agent =
HuggingGPT(llm, hf_tools)
langchain_experimental.autonomous_agents.HuggingGPT
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").load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) docs = text_splitter.split_documents(documents) embeddings = OpenAIEmbeddings() db =
DocArrayInMemorySearch.from_documents(docs, embeddings)
langchain_community.vectorstores.DocArrayInMemorySearch.from_documents
get_ipython().run_line_magic('pip', 'install --upgrade --quiet singlestoredb') 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 SingleStoreDB from langchain_openai import OpenAIEmbeddings from langchain_text_splitters import CharacterTextSplitter loader =
TextLoader("../../modules/state_of_the_union.txt")
langchain_community.document_loaders.TextLoader
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain_openai.chat_models import ChatOpenAI model = ChatOpenAI() prompt = ChatPromptTemplate.from_messages( [ ( "system", "You're an assistant who's good at {ability}. Respond in 20 words or fewer", ), MessagesPlaceholder(variable_name="history"), ("human", "{input}"), ] ) runnable = prompt | model from langchain_community.chat_message_histories import ChatMessageHistory from langchain_core.chat_history import BaseChatMessageHistory from langchain_core.runnables.history import RunnableWithMessageHistory store = {} def get_session_history(session_id: str) -> BaseChatMessageHistory: if session_id not in store: store[session_id] = ChatMessageHistory() return store[session_id] with_message_history = RunnableWithMessageHistory( runnable, get_session_history, input_messages_key="input", history_messages_key="history", ) with_message_history.invoke( {"ability": "math", "input": "What does cosine mean?"}, config={"configurable": {"session_id": "abc123"}}, ) with_message_history.invoke( {"ability": "math", "input": "What?"}, config={"configurable": {"session_id": "abc123"}}, ) with_message_history.invoke( {"ability": "math", "input": "What?"}, config={"configurable": {"session_id": "def234"}}, ) from langchain_core.runnables import ConfigurableFieldSpec store = {} def get_session_history(user_id: str, conversation_id: str) -> BaseChatMessageHistory: if (user_id, conversation_id) not in store: store[(user_id, conversation_id)] =
ChatMessageHistory()
langchain_community.chat_message_histories.ChatMessageHistory
get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain-community') import os os.environ["YDC_API_KEY"] = "" os.environ["OPENAI_API_KEY"] = "" from langchain_community.utilities.you import YouSearchAPIWrapper utility = YouSearchAPIWrapper(num_web_results=1) utility import json response = utility.raw_results(query="What is the weather in NY") hits = response["hits"] print(len(hits)) print(json.dumps(hits, indent=2)) response = utility.results(query="What is the weather in NY") print(len(response)) print(response) from langchain_community.retrievers.you import YouRetriever retriever = YouRetriever(num_web_results=1) retriever response = retriever.invoke("What is the weather in NY") print(len(response)) print(response) get_ipython().system('pip install --upgrade --quiet langchain-openai') from langchain_community.retrievers.you import YouRetriever from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_core.runnables import RunnablePassthrough from langchain_openai import ChatOpenAI runnable = RunnablePassthrough retriever = YouRetriever(num_web_results=1) model = ChatOpenAI(model="gpt-3.5-turbo-16k") output_parser = StrOutputParser() prompt =
ChatPromptTemplate.from_template( """Answer the question based only on the context provided. Context: {context} Question: {question}""" )
langchain_core.prompts.ChatPromptTemplate.from_template
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 OpenAI api_wrapper = WikipediaAPIWrapper(top_k_results=1, doc_content_chars_max=100) tool = WikipediaQueryRun(api_wrapper=api_wrapper) tools = [tool] prompt =
hub.pull("hwchase17/react")
langchain.hub.pull
get_ipython().system('pip install -U oci') from langchain_community.llms import OCIGenAI llm = OCIGenAI( model_id="MY_MODEL", service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com", compartment_id="MY_OCID", ) response = llm.invoke("Tell me one fact about earth", temperature=0.7) print(response) from langchain.chains import LLMChain from langchain_core.prompts import PromptTemplate llm = OCIGenAI( model_id="MY_MODEL", service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com", compartment_id="MY_OCID", auth_type="SECURITY_TOKEN", auth_profile="MY_PROFILE", # replace with your profile name model_kwargs={"temperature": 0.7, "top_p": 0.75, "max_tokens": 200}, ) prompt = PromptTemplate(input_variables=["query"], template="{query}") llm_chain = LLMChain(llm=llm, prompt=prompt) response = llm_chain.invoke("what is the capital of france?") print(response) from langchain.schema.output_parser import StrOutputParser from langchain.schema.runnable import RunnablePassthrough from langchain_community.embeddings import OCIGenAIEmbeddings from langchain_community.vectorstores import FAISS embeddings = OCIGenAIEmbeddings( model_id="MY_EMBEDDING_MODEL", service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com", compartment_id="MY_OCID", ) vectorstore = FAISS.from_texts( [ "Larry Ellison co-founded Oracle Corporation in 1977 with Bob Miner and Ed Oates.", "Oracle Corporation is an American multinational computer technology company headquartered in Austin, Texas, United States.", ], embedding=embeddings, ) retriever = vectorstore.as_retriever() template = """Answer the question based only on the following context: {context} Question: {question} """ prompt = PromptTemplate.from_template(template) llm = OCIGenAI( model_id="MY_MODEL", service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com", compartment_id="MY_OCID", ) chain = ( {"context": retriever, "question": RunnablePassthrough()} | prompt | llm |
StrOutputParser()
langchain.schema.output_parser.StrOutputParser
from langchain_community.llms import Ollama llm = Ollama(model="llama2") llm("The first man on the moon was ...") from langchain.callbacks.manager import CallbackManager from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler llm = Ollama( model="llama2", callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]) ) llm("The first man on the moon was ...") from langchain_community.llms import Ollama llm = Ollama(model="llama2:13b") llm("The first man on the moon was ... think step by step") get_ipython().run_line_magic('env', 'CMAKE_ARGS="-DLLAMA_METAL=on"') get_ipython().run_line_magic('env', 'FORCE_CMAKE=1') get_ipython().run_line_magic('pip', 'install --upgrade --quiet llama-cpp-python --no-cache-dirclear') from langchain.callbacks.manager import CallbackManager from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler from langchain_community.llms import LlamaCpp llm = LlamaCpp( model_path="/Users/rlm/Desktop/Code/llama.cpp/models/openorca-platypus2-13b.gguf.q4_0.bin", n_gpu_layers=1, n_batch=512, n_ctx=2048, f16_kv=True, callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]), verbose=True, ) llm("The first man on the moon was ... Let's think step by step") get_ipython().run_line_magic('pip', 'install gpt4all') from langchain_community.llms import GPT4All llm = GPT4All( model="/Users/rlm/Desktop/Code/gpt4all/models/nous-hermes-13b.ggmlv3.q4_0.bin" ) llm("The first man on the moon was ... Let's think step by step") from langchain_community.llms.llamafile import Llamafile llm = Llamafile() llm.invoke("The first man on the moon was ... Let's think step by step.") llm = LlamaCpp( model_path="/Users/rlm/Desktop/Code/llama.cpp/models/openorca-platypus2-13b.gguf.q4_0.bin", n_gpu_layers=1, n_batch=512, n_ctx=2048, f16_kv=True, callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]), verbose=True, ) from langchain.chains import LLMChain from langchain.chains.prompt_selector import ConditionalPromptSelector from langchain.prompts import PromptTemplate DEFAULT_LLAMA_SEARCH_PROMPT = PromptTemplate( input_variables=["question"], template="""<<SYS>> \n You are an assistant tasked with improving Google search \ results. \n <</SYS>> \n\n [INST] Generate THREE Google search queries that \ are similar to this question. The output should be a numbered list of questions \ and each should have a question mark at the end: \n\n {question} [/INST]""", ) DEFAULT_SEARCH_PROMPT = PromptTemplate( input_variables=["question"], template="""You are an assistant tasked with improving Google search \ results. Generate THREE Google search queries that are similar to \ this question. The output should be a numbered list of questions and each \ should have a question mark at the end: {question}""", ) QUESTION_PROMPT_SELECTOR = ConditionalPromptSelector( default_prompt=DEFAULT_SEARCH_PROMPT, conditionals=[(lambda llm: isinstance(llm, LlamaCpp), DEFAULT_LLAMA_SEARCH_PROMPT)], ) prompt = QUESTION_PROMPT_SELECTOR.get_prompt(llm) prompt llm_chain =
LLMChain(prompt=prompt, llm=llm)
langchain.chains.LLMChain
from langchain_community.vectorstores import Chroma from langchain_openai import OpenAIEmbeddings from langchain_text_splitters import CharacterTextSplitter with open("../../state_of_the_union.txt") as f: state_of_the_union = f.read() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) texts = text_splitter.split_text(state_of_the_union) embeddings = OpenAIEmbeddings() docsearch = Chroma.from_texts( texts, embeddings, metadatas=[{"source": i} for i in range(len(texts))] ) query = "What did the president say about Justice Breyer" docs = docsearch.similarity_search(query) from langchain.chains.question_answering import load_qa_chain from langchain.memory import ConversationBufferMemory from langchain.prompts import PromptTemplate from langchain_openai import OpenAI template = """You are a chatbot having a conversation with a human. Given the following extracted parts of a long document and a question, create a final answer. {context} {chat_history} Human: {human_input} Chatbot:""" prompt = PromptTemplate( input_variables=["chat_history", "human_input", "context"], template=template ) memory = ConversationBufferMemory(memory_key="chat_history", input_key="human_input") chain = load_qa_chain(
OpenAI(temperature=0)
langchain_openai.OpenAI
get_ipython().run_cell_magic('writefile', 'wechat_chats.txt', '女朋友 2023/09/16 2:51 PM\n天气有点凉\n\n男朋友 2023/09/16 2:51 PM\n珍簟凉风著,瑶琴寄恨生。嵇君懒书札,底物慰秋情。\n\n女朋友 2023/09/16 3:06 PM\n忙什么呢\n\n男朋友 2023/09/16 3:06 PM\n今天只干成了一件像样的事\n那就是想你\n\n女朋友 2023/09/16 3:06 PM\n[动画表情]\n') import logging import re from typing import Iterator, List from langchain_community.chat_loaders import base as chat_loaders from langchain_core.messages import BaseMessage, HumanMessage logger = logging.getLogger() class WeChatChatLoader(chat_loaders.BaseChatLoader): def __init__(self, path: str): """ Initialize the Discord chat loader. Args: path: Path to the exported Discord chat text file. """ self.path = path self._message_line_regex = re.compile( r"(?P<sender>.+?) (?P<timestamp>\d{4}/\d{2}/\d{2} \d{1,2}:\d{2} (?:AM|PM))", # noqa ) def _append_message_to_results( self, results: List, current_sender: str, current_timestamp: str, current_content: List[str], ): content = "\n".join(current_content).strip() if not re.match(r"\[.*\]", content): results.append( HumanMessage( content=content, additional_kwargs={ "sender": current_sender, "events": [{"message_time": current_timestamp}], }, ) ) return results def _load_single_chat_session_from_txt( self, file_path: str ) -> chat_loaders.ChatSession: """ Load a single chat session from a text file. Args: file_path: Path to the text file containing the chat messages. Returns: A `ChatSession` object containing the loaded chat messages. """ with open(file_path, "r", encoding="utf-8") as file: lines = file.readlines() results: List[BaseMessage] = [] current_sender = None current_timestamp = None current_content = [] for line in lines: if re.match(self._message_line_regex, line): if current_sender and current_content: results = self._append_message_to_results( results, current_sender, current_timestamp, current_content ) current_sender, current_timestamp = re.match( self._message_line_regex, line ).groups() current_content = [] else: current_content.append(line.strip()) if current_sender and current_content: results = self._append_message_to_results( results, current_sender, current_timestamp, current_content ) return chat_loaders.ChatSession(messages=results) def lazy_load(self) -> Iterator[chat_loaders.ChatSession]: """ Lazy load the messages from the chat file and yield them in the required format. Yields: A `ChatSession` object containing the loaded chat messages. """ yield self._load_single_chat_session_from_txt(self.path) loader = WeChatChatLoader( path="./wechat_chats.txt", ) from typing import List from langchain_community.chat_loaders.base import ChatSession from langchain_community.chat_loaders.utils import ( map_ai_messages, merge_chat_runs, ) raw_messages = loader.lazy_load() merged_messages =
merge_chat_runs(raw_messages)
langchain_community.chat_loaders.utils.merge_chat_runs
import os from langchain.chains import ConversationalRetrievalChain from langchain_community.vectorstores import Vectara from langchain_openai import OpenAI from langchain_community.document_loaders import TextLoader loader = TextLoader("state_of_the_union.txt") documents = loader.load() vectara = Vectara.from_documents(documents, embedding=None) from langchain.memory import ConversationBufferMemory memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True) openai_api_key = os.environ["OPENAI_API_KEY"] llm = OpenAI(openai_api_key=openai_api_key, temperature=0) retriever = vectara.as_retriever() d = retriever.get_relevant_documents( "What did the president say about Ketanji Brown Jackson", k=2 ) print(d) bot = ConversationalRetrievalChain.from_llm( llm, retriever, memory=memory, verbose=False ) query = "What did the president say about Ketanji Brown Jackson" result = bot.invoke({"question": query}) result["answer"] query = "Did he mention who she suceeded" result = bot.invoke({"question": query}) result["answer"] bot = ConversationalRetrievalChain.from_llm( OpenAI(temperature=0), vectara.as_retriever() ) chat_history = [] query = "What did the president say about Ketanji Brown Jackson" result = bot.invoke({"question": query, "chat_history": chat_history}) result["answer"] chat_history = [(query, result["answer"])] query = "Did he mention who she suceeded" result = bot.invoke({"question": query, "chat_history": chat_history}) result["answer"] bot = ConversationalRetrievalChain.from_llm( llm, vectara.as_retriever(), return_source_documents=True ) chat_history = [] query = "What did the president say about Ketanji Brown Jackson" result = bot.invoke({"question": query, "chat_history": chat_history}) result["source_documents"][0] from langchain.chains import LLMChain from langchain.chains.conversational_retrieval.prompts import CONDENSE_QUESTION_PROMPT from langchain.chains.question_answering import load_qa_chain question_generator = LLMChain(llm=llm, prompt=CONDENSE_QUESTION_PROMPT) doc_chain = load_qa_chain(llm, chain_type="map_reduce") chain = ConversationalRetrievalChain( retriever=vectara.as_retriever(), question_generator=question_generator, combine_docs_chain=doc_chain, ) chat_history = [] query = "What did the president say about Ketanji Brown Jackson" result = chain({"question": query, "chat_history": chat_history}) result["answer"] from langchain.chains.qa_with_sources import load_qa_with_sources_chain question_generator = LLMChain(llm=llm, prompt=CONDENSE_QUESTION_PROMPT) doc_chain = load_qa_with_sources_chain(llm, chain_type="map_reduce") chain = ConversationalRetrievalChain( retriever=vectara.as_retriever(), question_generator=question_generator, combine_docs_chain=doc_chain, ) chat_history = [] query = "What did the president say about Ketanji Brown Jackson" result = chain({"question": query, "chat_history": chat_history}) result["answer"] from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler from langchain.chains.conversational_retrieval.prompts import ( CONDENSE_QUESTION_PROMPT, QA_PROMPT, ) from langchain.chains.llm import LLMChain from langchain.chains.question_answering import load_qa_chain llm =
OpenAI(temperature=0, openai_api_key=openai_api_key)
langchain_openai.OpenAI
get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain langchain-openai') from langchain_core.runnables import RunnableParallel, RunnablePassthrough runnable = RunnableParallel( passed=RunnablePassthrough(), extra=RunnablePassthrough.assign(mult=lambda x: x["num"] * 3), modified=lambda x: x["num"] + 1, ) runnable.invoke({"num": 1}) from langchain_community.vectorstores import FAISS from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_core.runnables import RunnablePassthrough from langchain_openai import ChatOpenAI, OpenAIEmbeddings vectorstore = FAISS.from_texts( ["harrison worked at kensho"], embedding=OpenAIEmbeddings() ) retriever = vectorstore.as_retriever() template = """Answer the question based only on the following context: {context} Question: {question} """ prompt =
ChatPromptTemplate.from_template(template)
langchain_core.prompts.ChatPromptTemplate.from_template
"""For basic init and call""" from langchain_community.chat_models import ChatSparkLLM from langchain_core.messages import HumanMessage chat = ChatSparkLLM( spark_app_id="<app_id>", spark_api_key="<api_key>", spark_api_secret="<api_secret>" ) message = HumanMessage(content="Hello") chat([message]) chat =
ChatSparkLLM(streaming=True)
langchain_community.chat_models.ChatSparkLLM
get_ipython().run_cell_magic('capture', '', '%pip install --upgrade --quiet python-arango # The ArangoDB Python Driver\n%pip install --upgrade --quiet adb-cloud-connector # The ArangoDB Cloud Instance provisioner\n%pip install --upgrade --quiet langchain-openai\n%pip install --upgrade --quiet langchain\n') import json from adb_cloud_connector import get_temp_credentials from arango import ArangoClient con = get_temp_credentials() db = ArangoClient(hosts=con["url"]).db( con["dbName"], con["username"], con["password"], verify=True ) print(json.dumps(con, indent=2)) from langchain_community.graphs import ArangoGraph graph =
ArangoGraph(db)
langchain_community.graphs.ArangoGraph
from typing import Callable, List from langchain.memory import ConversationBufferMemory from langchain.schema import ( AIMessage, HumanMessage, SystemMessage, ) from langchain_openai import ChatOpenAI from langchain.agents import AgentType, initialize_agent, load_tools class DialogueAgent: def __init__( self, name: str, system_message: SystemMessage, model: ChatOpenAI, ) -> None: self.name = name self.system_message = system_message self.model = model self.prefix = f"{self.name}: " self.reset() def reset(self): self.message_history = ["Here is the conversation so far."] def send(self) -> str: """ Applies the chatmodel to the message history and returns the message string """ message = self.model( [ self.system_message, HumanMessage(content="\n".join(self.message_history + [self.prefix])), ] ) return message.content def receive(self, name: str, message: str) -> None: """ Concatenates {message} spoken by {name} into message history """ self.message_history.append(f"{name}: {message}") class DialogueSimulator: def __init__( self, agents: List[DialogueAgent], selection_function: Callable[[int, List[DialogueAgent]], int], ) -> None: self.agents = agents self._step = 0 self.select_next_speaker = selection_function def reset(self): for agent in self.agents: agent.reset() def inject(self, name: str, message: str): """ Initiates the conversation with a {message} from {name} """ for agent in self.agents: agent.receive(name, message) self._step += 1 def step(self) -> tuple[str, str]: speaker_idx = self.select_next_speaker(self._step, self.agents) speaker = self.agents[speaker_idx] message = speaker.send() for receiver in self.agents: receiver.receive(speaker.name, message) self._step += 1 return speaker.name, message class DialogueAgentWithTools(DialogueAgent): def __init__( self, name: str, system_message: SystemMessage, model: ChatOpenAI, tool_names: List[str], **tool_kwargs, ) -> None: super().__init__(name, system_message, model) self.tools = load_tools(tool_names, **tool_kwargs) def send(self) -> str: """ Applies the chatmodel to the message history and returns the message string """ agent_chain = initialize_agent( self.tools, self.model, agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION, verbose=True, memory=ConversationBufferMemory( memory_key="chat_history", return_messages=True ), ) message = AIMessage( content=agent_chain.run( input="\n".join( [self.system_message.content] + self.message_history + [self.prefix] ) ) ) return message.content names = { "AI accelerationist": ["arxiv", "ddg-search", "wikipedia"], "AI alarmist": ["arxiv", "ddg-search", "wikipedia"], } topic = "The current impact of automation and artificial intelligence on employment" word_limit = 50 # word limit for task brainstorming conversation_description = f"""Here is the topic of conversation: {topic} The participants are: {', '.join(names.keys())}""" agent_descriptor_system_message = SystemMessage( content="You can add detail to the description of the conversation participant." ) def generate_agent_description(name): agent_specifier_prompt = [ agent_descriptor_system_message, HumanMessage( content=f"""{conversation_description} Please reply with a creative description of {name}, in {word_limit} words or less. Speak directly to {name}. Give them a point of view. Do not add anything else.""" ), ] agent_description = ChatOpenAI(temperature=1.0)(agent_specifier_prompt).content return agent_description agent_descriptions = {name: generate_agent_description(name) for name in names} for name, description in agent_descriptions.items(): print(description) def generate_system_message(name, description, tools): return f"""{conversation_description} Your name is {name}. Your description is as follows: {description} Your goal is to persuade your conversation partner of your point of view. DO look up information with your tool to refute your partner's claims. DO cite your sources. DO NOT fabricate fake citations. DO NOT cite any source that you did not look up. Do not add anything else. Stop speaking the moment you finish speaking from your perspective. """ agent_system_messages = { name: generate_system_message(name, description, tools) for (name, tools), description in zip(names.items(), agent_descriptions.values()) } for name, system_message in agent_system_messages.items(): print(name) print(system_message) topic_specifier_prompt = [ SystemMessage(content="You can make a topic more specific."), HumanMessage( content=f"""{topic} You are the moderator. Please make the topic more specific. Please reply with the specified quest in {word_limit} words or less. Speak directly to the participants: {*names,}. Do not add anything else.""" ), ] specified_topic = ChatOpenAI(temperature=1.0)(topic_specifier_prompt).content print(f"Original topic:\n{topic}\n") print(f"Detailed topic:\n{specified_topic}\n") agents = [ DialogueAgentWithTools( name=name, system_message=SystemMessage(content=system_message), model=
ChatOpenAI(model_name="gpt-4", temperature=0.2)
langchain_openai.ChatOpenAI
get_ipython().run_line_magic('pip', 'install --upgrade --quiet sentence-transformers > /dev/null') from langchain.chains import LLMChain, StuffDocumentsChain from langchain.prompts import PromptTemplate from langchain_community.document_transformers import ( LongContextReorder, ) from langchain_community.embeddings import HuggingFaceEmbeddings from langchain_community.vectorstores import Chroma from langchain_openai import OpenAI embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2") texts = [ "Basquetball is a great sport.", "Fly me to the moon is one of my favourite songs.", "The Celtics are my favourite team.", "This is a document about the Boston Celtics", "I simply love going to the movies", "The Boston Celtics won the game by 20 points", "This is just a random text.", "Elden Ring is one of the best games in the last 15 years.", "L. Kornet is one of the best Celtics players.", "Larry Bird was an iconic NBA player.", ] retriever = Chroma.from_texts(texts, embedding=embeddings).as_retriever( search_kwargs={"k": 10} ) query = "What can you tell me about the Celtics?" docs = retriever.get_relevant_documents(query) docs reordering = LongContextReorder() reordered_docs = reordering.transform_documents(docs) reordered_docs document_prompt = PromptTemplate( input_variables=["page_content"], template="{page_content}" ) document_variable_name = "context" llm =
OpenAI()
langchain_openai.OpenAI
from langchain.evaluation import RegexMatchStringEvaluator evaluator =
RegexMatchStringEvaluator()
langchain.evaluation.RegexMatchStringEvaluator
get_ipython().run_line_magic('pip', 'install -qU langchain langchain-openai langchain-anthropic langchain-community wikipedia') import getpass import os os.environ["OPENAI_API_KEY"] = getpass.getpass() os.environ["ANTHROPIC_API_KEY"] = getpass.getpass() from langchain_community.retrievers import WikipediaRetriever from langchain_core.prompts import ChatPromptTemplate from langchain_openai import ChatOpenAI llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0) wiki = WikipediaRetriever(top_k_results=6, doc_content_chars_max=2000) prompt = ChatPromptTemplate.from_messages( [ ( "system", "You're a helpful AI assistant. Given a user question and some Wikipedia article snippets, answer the user question. If none of the articles answer the question, just say you don't know.\n\nHere are the Wikipedia articles:{context}", ), ("human", "{question}"), ] ) prompt.pretty_print() from operator import itemgetter from typing import List from langchain_core.documents import Document from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables import ( RunnableLambda, RunnableParallel, RunnablePassthrough, ) def format_docs(docs: List[Document]) -> str: """Convert Documents to a single string.:""" formatted = [ f"Article Title: {doc.metadata['title']}\nArticle Snippet: {doc.page_content}" for doc in docs ] return "\n\n" + "\n\n".join(formatted) format = itemgetter("docs") | RunnableLambda(format_docs) answer = prompt | llm | StrOutputParser() chain = ( RunnableParallel(question=RunnablePassthrough(), docs=wiki) .assign(context=format) .assign(answer=answer) .pick(["answer", "docs"]) ) chain.invoke("How fast are cheetahs?") from langchain_core.pydantic_v1 import BaseModel, Field class cited_answer(BaseModel): """Answer the user question based only on the given sources, and cite the sources used.""" answer: str = Field( ..., description="The answer to the user question, which is based only on the given sources.", ) citations: List[int] = Field( ..., description="The integer IDs of the SPECIFIC sources which justify the answer.", ) llm_with_tool = llm.bind_tools( [cited_answer], tool_choice="cited_answer", ) example_q = """What Brian's height? Source: 1 Information: Suzy is 6'2" Source: 2 Information: Jeremiah is blonde Source: 3 Information: Brian is 3 inches shorted than Suzy""" llm_with_tool.invoke(example_q) from langchain.output_parsers.openai_tools import JsonOutputKeyToolsParser output_parser = JsonOutputKeyToolsParser(key_name="cited_answer", return_single=True) (llm_with_tool | output_parser).invoke(example_q) def format_docs_with_id(docs: List[Document]) -> str: formatted = [ f"Source ID: {i}\nArticle Title: {doc.metadata['title']}\nArticle Snippet: {doc.page_content}" for i, doc in enumerate(docs) ] return "\n\n" + "\n\n".join(formatted) format_1 = itemgetter("docs") | RunnableLambda(format_docs_with_id) answer_1 = prompt | llm_with_tool | output_parser chain_1 = ( RunnableParallel(question=RunnablePassthrough(), docs=wiki) .assign(context=format_1) .assign(cited_answer=answer_1) .pick(["cited_answer", "docs"]) ) chain_1.invoke("How fast are cheetahs?") class Citation(BaseModel): source_id: int = Field( ..., description="The integer ID of a SPECIFIC source which justifies the answer.", ) quote: str = Field( ..., description="The VERBATIM quote from the specified source that justifies the answer.", ) class quoted_answer(BaseModel): """Answer the user question based only on the given sources, and cite the sources used.""" answer: str = Field( ..., description="The answer to the user question, which is based only on the given sources.", ) citations: List[Citation] = Field( ..., description="Citations from the given sources that justify the answer." ) output_parser_2 = JsonOutputKeyToolsParser(key_name="quoted_answer", return_single=True) llm_with_tool_2 = llm.bind_tools( [quoted_answer], tool_choice="quoted_answer", ) format_2 = itemgetter("docs") | RunnableLambda(format_docs_with_id) answer_2 = prompt | llm_with_tool_2 | output_parser_2 chain_2 = ( RunnableParallel(question=RunnablePassthrough(), docs=wiki) .assign(context=format_2) .assign(quoted_answer=answer_2) .pick(["quoted_answer", "docs"]) ) chain_2.invoke("How fast are cheetahs?") from langchain_anthropic import ChatAnthropicMessages anthropic = ChatAnthropicMessages(model_name="claude-instant-1.2") system = """You're a helpful AI assistant. Given a user question and some Wikipedia article snippets, \ answer the user question and provide citations. If none of the articles answer the question, just say you don't know. Remember, you must return both an answer and citations. A citation consists of a VERBATIM quote that \ justifies the answer and the ID of the quote article. Return a citation for every quote across all articles \ that justify the answer. Use the following format for your final output: <cited_answer> <answer></answer> <citations> <citation><source_id></source_id><quote></quote></citation> <citation><source_id></source_id><quote></quote></citation> ... </citations> </cited_answer> Here are the Wikipedia articles:{context}""" prompt_3 =
ChatPromptTemplate.from_messages( [("system", system)
langchain_core.prompts.ChatPromptTemplate.from_messages
get_ipython().run_line_magic('pip', 'install --upgrade --quiet rspace_client') from langchain_community.document_loaders.rspace import RSpaceLoader rspace_ids = ["NB1932027", "FL1921314", "SD1932029", "GL1932384"] for rs_id in rspace_ids: loader =
RSpaceLoader(global_id=rs_id)
langchain_community.document_loaders.rspace.RSpaceLoader
import os os.environ["OPENAI_API_KEY"] = "..." from langchain.prompts import PromptTemplate from langchain_experimental.smart_llm import SmartLLMChain from langchain_openai import ChatOpenAI hard_question = "I have a 12 liter jug and a 6 liter jug. I want to measure 6 liters. How do I do it?" prompt =
PromptTemplate.from_template(hard_question)
langchain.prompts.PromptTemplate.from_template
get_ipython().system(' pip install --quiet pypdf chromadb tiktoken openai langchain-together') from langchain_community.document_loaders import PyPDFLoader loader = PyPDFLoader("~/Desktop/mixtral.pdf") data = loader.load() from langchain_text_splitters import RecursiveCharacterTextSplitter text_splitter = RecursiveCharacterTextSplitter(chunk_size=2000, chunk_overlap=0) all_splits = text_splitter.split_documents(data) from langchain_community.embeddings import OpenAIEmbeddings from langchain_community.vectorstores import Chroma """ from langchain_together.embeddings import TogetherEmbeddings embeddings = TogetherEmbeddings(model="togethercomputer/m2-bert-80M-8k-retrieval") """ vectorstore = Chroma.from_documents( documents=all_splits, collection_name="rag-chroma", embedding=OpenAIEmbeddings(), ) retriever = vectorstore.as_retriever() from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_core.pydantic_v1 import BaseModel from langchain_core.runnables import RunnableParallel, RunnablePassthrough template = """Answer the question based only on the following context: {context} Question: {question} """ prompt = ChatPromptTemplate.from_template(template) from langchain_together import Together llm = Together( model="mistralai/Mixtral-8x7B-Instruct-v0.1", temperature=0.0, max_tokens=2000, top_k=1, ) chain = ( RunnableParallel({"context": retriever, "question": RunnablePassthrough()}) | prompt | llm |
StrOutputParser()
langchain_core.output_parsers.StrOutputParser
from langchain.agents import AgentExecutor, Tool, ZeroShotAgent from langchain.chains import LLMChain from langchain.memory import ConversationBufferMemory from langchain_community.utilities import GoogleSearchAPIWrapper from langchain_openai import OpenAI search =
GoogleSearchAPIWrapper()
langchain_community.utilities.GoogleSearchAPIWrapper
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()
langchain_core.output_parsers.StrOutputParser
get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain langchain-openai') from langchain.evaluation import load_evaluator evaluator =
load_evaluator("trajectory")
langchain.evaluation.load_evaluator
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")
langchain_core.runnables.ConfigurableField
get_ipython().run_line_magic('pip', 'install --upgrade --quiet openlm') get_ipython().run_line_magic('pip', 'install --upgrade --quiet langchain-openai') import os from getpass import getpass if "OPENAI_API_KEY" not in os.environ: print("Enter your OpenAI API key:") os.environ["OPENAI_API_KEY"] = getpass() if "HF_API_TOKEN" not in os.environ: print("Enter your HuggingFace Hub API key:") os.environ["HF_API_TOKEN"] = getpass() from langchain.chains import LLMChain from langchain.prompts import PromptTemplate from langchain_community.llms import OpenLM question = "What is the capital of France?" template = """Question: {question} Answer: Let's think step by step.""" prompt = PromptTemplate.from_template(template) for model in ["text-davinci-003", "huggingface.co/gpt2"]: llm = OpenLM(model=model) llm_chain =
LLMChain(prompt=prompt, llm=llm)
langchain.chains.LLMChain
from langchain.agents import AgentExecutor, Tool, ZeroShotAgent from langchain.chains import LLMChain from langchain.memory import ConversationBufferMemory, ReadOnlySharedMemory from langchain.prompts import PromptTemplate from langchain_community.utilities import GoogleSearchAPIWrapper from langchain_openai import OpenAI template = """This is a conversation between a human and a bot: {chat_history} Write a summary of the conversation for {input}: """ prompt = PromptTemplate(input_variables=["input", "chat_history"], template=template) memory = ConversationBufferMemory(memory_key="chat_history") readonlymemory = ReadOnlySharedMemory(memory=memory) summary_chain = LLMChain( llm=OpenAI(), prompt=prompt, verbose=True, memory=readonlymemory, # use the read-only memory to prevent the tool from modifying the memory ) search = GoogleSearchAPIWrapper() tools = [ Tool( name="Search", func=search.run, description="useful for when you need to answer questions about current events", ), Tool( name="Summary", func=summary_chain.run, description="useful for when you summarize a conversation. The input to this tool should be a string, representing who will read this summary.", ), ] prefix = """Have a conversation with a human, answering the following questions as best you can. You have access to the following tools:""" suffix = """Begin!" {chat_history} Question: {input} {agent_scratchpad}""" prompt = ZeroShotAgent.create_prompt( tools, prefix=prefix, suffix=suffix, input_variables=["input", "chat_history", "agent_scratchpad"], ) llm_chain = LLMChain(llm=
OpenAI(temperature=0)
langchain_openai.OpenAI
import uuid from pathlib import Path import langchain import torch from bs4 import BeautifulSoup as Soup from langchain.retrievers.multi_vector import MultiVectorRetriever from langchain.storage import InMemoryByteStore, LocalFileStore from langchain_community.document_loaders.recursive_url_loader import ( RecursiveUrlLoader, ) from langchain_community.vectorstores import Chroma from langchain_text_splitters import RecursiveCharacterTextSplitter # noqa DOCSTORE_DIR = "." DOCSTORE_ID_KEY = "doc_id" loader = RecursiveUrlLoader( "https://ar5iv.labs.arxiv.org/html/1706.03762", max_depth=2, extractor=lambda x: Soup(x, "html.parser").text, ) data = loader.load() print(f"Loaded {len(data)} documents") text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=0) all_splits = text_splitter.split_documents(data) print(f"Split into {len(all_splits)} documents") from langchain_community.embeddings import QuantizedBiEncoderEmbeddings from langchain_core.embeddings import Embeddings model_name = "Intel/bge-small-en-v1.5-rag-int8-static" encode_kwargs = {"normalize_embeddings": True} # set True to compute cosine similarity model_inc = QuantizedBiEncoderEmbeddings( model_name=model_name, encode_kwargs=encode_kwargs, query_instruction="Represent this sentence for searching relevant passages: ", ) def get_multi_vector_retriever( docstore_id_key: str, collection_name: str, embedding_function: Embeddings ): """Create the composed retriever object.""" vectorstore = Chroma( collection_name=collection_name, embedding_function=embedding_function, ) store = InMemoryByteStore() return MultiVectorRetriever( vectorstore=vectorstore, byte_store=store, id_key=docstore_id_key, ) retriever = get_multi_vector_retriever(DOCSTORE_ID_KEY, "multi_vec_store", model_inc) child_text_splitter = RecursiveCharacterTextSplitter(chunk_size=400) id_key = "doc_id" doc_ids = [str(uuid.uuid4()) for _ in all_splits] sub_docs = [] for i, doc in enumerate(all_splits): _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, all_splits))) import torch from langchain.llms.huggingface_pipeline import HuggingFacePipeline from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline model_id = "Intel/neural-chat-7b-v3-3" tokenizer = AutoTokenizer.from_pretrained(model_id) model = AutoModelForCausalLM.from_pretrained( model_id, device_map="auto", torch_dtype=torch.bfloat16 ) pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, max_new_tokens=100) hf = HuggingFacePipeline(pipeline=pipe) from langchain import hub prompt = hub.pull("rlm/rag-prompt") from langchain.schema.runnable import RunnablePassthrough rag_chain = {"context": retriever, "question":
RunnablePassthrough()
langchain.schema.runnable.RunnablePassthrough
from langchain_core.messages import ( AIMessage, BaseMessage, FunctionMessage, HumanMessage, SystemMessage, ToolMessage, ) from langchain_core.messages import ( AIMessageChunk, FunctionMessageChunk, HumanMessageChunk, SystemMessageChunk, ToolMessageChunk, ) AIMessageChunk(content="Hello") + AIMessageChunk(content=" World!") from typing import Any, AsyncIterator, Dict, Iterator, List, Optional from langchain_core.callbacks import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain_core.language_models import BaseChatModel, SimpleChatModel from langchain_core.messages import AIMessageChunk, BaseMessage, HumanMessage from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult from langchain_core.runnables import run_in_executor class CustomChatModelAdvanced(BaseChatModel): """A custom chat model that echoes the first `n` characters of the input. When contributing an implementation to LangChain, carefully document the model including the initialization parameters, include an example of how to initialize the model and include any relevant links to the underlying models documentation or API. Example: .. code-block:: python model = CustomChatModel(n=2) result = model.invoke([HumanMessage(content="hello")]) result = model.batch([[HumanMessage(content="hello")], [HumanMessage(content="world")]]) """ n: int """The number of characters from the last message of the prompt to be echoed.""" def _generate( self, messages: List[BaseMessage], stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> ChatResult: """Override the _generate method to implement the chat model logic. This can be a call to an API, a call to a local model, or any other implementation that generates a response to the input prompt. Args: messages: the prompt composed of a list of messages. stop: a list of strings on which the model should stop generating. If generation stops due to a stop token, the stop token itself SHOULD BE INCLUDED as part of the output. This is not enforced across models right now, but it's a good practice to follow since it makes it much easier to parse the output of the model downstream and understand why generation stopped. run_manager: A run manager with callbacks for the LLM. """ last_message = messages[-1] tokens = last_message.content[: self.n] message = AIMessage(content=tokens) generation = ChatGeneration(message=message) return ChatResult(generations=[generation]) def _stream( self, messages: List[BaseMessage], stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> Iterator[ChatGenerationChunk]: """Stream the output of the model. This method should be implemented if the model can generate output in a streaming fashion. If the model does not support streaming, do not implement it. In that case streaming requests will be automatically handled by the _generate method. Args: messages: the prompt composed of a list of messages. stop: a list of strings on which the model should stop generating. If generation stops due to a stop token, the stop token itself SHOULD BE INCLUDED as part of the output. This is not enforced across models right now, but it's a good practice to follow since it makes it much easier to parse the output of the model downstream and understand why generation stopped. run_manager: A run manager with callbacks for the LLM. """ last_message = messages[-1] tokens = last_message.content[: self.n] for token in tokens: chunk = ChatGenerationChunk(message=
AIMessageChunk(content=token)
langchain_core.messages.AIMessageChunk