Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
# from dataclasses import dataclass
|
| 3 |
+
from langchain_community.vectorstores import Chroma
|
| 4 |
+
from langchain_openai import OpenAIEmbeddings
|
| 5 |
+
from langchain_openai import ChatOpenAI
|
| 6 |
+
from langchain.prompts import ChatPromptTemplate
|
| 7 |
+
|
| 8 |
+
CHROMA_PATH = "chroma"
|
| 9 |
+
|
| 10 |
+
PROMPT_TEMPLATE = """
|
| 11 |
+
Answer the question based only on the following context:
|
| 12 |
+
|
| 13 |
+
{context}
|
| 14 |
+
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
Answer the question based on the above context: {question}
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def main():
|
| 22 |
+
# Create CLI.
|
| 23 |
+
parser = argparse.ArgumentParser()
|
| 24 |
+
parser.add_argument("query_text", type=str, help="The query text.")
|
| 25 |
+
args = parser.parse_args()
|
| 26 |
+
query_text = args.query_text
|
| 27 |
+
|
| 28 |
+
# Prepare the DB.
|
| 29 |
+
embedding_function = OpenAIEmbeddings()
|
| 30 |
+
db = Chroma(persist_directory=CHROMA_PATH, embedding_function=embedding_function)
|
| 31 |
+
|
| 32 |
+
# Search the DB.
|
| 33 |
+
results = db.similarity_search_with_relevance_scores(query_text, k=3)
|
| 34 |
+
if len(results) == 0 or results[0][1] < 0.7:
|
| 35 |
+
print(f"Unable to find matching results.")
|
| 36 |
+
return
|
| 37 |
+
|
| 38 |
+
context_text = "\n\n---\n\n".join([doc.page_content for doc, _score in results])
|
| 39 |
+
prompt_template = ChatPromptTemplate.from_template(PROMPT_TEMPLATE)
|
| 40 |
+
prompt = prompt_template.format(context=context_text, question=query_text)
|
| 41 |
+
print(prompt)
|
| 42 |
+
|
| 43 |
+
model = ChatOpenAI()
|
| 44 |
+
response_text = model.predict(prompt)
|
| 45 |
+
|
| 46 |
+
sources = [doc.metadata.get("source", None) for doc, _score in results]
|
| 47 |
+
formatted_response = f"Response: {response_text}\nSources: {sources}"
|
| 48 |
+
print(formatted_response)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
if __name__ == "__main__":
|
| 52 |
+
main()
|