Skip to content

Instantly share code, notes, and snippets.

@haohanyang
Created May 19, 2024 19:37
Show Gist options
  • Save haohanyang/afbead54fafcb80959cd215025ea3ca2 to your computer and use it in GitHub Desktop.
Save haohanyang/afbead54fafcb80959cd215025ea3ca2 to your computer and use it in GitHub Desktop.
Get start with LangChain
from langchain_cohere import ChatCohere
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.output_parsers import StrOutputParser
from langchain_community.document_loaders import WebBaseLoader
from langchain_cohere.embeddings import CohereEmbeddings
from langchain_community.vectorstores import FAISS
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain.chains import create_retrieval_chain
COHERE_API_KEY = "2kCP5oLe6XsNfheXuHPuNfb1lbAqkCqU"
llm = ChatCohere(cohere_api_key=COHERE_API_KEY)
prompt = ChatPromptTemplate.from_template(
"""Answer the following question based only on the provided context:
<context>
{context}
</context>
Question: {input}"""
)
output_parser = StrOutputParser()
loader = WebBaseLoader("https://docs.smith.langchain.com/user_guide")
docs = loader.load()
embeddings = CohereEmbeddings(cohere_api_key=COHERE_API_KEY)
text_splitter = RecursiveCharacterTextSplitter()
documents = text_splitter.split_documents(docs)
vector = FAISS.from_documents(documents, embeddings)
document_chain = create_stuff_documents_chain(llm, prompt)
retriever = vector.as_retriever()
retrieval_chain = create_retrieval_chain(retriever, document_chain)
response = retrieval_chain.invoke({"input": "how can langsmith help with testing?"})
print(response["answer"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment