-
Notifications
You must be signed in to change notification settings - Fork 773
Expand file tree
/
Copy path6_rag_one_off_question.py
More file actions
64 lines (51 loc) · 1.95 KB
/
6_rag_one_off_question.py
File metadata and controls
64 lines (51 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import os
from dotenv import load_dotenv
from langchain_community.vectorstores import Chroma
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
# Load environment variables from .env
load_dotenv()
# Define the persistent directory
current_dir = os.path.dirname(os.path.abspath(__file__))
persistent_directory = os.path.join(
current_dir, "db", "chroma_db_with_metadata")
# Define the embedding model
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
# Load the existing vector store with the embedding function
db = Chroma(persist_directory=persistent_directory,
embedding_function=embeddings)
# Define the user's question
query = "How can I learn more about LangChain?"
# Retrieve relevant documents based on the query
retriever = db.as_retriever(
search_type="similarity",
search_kwargs={"k": 1},
)
relevant_docs = retriever.invoke(query)
# Display the relevant results with metadata
print("\n--- Relevant Documents ---")
for i, doc in enumerate(relevant_docs, 1):
print(f"Document {i}:\n{doc.page_content}\n")
# Combine the query and the relevant document contents
combined_input = (
"Here are some documents that might help answer the question: "
+ query
+ "\n\nRelevant Documents:\n"
+ "\n\n".join([doc.page_content for doc in relevant_docs])
+ "\n\nPlease provide an answer based only on the provided documents. If the answer is not found in the documents, respond with 'I'm not sure'."
)
# Create a ChatOpenAI model
model = ChatOpenAI(model="gpt-4o")
# Define the messages for the model
messages = [
SystemMessage(content="You are a helpful assistant."),
HumanMessage(content=combined_input),
]
# Invoke the model with the combined input
result = model.invoke(messages)
# Display the full result and content only
print("\n--- Generated Response ---")
# print("Full result:")
# print(result)
print("Content only:")
print(result.content)