Spaces:
Sleeping
Sleeping
soyleyicicem
commited on
Upload 8 files
Browse files- __init__.py +0 -0
- app.py +105 -0
- db_operations.py +91 -0
- embedding_loader.py +22 -0
- initialize_db.py +41 -0
- pdf_loader.py +111 -0
- requirements.txt +211 -0
- wrappers.py +549 -0
__init__.py
ADDED
File without changes
|
app.py
ADDED
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import uuid
|
2 |
+
from wrappers import *
|
3 |
+
from embedding_loader import *
|
4 |
+
from initialize_db import QdrantClientInitializer
|
5 |
+
from pdf_loader import PDFLoader
|
6 |
+
from IPython.display import display, Markdown
|
7 |
+
import gradio as gr
|
8 |
+
from langchain_core.messages import HumanMessage, AIMessage
|
9 |
+
from langchain.memory import ConversationBufferMemory
|
10 |
+
from langchain_core.chat_history import InMemoryChatMessageHistory
|
11 |
+
|
12 |
+
embeddings = import_embedding()
|
13 |
+
AZURE_OPENAI_KEY = os.getenv('azure_api')
|
14 |
+
os.environ['AZURE_OPENAI_KEY'] = AZURE_OPENAI_KEY
|
15 |
+
openai.api_version = "2024-02-15-preview" # change it with your own version
|
16 |
+
openai.azure_endpoint = os.getenv('azure_endpoint')
|
17 |
+
model = "gpt35turbo" # deployment name on Azure OPENAI Studio
|
18 |
+
myLLM = AzureChatOpenAI(azure_endpoint = openai.azure_endpoint,
|
19 |
+
api_key=AZURE_OPENAI_KEY,
|
20 |
+
api_version=openai.api_version,
|
21 |
+
temperature=0,
|
22 |
+
streaming=True,
|
23 |
+
model = model,)
|
24 |
+
|
25 |
+
obj_qdrant = QdrantClientInitializer()
|
26 |
+
client = obj_qdrant.initialize_db()
|
27 |
+
obj_loader = PDFLoader()
|
28 |
+
|
29 |
+
def print_result(question, result):
|
30 |
+
output_text = f"""### Question:
|
31 |
+
{question}
|
32 |
+
### Answer:
|
33 |
+
{result}
|
34 |
+
"""
|
35 |
+
return(output_text)
|
36 |
+
|
37 |
+
def format_chat_prompt(chat_history):
|
38 |
+
prompt = []
|
39 |
+
|
40 |
+
for turn in chat_history:
|
41 |
+
user_message, ai_message = turn
|
42 |
+
prompt.append(HumanMessage(user_message))
|
43 |
+
prompt.append(AIMessage(ai_message))
|
44 |
+
|
45 |
+
chat_history = InMemoryChatMessageHistory(messages=prompt)
|
46 |
+
memory = ConversationBufferMemory(chat_memory=chat_history, memory_key="history", input_key="question")
|
47 |
+
return memory
|
48 |
+
|
49 |
+
def chat(question, manual, history):
|
50 |
+
history = history or []
|
51 |
+
memory = format_chat_prompt(history)
|
52 |
+
manual_list = {"Toyota_Corolla_2024_TR": -8580416610875007536,
|
53 |
+
"Renault_Clio_2024_TR":-5514489544983735006,
|
54 |
+
"Fiat_Egea_2024_TR":-2026113796962100812}
|
55 |
+
|
56 |
+
collection_list = {"Toyota_Corolla_2024_TR": "TOYOTA_MANUAL_COLLECTION_EMBED3",
|
57 |
+
"Renault_Clio_2024_TR": "RENAULT_MANUAL_COLLECTION_EMBED3",
|
58 |
+
"Fiat_Egea_2024_TR": "FIAT_MANUAL_COLLECTION_EMBED3"}
|
59 |
+
|
60 |
+
collection_name = collection_list[f"{manual}"]
|
61 |
+
|
62 |
+
db = obj_loader.load_from_database(embeddings=embeddings, collection_name=collection_name)
|
63 |
+
|
64 |
+
CAR_ID = manual_list[f"{manual}"]
|
65 |
+
wrapper = Wrappers(collection_name, client, embeddings, myLLM, db, CAR_ID, memory)
|
66 |
+
|
67 |
+
inputs = {"question": question, "iter_halucination": 0}
|
68 |
+
app = wrapper.lagchain_graph()
|
69 |
+
|
70 |
+
for output in app.stream(inputs):
|
71 |
+
for key, value in output.items():
|
72 |
+
pprint(f"Finished running: {key}:")
|
73 |
+
# display(Markdown(print_result(question, value["generation"]['text'])))
|
74 |
+
response = value["generation"]['text']
|
75 |
+
history.append((question, response))
|
76 |
+
|
77 |
+
point_id = uuid.uuid4().hex
|
78 |
+
DatabaseOperations.save_user_history_demo(client, "USER_COLLECTION_EMBED3", question, response, embeddings, point_id, manual)
|
79 |
+
|
80 |
+
return '', history
|
81 |
+
|
82 |
+
def vote(data: gr.LikeData):
|
83 |
+
if data.liked:
|
84 |
+
print("You upvoted this response: ")
|
85 |
+
return "OK"
|
86 |
+
else:
|
87 |
+
print("You downvoted this response: " )
|
88 |
+
return "NOK"
|
89 |
+
|
90 |
+
|
91 |
+
|
92 |
+
manual_list = ["Toyota_Corolla_2024_TR", "Renault_Clio_2024_TR", "Fiat_Egea_2024_TR"]
|
93 |
+
|
94 |
+
with gr.Blocks() as demo:
|
95 |
+
|
96 |
+
chatbot = gr.Chatbot(height=600)
|
97 |
+
manual = gr.Dropdown(label="Kullanım Kılavuzları", value="Toyota_Corolla_2024_TR", choices=manual_list)
|
98 |
+
textbox = gr.Textbox()
|
99 |
+
clear = gr.ClearButton(components=[textbox, chatbot], value='Clear console')
|
100 |
+
textbox.submit(chat, [textbox, manual, chatbot], [textbox, chatbot])
|
101 |
+
chatbot.like(vote, None, None) # Adding this line causes the like/dislike icons to appear in your chatbot
|
102 |
+
|
103 |
+
# gr.close_all()
|
104 |
+
demo.launch(share=True)
|
105 |
+
|
db_operations.py
ADDED
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import datetime
|
2 |
+
from qdrant_client import QdrantClient, models
|
3 |
+
from langchain_qdrant import Qdrant
|
4 |
+
|
5 |
+
class DatabaseOperations:
|
6 |
+
|
7 |
+
def __init__(self):
|
8 |
+
pass
|
9 |
+
|
10 |
+
def save_user_history(client, collection_name, question, answer, embeddings, point_id, user_id, session_id):
|
11 |
+
|
12 |
+
vector = embeddings.embed_documents([question])[0]
|
13 |
+
client.upsert(
|
14 |
+
collection_name=collection_name,
|
15 |
+
points=[
|
16 |
+
models.PointStruct(
|
17 |
+
id=point_id,
|
18 |
+
payload={"user_id": user_id,
|
19 |
+
"session_id": session_id,
|
20 |
+
"create_date": datetime.datetime.now().isoformat(),
|
21 |
+
"question": question,
|
22 |
+
"answer": answer},
|
23 |
+
vector=vector,
|
24 |
+
)
|
25 |
+
],
|
26 |
+
)
|
27 |
+
|
28 |
+
def save_user_history_demo(client, collection_name, question, answer, embeddings, point_id, manual):
|
29 |
+
|
30 |
+
vector = embeddings.embed_documents([question])[0]
|
31 |
+
client.upsert(
|
32 |
+
collection_name=collection_name,
|
33 |
+
points=[
|
34 |
+
models.PointStruct(
|
35 |
+
id=point_id,
|
36 |
+
payload={"manual": manual,
|
37 |
+
"create_date": datetime.datetime.now().isoformat(),
|
38 |
+
"question": question,
|
39 |
+
"answer": answer},
|
40 |
+
vector=vector,
|
41 |
+
)
|
42 |
+
],
|
43 |
+
)
|
44 |
+
|
45 |
+
def question_history_search(client, collection_name, car_id, question, embeddings, threshold=0.9):
|
46 |
+
|
47 |
+
CAR_ID = car_id
|
48 |
+
|
49 |
+
vector = embeddings.embed_documents([question])[0]
|
50 |
+
|
51 |
+
search_result = client.search(collection_name=collection_name,
|
52 |
+
query_vector=vector,
|
53 |
+
query_filter=models.Filter(
|
54 |
+
must=[
|
55 |
+
models.FieldCondition(key="car_id", match=models.MatchValue(value=CAR_ID)),
|
56 |
+
models.FieldCondition(key="source_name", match=models.MatchValue(value="User Question"))
|
57 |
+
]
|
58 |
+
),
|
59 |
+
score_threshold=threshold,
|
60 |
+
limit=1)
|
61 |
+
return search_result
|
62 |
+
|
63 |
+
def user_history_scroll(client, collection_name, user_id, key="user_id"):
|
64 |
+
|
65 |
+
history = client.scroll(collection_name=collection_name,
|
66 |
+
scroll_filter=models.Filter(
|
67 |
+
must=[
|
68 |
+
models.FieldCondition(key=key, match=models.MatchValue(value=user_id))
|
69 |
+
]
|
70 |
+
))
|
71 |
+
return history
|
72 |
+
|
73 |
+
def save_question_history(client, collection_name, question, answer, embeddings,
|
74 |
+
point_id, car_id, source_name, model_year):
|
75 |
+
|
76 |
+
vector = embeddings.embed_documents([question])[0]
|
77 |
+
client.upsert(
|
78 |
+
collection_name=collection_name,
|
79 |
+
points=[
|
80 |
+
models.PointStruct(
|
81 |
+
id=point_id,
|
82 |
+
payload={"source_name": source_name,
|
83 |
+
"page_content": question,
|
84 |
+
"car_id": car_id,
|
85 |
+
"model_year": model_year,
|
86 |
+
"create_date": datetime.datetime.now().isoformat(),
|
87 |
+
"answer": answer},
|
88 |
+
vector=vector,
|
89 |
+
)
|
90 |
+
],
|
91 |
+
)
|
embedding_loader.py
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
2 |
+
from langchain_openai import AzureOpenAIEmbeddings
|
3 |
+
import openai
|
4 |
+
import os
|
5 |
+
def import_embedding():
|
6 |
+
# embedding_name = None
|
7 |
+
# myEmbeddingModel = HuggingFaceEmbeddings(
|
8 |
+
# model_name = embedding_name,
|
9 |
+
# model_kwargs = {'device':'cuda'},
|
10 |
+
# encode_kwargs={'normalize_embeddings':True})
|
11 |
+
|
12 |
+
AZURE_OPENAI_KEY = os.getenv('azure_api')
|
13 |
+
os.environ['AZURE_OPENAI_KEY'] = AZURE_OPENAI_KEY
|
14 |
+
openai.api_version = "2024-02-15-preview" # change it with your own version
|
15 |
+
openai.azure_endpoint = os.getenv('azure_endpoint')
|
16 |
+
embedding_name = "embedding3large" # deployment name on Azure OPENAI Studio
|
17 |
+
myEmbeddingModel = AzureOpenAIEmbeddings(azure_deployment=embedding_name,
|
18 |
+
azure_endpoint = openai.azure_endpoint,
|
19 |
+
api_key=AZURE_OPENAI_KEY,
|
20 |
+
api_version=openai.api_version)
|
21 |
+
|
22 |
+
return myEmbeddingModel
|
initialize_db.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import datetime
|
2 |
+
import subprocess
|
3 |
+
from qdrant_client import QdrantClient, models
|
4 |
+
import os
|
5 |
+
class QdrantClientInitializer:
|
6 |
+
|
7 |
+
def __init__(self):
|
8 |
+
pass
|
9 |
+
|
10 |
+
def run_docker(self):
|
11 |
+
# Define the Docker command
|
12 |
+
docker_command = [
|
13 |
+
"docker run -d -p 6333:6333 -p 6334:6334 \
|
14 |
+
-v $(pwd)/qdrant_storage:/qdrant/storage:z \
|
15 |
+
qdrant/qdrant"
|
16 |
+
]
|
17 |
+
|
18 |
+
# Run the Docker command
|
19 |
+
subprocess.run(docker_command, shell=True)
|
20 |
+
print("Docker container is running in the background.")
|
21 |
+
|
22 |
+
def initialize_db(self):
|
23 |
+
client = QdrantClient(
|
24 |
+
url=os.getenv('qdrant_url'),
|
25 |
+
api_key=os.getenv('qdrant_api'), timeout=20)
|
26 |
+
# client = QdrantClient(url="http://localhost:6333", timeout=1200, grpc_port=6333)
|
27 |
+
|
28 |
+
return client
|
29 |
+
|
30 |
+
def create_collection(self, client, collection_name, vector_size=4096, distance=models.Distance.COSINE):
|
31 |
+
|
32 |
+
if client.collection_exists(collection_name=collection_name):
|
33 |
+
print("{name} is exist!".format(name=collection_name))
|
34 |
+
|
35 |
+
else:
|
36 |
+
print("Name is not exist!")
|
37 |
+
client.create_collection(collection_name=collection_name,
|
38 |
+
vectors_config=models.VectorParams(size=vector_size,
|
39 |
+
distance=distance,
|
40 |
+
)
|
41 |
+
)
|
pdf_loader.py
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import os
|
3 |
+
import uuid
|
4 |
+
import datetime
|
5 |
+
from qdrant_client import QdrantClient, models
|
6 |
+
from langchain_core.load import dumpd, dumps, load, loads
|
7 |
+
from langchain_community.document_loaders import AzureAIDocumentIntelligenceLoader
|
8 |
+
from langchain.text_splitter import NLTKTextSplitter, RecursiveCharacterTextSplitter
|
9 |
+
from langchain_qdrant import Qdrant
|
10 |
+
|
11 |
+
class PDFLoader:
|
12 |
+
|
13 |
+
def __init__(self):
|
14 |
+
pass
|
15 |
+
|
16 |
+
def pdf_reader(self, path):
|
17 |
+
key = None # change it with your own loader key
|
18 |
+
endpoint = None # change it with your own loader endpoint
|
19 |
+
analysis_features = ["ocrHighResolution"]
|
20 |
+
# PDF Loader
|
21 |
+
AzurePDFLoader = AzureAIDocumentIntelligenceLoader(
|
22 |
+
api_endpoint=endpoint,
|
23 |
+
api_key=key,
|
24 |
+
file_path=path,
|
25 |
+
api_model="prebuilt-layout",
|
26 |
+
mode="page",
|
27 |
+
analysis_features=analysis_features
|
28 |
+
)
|
29 |
+
documents = AzurePDFLoader.load()
|
30 |
+
return documents
|
31 |
+
|
32 |
+
def save_raw_documents(self, path, name, documents):
|
33 |
+
|
34 |
+
log_file={"documents": dumpd(documents)}
|
35 |
+
log_file_name = os.path.join(path, name)
|
36 |
+
|
37 |
+
with open(log_file_name, 'w') as output_file:
|
38 |
+
print(json.dumps(log_file, indent=2), file=output_file)
|
39 |
+
|
40 |
+
def load_raw_documents(self, path, name):
|
41 |
+
|
42 |
+
log_file_name = os.path.join(path, name)
|
43 |
+
|
44 |
+
with open(log_file_name, 'rb') as output_file:
|
45 |
+
log_file= json.load(output_file)
|
46 |
+
|
47 |
+
documents = load(log_file["documents"])
|
48 |
+
return documents
|
49 |
+
|
50 |
+
def recursive_splitter(self, documents, chunk_size=1024, chunk_overlap=256):
|
51 |
+
|
52 |
+
# Splitter
|
53 |
+
mySplitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size,
|
54 |
+
chunk_overlap=chunk_overlap,
|
55 |
+
add_start_index=False)
|
56 |
+
chunks = mySplitter.split_documents(documents)
|
57 |
+
return chunks
|
58 |
+
|
59 |
+
def generate_vectors(self, chunks, embeddings, source_name):
|
60 |
+
vectors = []
|
61 |
+
metadatas = []
|
62 |
+
page_contents = []
|
63 |
+
for chunk in chunks:
|
64 |
+
page_contents.append(chunk.page_content)
|
65 |
+
|
66 |
+
vector = embeddings.embed_documents([chunk.page_content])
|
67 |
+
vectors.append(vector)
|
68 |
+
|
69 |
+
meta = chunk.metadata
|
70 |
+
meta["source"] = source_name
|
71 |
+
metadatas.append(meta)
|
72 |
+
|
73 |
+
return page_contents, vectors, metadatas
|
74 |
+
|
75 |
+
def save_to_database(self, chunks, embeddings, collection_name):
|
76 |
+
|
77 |
+
qdrant = Qdrant.from_documents(
|
78 |
+
chunks,
|
79 |
+
embeddings,
|
80 |
+
url=os.getenv('qdrant_url'),
|
81 |
+
api_key=os.getenv('qdrant_api'),
|
82 |
+
prefer_grpc=True,
|
83 |
+
collection_name=collection_name)
|
84 |
+
|
85 |
+
def load_from_database(self, embeddings, collection_name):
|
86 |
+
|
87 |
+
db = Qdrant.from_existing_collection(
|
88 |
+
embedding=embeddings,
|
89 |
+
url=os.getenv('qdrant_url'),
|
90 |
+
api_key=os.getenv('qdrant_api'),
|
91 |
+
collection_name=collection_name)
|
92 |
+
|
93 |
+
return db
|
94 |
+
|
95 |
+
def save_manuals(self, client, collection_name, car_id, model_year, vectors, metadatas, page_contents):
|
96 |
+
|
97 |
+
client.upsert(
|
98 |
+
collection_name=collection_name,
|
99 |
+
points=[
|
100 |
+
models.PointStruct(
|
101 |
+
id=uuid.uuid4().hex,
|
102 |
+
payload={"metadata":metadatas[idx],
|
103 |
+
"page_content": page_contents[idx],
|
104 |
+
"car_id": car_id,
|
105 |
+
"model_year": model_year,
|
106 |
+
"create_date": datetime.datetime.now().isoformat()},
|
107 |
+
vector=vector[0]
|
108 |
+
)
|
109 |
+
for idx, vector in enumerate(vectors)
|
110 |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
anyio==4.4.0
|
8 |
+
asttokens==2.4.1
|
9 |
+
attrs==24.2.0
|
10 |
+
azure-ai-documentintelligence==1.0.0b4
|
11 |
+
azure-ai-ml==1.19.0
|
12 |
+
azure-common==1.1.28
|
13 |
+
azure-core==1.30.2
|
14 |
+
azure-identity==1.17.1
|
15 |
+
azure-mgmt-core==1.4.0
|
16 |
+
azure-storage-blob==12.22.0
|
17 |
+
azure-storage-file-datalake==12.16.0
|
18 |
+
azure-storage-file-share==12.17.0
|
19 |
+
backcall==0.2.0
|
20 |
+
beautifulsoup4==4.12.3
|
21 |
+
bleach==6.1.0
|
22 |
+
boto3==1.35.15
|
23 |
+
botocore==1.35.15
|
24 |
+
cachetools==5.5.0
|
25 |
+
certifi==2024.8.30
|
26 |
+
cffi==1.17.1
|
27 |
+
charset-normalizer==3.3.2
|
28 |
+
click==8.1.7
|
29 |
+
cohere==5.9.1
|
30 |
+
colorama==0.4.6
|
31 |
+
colorlog==6.8.2
|
32 |
+
comm==0.2.2
|
33 |
+
contourpy==1.3.0
|
34 |
+
cryptography==43.0.1
|
35 |
+
cycler==0.12.1
|
36 |
+
dataclasses-json==0.6.7
|
37 |
+
debugpy==1.8.5
|
38 |
+
decorator==5.1.1
|
39 |
+
defusedxml==0.7.1
|
40 |
+
distro==1.9.0
|
41 |
+
docopt==0.6.2
|
42 |
+
et-xmlfile==1.1.0
|
43 |
+
executing==2.1.0
|
44 |
+
fastapi==0.114.2
|
45 |
+
fastavro==1.9.7
|
46 |
+
fastjsonschema==2.20.0
|
47 |
+
ffmpy==0.4.0
|
48 |
+
filelock==3.13.1
|
49 |
+
fonttools==4.53.1
|
50 |
+
frozenlist==1.4.1
|
51 |
+
fsspec==2024.2.0
|
52 |
+
google-api-core==2.19.2
|
53 |
+
google-api-python-client==2.145.0
|
54 |
+
google-auth==2.34.0
|
55 |
+
google-auth-httplib2==0.2.0
|
56 |
+
googleapis-common-protos==1.65.0
|
57 |
+
gradio==4.44.0
|
58 |
+
gradio_client==1.3.0
|
59 |
+
greenlet==3.0.3
|
60 |
+
grpcio==1.66.1
|
61 |
+
grpcio-tools==1.66.1
|
62 |
+
h11==0.14.0
|
63 |
+
h2==4.1.0
|
64 |
+
hpack==4.0.0
|
65 |
+
httpcore==1.0.5
|
66 |
+
httplib2==0.22.0
|
67 |
+
httpx==0.27.2
|
68 |
+
httpx-sse==0.4.0
|
69 |
+
huggingface-hub==0.24.6
|
70 |
+
hyperframe==6.0.1
|
71 |
+
idna==3.8
|
72 |
+
importlib_resources==6.4.5
|
73 |
+
ipykernel==6.29.5
|
74 |
+
ipython==8.12.3
|
75 |
+
ipywidgets==8.1.5
|
76 |
+
isodate==0.6.1
|
77 |
+
jedi==0.19.1
|
78 |
+
Jinja2==3.1.4
|
79 |
+
jiter==0.5.0
|
80 |
+
jmespath==1.0.1
|
81 |
+
joblib==1.4.2
|
82 |
+
jsonpatch==1.33
|
83 |
+
jsonpointer==3.0.0
|
84 |
+
jsonschema==4.23.0
|
85 |
+
jsonschema-specifications==2023.12.1
|
86 |
+
jupyter_client==8.6.2
|
87 |
+
jupyter_core==5.7.2
|
88 |
+
jupyterlab_pygments==0.3.0
|
89 |
+
jupyterlab_widgets==3.0.13
|
90 |
+
kiwisolver==1.4.7
|
91 |
+
langchain==0.2.16
|
92 |
+
langchain-community==0.2.16
|
93 |
+
langchain-core==0.2.38
|
94 |
+
langchain-huggingface==0.0.3
|
95 |
+
langchain-openai==0.1.23
|
96 |
+
langchain-qdrant==0.1.3
|
97 |
+
langchain-text-splitters==0.2.4
|
98 |
+
langgraph==0.2.19
|
99 |
+
langgraph-checkpoint==1.0.9
|
100 |
+
langsmith==0.1.117
|
101 |
+
markdown-it-py==3.0.0
|
102 |
+
MarkupSafe==2.1.5
|
103 |
+
marshmallow==3.22.0
|
104 |
+
matplotlib==3.9.2
|
105 |
+
matplotlib-inline==0.1.7
|
106 |
+
mdurl==0.1.2
|
107 |
+
mistune==3.0.2
|
108 |
+
mpmath==1.3.0
|
109 |
+
msal==1.31.0
|
110 |
+
msal-extensions==1.2.0
|
111 |
+
msrest==0.7.1
|
112 |
+
multidict==6.1.0
|
113 |
+
mypy-extensions==1.0.0
|
114 |
+
nbclient==0.10.0
|
115 |
+
nbconvert==7.16.4
|
116 |
+
nbformat==5.10.4
|
117 |
+
nest-asyncio==1.6.0
|
118 |
+
networkx==3.2.1
|
119 |
+
numpy==1.26.3
|
120 |
+
oauthlib==3.2.2
|
121 |
+
openai==1.44.1
|
122 |
+
opencensus==0.11.4
|
123 |
+
opencensus-context==0.1.3
|
124 |
+
opencensus-ext-azure==1.1.13
|
125 |
+
opencensus-ext-logging==0.1.1
|
126 |
+
openpyxl==3.1.5
|
127 |
+
orjson==3.10.7
|
128 |
+
packaging==24.1
|
129 |
+
pandas==2.2.2
|
130 |
+
pandocfilters==1.5.1
|
131 |
+
parameterized==0.9.0
|
132 |
+
parso==0.8.4
|
133 |
+
pexpect==4.9.0
|
134 |
+
pickleshare==0.7.5
|
135 |
+
pillow==10.2.0
|
136 |
+
pipreqs==0.5.0
|
137 |
+
platformdirs==4.3.2
|
138 |
+
portalocker==2.10.1
|
139 |
+
prompt_toolkit==3.0.47
|
140 |
+
proto-plus==1.24.0
|
141 |
+
protobuf==5.28.0
|
142 |
+
psutil==6.0.0
|
143 |
+
ptyprocess==0.7.0
|
144 |
+
pure_eval==0.2.3
|
145 |
+
pyasn1==0.6.0
|
146 |
+
pyasn1_modules==0.4.0
|
147 |
+
pycparser==2.22
|
148 |
+
pydantic==2.9.1
|
149 |
+
pydantic_core==2.23.3
|
150 |
+
pydash==8.0.3
|
151 |
+
pydub==0.25.1
|
152 |
+
Pygments==2.18.0
|
153 |
+
PyJWT==2.9.0
|
154 |
+
pyparsing==3.1.4
|
155 |
+
python-dateutil==2.9.0.post0
|
156 |
+
python-multipart==0.0.9
|
157 |
+
pytz==2024.1
|
158 |
+
PyYAML==6.0.2
|
159 |
+
pyzmq==26.2.0
|
160 |
+
qdrant-client==1.11.1
|
161 |
+
referencing==0.35.1
|
162 |
+
regex==2024.7.24
|
163 |
+
requests==2.32.3
|
164 |
+
requests-mock==1.12.1
|
165 |
+
requests-oauthlib==2.0.0
|
166 |
+
rich==13.8.1
|
167 |
+
rpds-py==0.20.0
|
168 |
+
rsa==4.9
|
169 |
+
ruff==0.6.5
|
170 |
+
s3transfer==0.10.2
|
171 |
+
safetensors==0.4.5
|
172 |
+
scikit-learn==1.5.1
|
173 |
+
scipy==1.14.1
|
174 |
+
semantic-router==0.0.65
|
175 |
+
semantic-version==2.10.0
|
176 |
+
sentence-transformers==3.0.1
|
177 |
+
shellingham==1.5.4
|
178 |
+
six==1.16.0
|
179 |
+
sniffio==1.3.1
|
180 |
+
soupsieve==2.6
|
181 |
+
SQLAlchemy==2.0.34
|
182 |
+
stack-data==0.6.3
|
183 |
+
starlette==0.38.5
|
184 |
+
strictyaml==1.7.3
|
185 |
+
sympy==1.12
|
186 |
+
tenacity==8.5.0
|
187 |
+
threadpoolctl==3.5.0
|
188 |
+
tiktoken==0.7.0
|
189 |
+
tinycss2==1.3.0
|
190 |
+
tokenizers==0.19.1
|
191 |
+
tomlkit==0.12.0
|
192 |
+
tornado==6.4.1
|
193 |
+
tqdm==4.66.5
|
194 |
+
traitlets==5.14.3
|
195 |
+
transformers==4.44.2
|
196 |
+
triton==2.3.0
|
197 |
+
typer==0.12.5
|
198 |
+
types-requests==2.32.0.20240907
|
199 |
+
typing-inspect==0.9.0
|
200 |
+
typing_extensions==4.12.2
|
201 |
+
tzdata==2024.1
|
202 |
+
uritemplate==4.1.1
|
203 |
+
urllib3==2.2.2
|
204 |
+
uvicorn==0.30.6
|
205 |
+
v==1
|
206 |
+
wcwidth==0.2.13
|
207 |
+
webencodings==0.5.1
|
208 |
+
websockets==12.0
|
209 |
+
widgetsnbextension==4.0.13
|
210 |
+
yarg==0.1.9
|
211 |
+
yarl==1.11.1
|
wrappers.py
ADDED
@@ -0,0 +1,549 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import openai
|
3 |
+
from langchain_openai import AzureChatOpenAI
|
4 |
+
from langchain.prompts import ChatPromptTemplate, PromptTemplate
|
5 |
+
from qdrant_client.http import models as rest
|
6 |
+
from qdrant_client import QdrantClient, models
|
7 |
+
from langchain_core.pydantic_v1 import BaseModel, Field
|
8 |
+
from langchain.memory import ConversationBufferMemory
|
9 |
+
from langchain.chains import LLMChain
|
10 |
+
from langchain_community.utilities import GoogleSearchAPIWrapper
|
11 |
+
from langchain_core.tools import Tool
|
12 |
+
from typing_extensions import TypedDict
|
13 |
+
from typing import List
|
14 |
+
from langchain.schema import Document
|
15 |
+
from pprint import pprint
|
16 |
+
from langgraph.graph import END, StateGraph
|
17 |
+
|
18 |
+
from db_operations import DatabaseOperations
|
19 |
+
# from initialize_db import QdrantClientInitializer
|
20 |
+
from embedding_loader import *
|
21 |
+
|
22 |
+
class Wrappers:
|
23 |
+
|
24 |
+
def __init__(self, collection_name_manual, client, embeddings, LLM, db, CAR_ID, memory):
|
25 |
+
self.collection_name_manual = collection_name_manual
|
26 |
+
self.embeddings = embeddings
|
27 |
+
self.client = client
|
28 |
+
self.myLLM = LLM
|
29 |
+
self.db = db
|
30 |
+
self.CAR_ID = CAR_ID
|
31 |
+
self.memory = memory
|
32 |
+
# self.memory = ConversationBufferMemory(memory_key="history",
|
33 |
+
# input_key="question")
|
34 |
+
def translater(self):
|
35 |
+
template = """You are a Turkish-English translator. Translate the input to English considering vehicle/car domain terms.
|
36 |
+
|
37 |
+
Input: {question}
|
38 |
+
|
39 |
+
Answer: """
|
40 |
+
|
41 |
+
PROMPT = PromptTemplate.from_template(template) # -----------------> ChatPromptTemplate kullanmak daha sağlıklı
|
42 |
+
|
43 |
+
translate_chain = LLMChain(llm=self.myLLM, prompt=PROMPT)
|
44 |
+
# translate_chain = PROMPT | self.myLLM
|
45 |
+
|
46 |
+
return translate_chain
|
47 |
+
|
48 |
+
def retriever(self):
|
49 |
+
|
50 |
+
retriever = self.db.as_retriever(search_kwargs={'k': 4}, filter=rest.Filter(
|
51 |
+
must=[
|
52 |
+
models.FieldCondition(key="car_id", match=models.MatchValue(value=self.CAR_ID))
|
53 |
+
]
|
54 |
+
))
|
55 |
+
|
56 |
+
return retriever
|
57 |
+
|
58 |
+
def grade_documents(self):
|
59 |
+
class GradeDocuments(BaseModel):
|
60 |
+
"""Binary score for relevance check on retrieved documents."""
|
61 |
+
|
62 |
+
binary_score: str = Field(description="Documents are relevant to the question, 'yes' or 'no'")
|
63 |
+
|
64 |
+
# LLM with function call
|
65 |
+
structured_llm_grader_docs = self.myLLM.with_structured_output(GradeDocuments)
|
66 |
+
|
67 |
+
# Prompt
|
68 |
+
system = """You are a grader assessing relevance of a retrieved document to a user question. \n
|
69 |
+
Consider the following when making your assessment: \n
|
70 |
+
- Does the document directly address the user's question? \n
|
71 |
+
- Does it provide information or context that is pertinent to the question? \n
|
72 |
+
- Does it discuss relevant risks, benefits, recommendations, or considerations related to the question? \n
|
73 |
+
If the document contains keyword(s) or semantic meaning related or partially related to the question, grade it as relevant. \n
|
74 |
+
Give a binary score 'yes' or 'no' score to indicate whether the document is relevant to the question."""
|
75 |
+
|
76 |
+
grade_prompt = ChatPromptTemplate.from_messages(
|
77 |
+
[
|
78 |
+
("system", system),
|
79 |
+
("human", "Retrieved document: \n\n {document} \n\n User question: {question}"),
|
80 |
+
]
|
81 |
+
)
|
82 |
+
|
83 |
+
retrieval_grader_relevance = grade_prompt | structured_llm_grader_docs
|
84 |
+
|
85 |
+
return retrieval_grader_relevance
|
86 |
+
|
87 |
+
def lead_check(self):
|
88 |
+
|
89 |
+
class LeadCheck(BaseModel):
|
90 |
+
"""Binary score for service relevance check on question."""
|
91 |
+
|
92 |
+
binary_score: str = Field(description="Services are relevant to the question, 'yes' or 'no'")
|
93 |
+
|
94 |
+
# LLM with function call
|
95 |
+
structured_llm_grader_service = self.myLLM.with_structured_output(LeadCheck)
|
96 |
+
|
97 |
+
# Prompt
|
98 |
+
system = """You are a grader assessing relevance of services to a user question. \n
|
99 |
+
If the provided services related or partially related to the question, grade it as relevant. \n
|
100 |
+
Give a binary score 'yes' or 'no' score to indicate whether the document is relevant to the question."""
|
101 |
+
|
102 |
+
lead_prompt = ChatPromptTemplate.from_messages(
|
103 |
+
[
|
104 |
+
("system", system),
|
105 |
+
("human", "Provided services: \n\n {hizmet_listesi} \n\n User question: {question}"),
|
106 |
+
]
|
107 |
+
)
|
108 |
+
|
109 |
+
service_grader_relevance = lead_prompt | structured_llm_grader_service
|
110 |
+
|
111 |
+
return service_grader_relevance
|
112 |
+
|
113 |
+
def main_prompt(self):
|
114 |
+
|
115 |
+
prompt = ChatPromptTemplate.from_template(
|
116 |
+
"""
|
117 |
+
You are an expert assistant named ARVI focused solely on car troubles and vehicle information.
|
118 |
+
Your goal is to provide accurate, helpful, and clear answers to any questions related to car issues, maintenance, repairs, specifications, and other vehicle-related topics.
|
119 |
+
|
120 |
+
You are also designed to respond politely and appropriately to basic courteous interactions. Here are the guidelines:
|
121 |
+
|
122 |
+
1. Car Troubles and Vehicle Information:
|
123 |
+
|
124 |
+
- Always answer questions regarding car issues, diagnostics, repairs, maintenance, and vehicle specifications.
|
125 |
+
- Provide detailed and practical advice that can help users resolve their car troubles or understand more about their vehicles based on context.
|
126 |
+
|
127 |
+
2. References:
|
128 |
+
|
129 |
+
- When answering a question, if you use specific information from the context, add the context's metadata (source and page) as references at the end of your response.
|
130 |
+
- Do not repeat same reference.
|
131 |
+
- Never include irrelevant context.
|
132 |
+
|
133 |
+
The first information you have is the relevant text that is automatically extracted from the manual or through the web search. \n
|
134 |
+
Context: {context} \n
|
135 |
+
|
136 |
+
History: {history} \n
|
137 |
+
|
138 |
+
Based on all the information provided, answer the following question briefly: \n
|
139 |
+
Question: {question} \n
|
140 |
+
|
141 |
+
Lead: {lead} \n
|
142 |
+
Do not use your prior knowledge! \n
|
143 |
+
If the question is too general, ask for specific information. \n
|
144 |
+
Answer: Answer in Turkish\n
|
145 |
+
References: 1: \n
|
146 |
+
2: \n
|
147 |
+
...
|
148 |
+
"""
|
149 |
+
)
|
150 |
+
|
151 |
+
# Chain
|
152 |
+
|
153 |
+
# rag_chain = prompt | myLLM | StrOutputParser()
|
154 |
+
rag_chain =LLMChain(llm=self.myLLM, prompt=prompt, memory=self.memory)
|
155 |
+
|
156 |
+
return rag_chain
|
157 |
+
|
158 |
+
def hallucination_grader(self):
|
159 |
+
class GradeHallucinations(BaseModel):
|
160 |
+
"""Binary score for hallucination present in generation answer."""
|
161 |
+
|
162 |
+
binary_score: str = Field(description="Don't consider calling external APIs for additional information. Answer is supported by the facts, 'yes' or 'no'.")
|
163 |
+
|
164 |
+
# LLM with function call
|
165 |
+
structured_llm_grader_hallucination = self.myLLM.with_structured_output(GradeHallucinations)
|
166 |
+
|
167 |
+
# Prompt
|
168 |
+
system = """You are a grader assessing whether an LLM generation is supported by a set of retrieved facts. \n
|
169 |
+
If the LLM generation is greetings sentences or say 'cannot answer the question", always consider it is a yes. \n
|
170 |
+
For others, restrict yourself to give a binary score, either 'yes' or 'no'. If the answer is supported or partially supported by the set of facts, consider it a yes. \n
|
171 |
+
Don't consider calling external APIs or prior knowledge for additional information as consistent with the facts."""
|
172 |
+
|
173 |
+
hallucination_prompt = ChatPromptTemplate.from_messages(
|
174 |
+
[
|
175 |
+
("system", system),
|
176 |
+
("human", "Set of facts: \n\n {documents} \n\n LLM generation: {generation}"),
|
177 |
+
]
|
178 |
+
)
|
179 |
+
|
180 |
+
hallucination_grader = hallucination_prompt | structured_llm_grader_hallucination
|
181 |
+
|
182 |
+
return hallucination_grader
|
183 |
+
|
184 |
+
def answer_grader(self):
|
185 |
+
class GradeAnswer(BaseModel):
|
186 |
+
"""Binary score to assess answer addresses question."""
|
187 |
+
|
188 |
+
binary_score: str = Field(description="Answer addresses the question, 'yes' or 'no'")
|
189 |
+
|
190 |
+
# LLM with function call
|
191 |
+
structured_llm_grader_answer = self.myLLM.with_structured_output(GradeAnswer)
|
192 |
+
|
193 |
+
# Prompt
|
194 |
+
system = """You are a grader assessing whether an answer addresses / resolves a question \n
|
195 |
+
Give a binary score 'yes' or 'no'. Yes' means that the answer resolves the question. \n
|
196 |
+
If the LLM generation is greetings sentences, always consider it is a yes.\n
|
197 |
+
If the LLM generation said that 'I cannot answer that question", consider it is a yes."""
|
198 |
+
|
199 |
+
answer_prompt = ChatPromptTemplate.from_messages(
|
200 |
+
[
|
201 |
+
("system", system),
|
202 |
+
("human", "User question: \n\n {question} \n\n LLM generation: {generation}"),
|
203 |
+
]
|
204 |
+
)
|
205 |
+
|
206 |
+
answer_grader = answer_prompt | structured_llm_grader_answer
|
207 |
+
|
208 |
+
return answer_grader
|
209 |
+
|
210 |
+
|
211 |
+
def web_search(self):
|
212 |
+
os.environ["GOOGLE_CSE_ID"] = os.getenv('google_search_id')
|
213 |
+
os.environ["GOOGLE_API_KEY"] = os.getenv('google_search_api')
|
214 |
+
|
215 |
+
search = GoogleSearchAPIWrapper()
|
216 |
+
|
217 |
+
def top3_results(query):
|
218 |
+
return search.results(query, 3)
|
219 |
+
|
220 |
+
web_search_tool = Tool(
|
221 |
+
name="google_search",
|
222 |
+
description="Search Google for recent results.",
|
223 |
+
func=top3_results,
|
224 |
+
)
|
225 |
+
|
226 |
+
return web_search_tool
|
227 |
+
|
228 |
+
|
229 |
+
def lagchain_graph(self):
|
230 |
+
|
231 |
+
class GraphState(TypedDict):
|
232 |
+
"""
|
233 |
+
Represents the state of our graph.
|
234 |
+
|
235 |
+
Attributes:
|
236 |
+
question: question
|
237 |
+
generation: LLM generation
|
238 |
+
web_search: whether to add search
|
239 |
+
documents: list of documents
|
240 |
+
"""
|
241 |
+
question : str
|
242 |
+
generation : str
|
243 |
+
web_search : str
|
244 |
+
documents : List[str]
|
245 |
+
iter_halucination: int
|
246 |
+
lead: str
|
247 |
+
|
248 |
+
### Nodes
|
249 |
+
|
250 |
+
def retrieve(state):
|
251 |
+
"""
|
252 |
+
Retrieve documents from vectorstore
|
253 |
+
|
254 |
+
Args:
|
255 |
+
state (dict): The current graph state
|
256 |
+
|
257 |
+
Returns:
|
258 |
+
state (dict): New key added to state, documents, that contains retrieved documents
|
259 |
+
"""
|
260 |
+
print("---RETRIEVE from Vector Store DB---")
|
261 |
+
question = state["question"]
|
262 |
+
# Retrieval
|
263 |
+
documents = self.retriever().invoke(question)
|
264 |
+
return {"documents": documents, "question": question}
|
265 |
+
|
266 |
+
def generate(state):
|
267 |
+
"""
|
268 |
+
Generate answer using RAG on retrieved documents
|
269 |
+
|
270 |
+
Args:
|
271 |
+
state (dict): The current graph state
|
272 |
+
|
273 |
+
Returns:
|
274 |
+
state (dict): New key added to state, generation, that contains LLM generation
|
275 |
+
"""
|
276 |
+
print("---GENERATE Answer---")
|
277 |
+
question = state["question"]
|
278 |
+
documents = state["documents"]
|
279 |
+
lead = state["lead"]
|
280 |
+
|
281 |
+
# RAG generation
|
282 |
+
generation = self.main_prompt().invoke({"context": documents, "question": question, "history": self.memory, "lead": lead})
|
283 |
+
return {"documents": documents, "question": question, "generation": generation}
|
284 |
+
|
285 |
+
def history_router(state):
|
286 |
+
|
287 |
+
question = state["question"]
|
288 |
+
history_log = DatabaseOperations.question_history_search(client=self.client,
|
289 |
+
collection_name=self.collection_name_manual,
|
290 |
+
car_id=self.CAR_ID,
|
291 |
+
question=question, embeddings=self.embeddings)
|
292 |
+
|
293 |
+
if len(history_log) > 0:
|
294 |
+
print("---ANSWER FROM HISTORY---")
|
295 |
+
return 'question history'
|
296 |
+
|
297 |
+
else:
|
298 |
+
print("---ANSWER FROM MANUAL---")
|
299 |
+
return 'user manual'
|
300 |
+
|
301 |
+
def generate_from_history(state):
|
302 |
+
# sohbet devamlılığı için history'den konuşmayı memory'e ekle
|
303 |
+
question = state["question"]
|
304 |
+
history_log = DatabaseOperations.question_history_search(client=self.client,
|
305 |
+
collection_name=self.collection_name_manual,
|
306 |
+
car_id=self.CAR_ID,
|
307 |
+
question=question, embeddings=self.embeddings)
|
308 |
+
return {"generation": {"text": history_log[0].payload["answer"]}}
|
309 |
+
|
310 |
+
def grade_documents(state):
|
311 |
+
"""
|
312 |
+
Determines whether the retrieved documents are relevant to the question
|
313 |
+
If any document is not relevant, we will set a flag to run web search
|
314 |
+
|
315 |
+
Args:
|
316 |
+
state (dict): The current graph state
|
317 |
+
|
318 |
+
Returns:
|
319 |
+
state (dict): Filtered out irrelevant documents and updated web_search state
|
320 |
+
"""
|
321 |
+
|
322 |
+
print("---CHECK DOCUMENT RELEVANCE TO QUESTION---")
|
323 |
+
question = state["question"]
|
324 |
+
documents = state["documents"]
|
325 |
+
# Score each doc
|
326 |
+
filtered_docs = []
|
327 |
+
web_search = "No"
|
328 |
+
for d in documents:
|
329 |
+
score = self.grade_documents().invoke({"question": question, "document": d.page_content})
|
330 |
+
grade = score.binary_score
|
331 |
+
# Document relevant
|
332 |
+
if grade.lower() == "yes":
|
333 |
+
print("---GRADE: DOCUMENT RELEVANT---")
|
334 |
+
filtered_docs.append(d)
|
335 |
+
# Document not relevant
|
336 |
+
else:
|
337 |
+
print("---GRADE: DOCUMENT NOT RELEVANT---")
|
338 |
+
# We do not include the document in filtered_docs
|
339 |
+
# We set a flag to indicate that we want to run web search
|
340 |
+
# web_search = "Yes"
|
341 |
+
continue
|
342 |
+
if filtered_docs == []:
|
343 |
+
web_search = "Yes"
|
344 |
+
|
345 |
+
return {"documents": filtered_docs, "question": question, "web_search": web_search}
|
346 |
+
|
347 |
+
def grade_service(state):
|
348 |
+
hizmet_listesi = hizmet_listesi = {"Bakım": """Check-Up, Periyodik Bakım, Aks Değişimi, Amortisör Değişimi, Amortisör Takozu Değişimi, Baskı Balata Değişimi, Benzin Filtresi Değişimi,
|
349 |
+
Debriyaj Balatası Değişimi, Direksiyon Kutusu Değişimi, Dizel Araç Bakımı, Egzoz Muayenesi, Fren Kaliperi Değişimi, El Freni Teli Değişimi,
|
350 |
+
Fren Balatası Değişimi, Fren Disk Değişimi, Hava Filtresi Değişimi, Helezon Yay Değişimi, Kampana Fren Balatası Değişimi,
|
351 |
+
Kızdırma Bujisi Değişimi, Rot Başı Değişimi, Rot Kolu Değişimi, Rotil Değişimi, Silecek Değişimi, Süspansiyon, Triger Kayışı Değişimi,
|
352 |
+
Triger Zinciri Değişimi, V Kayışı Değişimi, Yağ Filtresi Değişimi, Yakıt Filtresi Değişimi,""",
|
353 |
+
"Yağ ve Sıvılar": """Şanzıman Yağı Değişimi, Dizel Araçlarda Yağ Değişimi, Yağ Değişimi, Fren Hidrolik Değişimi, Antifriz Değişimi,""",
|
354 |
+
"Akü": """Akü Şarj Etme, Akü Değişimi""",
|
355 |
+
"Klima": """Oto Klima Kompresörü Tamiri, Oto Klima Tamiri, Araç Klima Temizliği, Araç Klima Bakteri Temizliği, Klima Gazı Dolumu, Klima Dezenfeksiyonu, Polen Filtresi Değişimi""",
|
356 |
+
"Elektrik": """Servis Uyarı Lambası Sıfırlama,Buji Kablosu Değişimi, Arıza Tespit, Göstergelerin Kontrolü, Far Ayarı ve Ampul Değişimi, Buji Değişimi, Sigorta Değişimi""",
|
357 |
+
"Lastik/ Jant": """Lastik Jant Satış, Lastik Değişimi, Balans Ayarı, Rot Ayarı, Rotasyon, Lastik Tamiri, Hava Kontrolü, Nitrojen Dolumu, Supap Değişimi, Lastik Saklama (Lastik Oteli), Jant Sökme Takma,""",
|
358 |
+
"Diğer": """Cam Tamiri""",
|
359 |
+
"Hibrit Araçlar": "Hibrit Araç Aküsü"}
|
360 |
+
|
361 |
+
print("---CHECK SERVICE RELEVANCE TO QUESTION---")
|
362 |
+
question = state["question"]
|
363 |
+
score = self.lead_check().invoke({"hizmet_listesi": hizmet_listesi, "question": question})
|
364 |
+
grade = score.binary_score
|
365 |
+
lead = 'Always use "XXX Servisi" only instead of "Yetkili Servis" or "Yetkili Bayi".'
|
366 |
+
|
367 |
+
# Document relevant
|
368 |
+
if grade.lower() == "yes":
|
369 |
+
print("---GRADE: SERVICE RELEVANT---")
|
370 |
+
lead = 'Always use "Otobakım Servisi" only instead of "Toyota Servisi", "Yetkili Servis" or "Toyota Bayisi". At the end of the answer, offer the user to visit Otobakım shops for quick and affordable solutions, starting with the phrase: "If you are not sure how to proceed.".'
|
371 |
+
# Document not relevant
|
372 |
+
else:
|
373 |
+
print("---GRADE: SERVICE NOT RELEVANT---")
|
374 |
+
|
375 |
+
return {"lead": lead}
|
376 |
+
|
377 |
+
def web_search(state):
|
378 |
+
"""
|
379 |
+
Web search based based on the question
|
380 |
+
|
381 |
+
Args:
|
382 |
+
state (dict): The current graph state
|
383 |
+
|
384 |
+
Returns:
|
385 |
+
state (dict): Appended web results to documents
|
386 |
+
"""
|
387 |
+
|
388 |
+
print("---WEB SEARCH. Append to vector store db---")
|
389 |
+
question = state["question"]
|
390 |
+
documents = state["documents"]
|
391 |
+
translated_question = self.translater().invoke({"question": question})["text"]
|
392 |
+
|
393 |
+
# Web search
|
394 |
+
docs = self.web_search().invoke({"query": translated_question})
|
395 |
+
# web_results = [d["snippet"] for d in docs]
|
396 |
+
# source = [d["link"] for d in docs]
|
397 |
+
# web_results = Document(page_content = web_results, metadata={'source': source})
|
398 |
+
web_results = [Document(page_content=d["snippet"], metadata={'source': d["link"]}) for d in docs]
|
399 |
+
# if documents is not None:
|
400 |
+
# documents.append(web_results)
|
401 |
+
# else:
|
402 |
+
# documents = [web_results]
|
403 |
+
if documents == []:
|
404 |
+
documents = web_results
|
405 |
+
print(documents)
|
406 |
+
return {"documents": documents, "question": question}
|
407 |
+
|
408 |
+
|
409 |
+
def decide_to_generate(state):
|
410 |
+
"""
|
411 |
+
Determines whether to generate an answer, or add web search
|
412 |
+
|
413 |
+
Args:
|
414 |
+
state (dict): The current graph state
|
415 |
+
|
416 |
+
Returns:
|
417 |
+
str: Binary decision for next node to call
|
418 |
+
"""
|
419 |
+
|
420 |
+
print("---ASSESS GRADED DOCUMENTS---")
|
421 |
+
question = state["question"]
|
422 |
+
web_search = state["web_search"]
|
423 |
+
filtered_documents = state["documents"]
|
424 |
+
|
425 |
+
if web_search == "Yes":
|
426 |
+
# All documents have been filtered check_relevance
|
427 |
+
# We will re-generate a new query
|
428 |
+
print("---DECISION: ALL DOCUMENTS ARE NOT RELEVANT TO QUESTION, INCLUDE WEB SEARCH---")
|
429 |
+
return "websearch"
|
430 |
+
else:
|
431 |
+
# We have relevant documents, so generate answer
|
432 |
+
print("---DECISION: GENERATE---")
|
433 |
+
return "generate"
|
434 |
+
|
435 |
+
def hallucination_router(state):
|
436 |
+
print("---QUESTION CHANGING---")
|
437 |
+
question = 'You are hallucinating! Please change your answer by sticking to the context.'
|
438 |
+
iter_halucination = state["iter_halucination"]
|
439 |
+
iter_halucination += 1
|
440 |
+
return {'question': question, "iter_halucination": iter_halucination}
|
441 |
+
|
442 |
+
def grade_generation_v_documents_and_question(state):
|
443 |
+
"""
|
444 |
+
Determines whether the generation is grounded in the document and answers question
|
445 |
+
|
446 |
+
Args:
|
447 |
+
state (dict): The current graph state
|
448 |
+
|
449 |
+
Returns:
|
450 |
+
str: Decision for next node to call
|
451 |
+
"""
|
452 |
+
print("---CHECK HALLUCINATIONS---")
|
453 |
+
question = state["question"]
|
454 |
+
documents = state["documents"]
|
455 |
+
generation = state["generation"]
|
456 |
+
iter_halucination = state["iter_halucination"]
|
457 |
+
# print("Generation:", generation)
|
458 |
+
score = self.hallucination_grader().invoke({"documents": documents, "generation": generation})
|
459 |
+
grade = score.binary_score
|
460 |
+
# Check hallucination
|
461 |
+
if grade == "yes":
|
462 |
+
print("---DECISION: GENERATION IS GROUNDED IN DOCUMENTS---")
|
463 |
+
# Check question-answering
|
464 |
+
print("---GRADE GENERATION vs QUESTION---")
|
465 |
+
score = self.answer_grader().invoke({"question": question,"generation": generation})
|
466 |
+
grade = score.binary_score
|
467 |
+
if grade == "yes":
|
468 |
+
print("---DECISION: GENERATION ADDRESSES QUESTION---")
|
469 |
+
return "useful"
|
470 |
+
else:
|
471 |
+
print("---DECISION: GENERATION DOES NOT ADDRESS QUESTION---")
|
472 |
+
return "not useful"
|
473 |
+
else:
|
474 |
+
if iter_halucination < 2:
|
475 |
+
pprint("---DECISION: GENERATION IS NOT GROUNDED IN DOCUMENTS, RE-TRY---")
|
476 |
+
return "not supported"
|
477 |
+
else:
|
478 |
+
return "not useful"
|
479 |
+
|
480 |
+
def lead_check(answer):
|
481 |
+
|
482 |
+
if "otobakım" in answer.lower():
|
483 |
+
return 1
|
484 |
+
else:
|
485 |
+
return 0
|
486 |
+
|
487 |
+
|
488 |
+
def print_result(question, result):
|
489 |
+
output_text = f"""### Question:
|
490 |
+
{question}
|
491 |
+
### Answer:
|
492 |
+
{result}
|
493 |
+
"""
|
494 |
+
return(output_text)
|
495 |
+
|
496 |
+
workflow = StateGraph(GraphState)
|
497 |
+
|
498 |
+
# Define the nodes
|
499 |
+
workflow.add_node("websearch", web_search) # web search # key: action to 0do
|
500 |
+
workflow.add_node("retrieve", retrieve) # retrieve
|
501 |
+
workflow.add_node("grade_documents", grade_documents) # grade documents
|
502 |
+
workflow.add_node("generate", generate) # generatae
|
503 |
+
workflow.add_node("hallucination_router", hallucination_router)
|
504 |
+
workflow.add_node("grade_service", grade_service)
|
505 |
+
|
506 |
+
# workflow.add_node("generate_from_history", generate_from_history)
|
507 |
+
|
508 |
+
workflow.add_edge("grade_service", "retrieve")
|
509 |
+
workflow.add_edge("websearch", "generate") #start -> end of node
|
510 |
+
workflow.add_edge("retrieve", "grade_documents")
|
511 |
+
workflow.add_edge("hallucination_router", "generate")
|
512 |
+
|
513 |
+
|
514 |
+
# workflow.add_edge("generate_from_history", END)
|
515 |
+
|
516 |
+
# Build graph
|
517 |
+
# workflow.set_conditional_entry_point(
|
518 |
+
# history_router, # defined function
|
519 |
+
# {
|
520 |
+
# "question history": "generate_from_history", #returns of the function
|
521 |
+
# "user manual": "grade_service", #returns of the function
|
522 |
+
# },
|
523 |
+
# )
|
524 |
+
workflow.set_entry_point(
|
525 |
+
"grade_service")
|
526 |
+
|
527 |
+
workflow.add_conditional_edges(
|
528 |
+
"grade_documents", # start: node
|
529 |
+
decide_to_generate, # defined function
|
530 |
+
{
|
531 |
+
"websearch": "websearch", #returns of the function
|
532 |
+
"generate": "generate", #returns of the function
|
533 |
+
},
|
534 |
+
)
|
535 |
+
|
536 |
+
workflow.add_conditional_edges(
|
537 |
+
"generate", # start: node
|
538 |
+
grade_generation_v_documents_and_question, # defined function
|
539 |
+
{
|
540 |
+
"not supported": "hallucination_router", #returns of the function
|
541 |
+
"not useful": END, #returns of the function
|
542 |
+
"useful": END, #returns of the function
|
543 |
+
},
|
544 |
+
)
|
545 |
+
|
546 |
+
# Compile
|
547 |
+
app = workflow.compile()
|
548 |
+
|
549 |
+
return app
|