Repository navigation
Expand file tree
/
Copy pathgemini_agent.py
More file actions
151 lines (123 loc) · 4.87 KB
/
Copy pathgemini_agent.py
File metadata and controls
151 lines (123 loc) · 4.87 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
from langchain_community.vectorstores import FAISS
from langchain_huggingface.embeddings import HuggingFaceEmbeddings
from langchain_classic.chains import RetrievalQA
# from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_groq import ChatGroq
from langchain_core.prompts import PromptTemplate
import os
from google.genai import types
from google import genai
from dotenv import load_dotenv
import streamlit as st
load_dotenv()
# llm = ChatGoogleGenerativeAI(
# # model="gemini-2.5-flash-lite",
# model="gemini-flash-latest",
# temperature=0.7,
# max_tokens=3000,
# timeout=None,
# max_retries=2,
# api_key=os.getenv('GEMINI_API_KEY'),
# )
llm = ChatGroq(
model="llama-3.1-8b-instant",
temperature=0.7,
max_tokens=None,
timeout=None,
max_retries=2,
)
embeddings = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-mpnet-base-v2"
)
FALLBACK_PHRASES = [
"i don't have info",
"i do not have info",
"i can only assist you with the information of file uploaded",
"not present in the document",
"not available in the provided content"
]
def needs_internet_search(answer: str) -> bool:
answer_lower = answer.lower()
return any(phrase in answer_lower for phrase in FALLBACK_PHRASES)
def switch_to_internet_search(retriever_query):
if os.getenv('GEMINI_API_KEY'):
client = genai.Client(api_key=os.getenv('GEMINI_API_KEY'))
model = "gemini-2.5-flash"
contents = [
types.Content(
role="user",
parts=[types.Part.from_text(text=retriever_query)],
),
]
tools = [
types.Tool(google_search=types.GoogleSearchRetrieval()),
]
generate_content_config = types.GenerateContentConfig(
tools=tools,
)
try:
response = client.models.generate_content(
model=model,
contents=contents,
config=generate_content_config,
)
response_after_internet_search = response.text
return response_after_internet_search
except Exception as e:
if "429" in str(e):
response_after_internet_search = "Quota exceeded. Please wait a moment or check your billing."
elif "400" in str(e):
response_after_internet_search = "Invalid API key, Check your API key in Settings"
else:
response_after_internet_search = (f"An unexpected error occurred: {e}")
print(f"Detailed Error: {e}")
return response_after_internet_search
else:
return "Head over to Settings and configure your Gemini API key"
def ask_ai(retriever_query, full_history,data_base_live_connected):
vector_embeddings = FAISS.load_local(
f'{data_base_live_connected}',
embeddings,
allow_dangerous_deserialization=True
)
retriever = vector_embeddings.as_retriever(
search_type="similarity",
search_kwargs={"k": 3},
score_threshold=0.5
)
prompt_template = """
Given the following context and a question, generate an answer based on this context
NO PREAMBLE, Dont repeat the question in answer
In the answer try to provide as much text as possible from "response" section in the source document context without making much changes.
If the answer is not found in the context but related to the website then, kindly state "I don't have info on (use appropriate words end with full stop), switching back to Internet search". Don't try to make up an answer.
If the question is completely unrelated and makes no sense with vector DB context backgroud the tell user that "I can only assist you with the information of file uploaded"
If the intent of the question is not related to topic like greetings or short msgs (hi,bye,thanks,okay.alr,slangs used) then reply normally as a LLM/chatbot
CONTEXT: {context}
QUESTION: {question}
"""
PROMPT = PromptTemplate(
template=prompt_template,
input_variables=["context", "question"]
)
qa = RetrievalQA.from_chain_type(
llm=llm,
chain_type="stuff",
retriever=retriever,
input_key="query",
chain_type_kwargs={"prompt": PROMPT},
verbose=True
)
try:
result = qa.invoke(retriever_query)
print(result)
result = result["result"]
if needs_internet_search(result):
internet_answer = switch_to_internet_search(retriever_query)
final_answer = f"Information unavailable in file uploaded\nInternet Search result:\n{internet_answer}"
else:
final_answer = result
except Exception as e:
st.warning("You exceeded your current quota, Please try later or get a new API key")
print(e)
return ""
return final_answer