langchain/templates/cohere-librarian/cohere_librarian/blurb_matcher.py
billytrend-cohere 7e4dbb26a8
templates[patch]: Add cohere librarian template (#14601)
Adding the example I build for the Cohere hackathon.

It can:

use a vector database to reccommend books

<img width="840" alt="image"
src="https://github.com/langchain-ai/langchain/assets/144115527/96543a18-217b-4445-ab4b-950c7cced915">

Use a prompt template to provide information about the library

<img width="834" alt="image"
src="https://github.com/langchain-ai/langchain/assets/144115527/996c8e0f-cab0-4213-bcc9-9baf84f1494b">

Use Cohere RAG to provide grounded results

<img width="822" alt="image"
src="https://github.com/langchain-ai/langchain/assets/144115527/7bb4a883-5316-41a9-9d2e-19fd49a43dcb">

---------

Co-authored-by: Erick Friis <erick@langchain.dev>
2023-12-13 14:34:44 -08:00

50 lines
1.2 KiB
Python

import csv
from langchain.chains.question_answering import load_qa_chain
from langchain.embeddings import CohereEmbeddings
from langchain.prompts import PromptTemplate
from langchain.vectorstores import Chroma
from .chat import chat
csv_file = open("data/books_with_blurbs.csv", "r")
csv_reader = csv.reader(csv_file)
csv_data = list(csv_reader)
parsed_data = [
{
"id": x[0],
"title": x[1],
"author": x[2],
"year": x[3],
"publisher": x[4],
"blurb": x[5],
}
for x in csv_data
]
parsed_data[1]
embeddings = CohereEmbeddings()
docsearch = Chroma.from_texts(
[x["title"] for x in parsed_data], embeddings, metadatas=parsed_data
).as_retriever()
prompt_template = """
{context}
Use the book reccommendations to suggest books for the user to read.
Only use the titles of the books, do not make up titles. Format the response as
a bulleted list prefixed by a relevant message.
User: {message}"""
PROMPT = PromptTemplate(
template=prompt_template, input_variables=["context", "message"]
)
book_rec_chain = {
"input_documents": lambda x: docsearch.get_relevant_documents(x["message"]),
"message": lambda x: x["message"],
} | load_qa_chain(chat, chain_type="stuff", prompt=PROMPT)