Kackle commited on
Commit
7e06f4a
·
verified ·
1 Parent(s): 2a05f5f

Update gemini_agent.py

Browse files
Files changed (1) hide show
  1. gemini_agent.py +132 -0
gemini_agent.py CHANGED
@@ -44,6 +44,10 @@ class GeminiAgent:
44
  # Check if question is about actors, TV shows, or movies
45
  if self._is_actor_or_show_question(question):
46
  return await self._handle_actor_show_question(question)
 
 
 
 
47
 
48
  # Regular text-based question
49
  return await self._handle_text_question(question)
@@ -64,6 +68,134 @@ class GeminiAgent:
64
  ]
65
  return any(pattern in q for pattern in actor_show_patterns)
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  async def _handle_actor_show_question(self, question: str) -> str:
68
  """Handle questions about actors, TV shows, and movies with enhanced search"""
69
  print(f"Processing actor/show question: {question[:50]}...")
 
44
  # Check if question is about actors, TV shows, or movies
45
  if self._is_actor_or_show_question(question):
46
  return await self._handle_actor_show_question(question)
47
+
48
+ # Check if question is about music, albums, or discography
49
+ if self._is_music_question(question):
50
+ return await self._handle_music_question(question)
51
 
52
  # Regular text-based question
53
  return await self._handle_text_question(question)
 
68
  ]
69
  return any(pattern in q for pattern in actor_show_patterns)
70
 
71
+ def _is_music_question(self, question: str) -> bool:
72
+ """Determine if a question is about music, albums, or discography"""
73
+ q = question.lower()
74
+ music_patterns = [
75
+ "album", "albums", "discography", "song", "songs", "track", "tracks",
76
+ "musician", "singer", "artist", "band", "composer", "recorded", "released",
77
+ "studio album", "live album", "compilation", "single", "ep"
78
+ ]
79
+ # Check for music-related terms
80
+ has_music_term = any(pattern in q for pattern in music_patterns)
81
+ # Check for date ranges which are common in discography questions
82
+ has_date_range = re.search(r'between\s+\d{4}\s+and\s+\d{4}', q) is not None
83
+ return has_music_term or has_date_range
84
+
85
+ async def _handle_music_question(self, question: str) -> str:
86
+ """Handle questions about music, albums, and discographies with enhanced search"""
87
+ print(f"Processing music/discography question: {question[:50]}...")
88
+
89
+ # Always try both Wikipedia and DuckDuckGo for these questions
90
+ wiki_context = ""
91
+ ddg_context = ""
92
+
93
+ # Extract date range if present
94
+ date_range = re.search(r'between\s+(\d{4})\s+and\s+(\d{4})', question.lower())
95
+ start_year = None
96
+ end_year = None
97
+ if date_range:
98
+ start_year = int(date_range.group(1))
99
+ end_year = int(date_range.group(2))
100
+ else:
101
+ # Check for other date range formats
102
+ date_range = re.search(r'from\s+(\d{4})\s+to\s+(\d{4})', question.lower())
103
+ if date_range:
104
+ start_year = int(date_range.group(1))
105
+ end_year = int(date_range.group(2))
106
+ else:
107
+ # Check for single year with inclusion indicator
108
+ included_year = re.search(r'(\d{4})\s*\(included\)', question.lower())
109
+ if included_year:
110
+ end_year = int(included_year.group(1))
111
+
112
+ # Specifically mention Wikipedia version if specified
113
+ wiki_version = None
114
+ if "version of" in question.lower() and "wikipedia" in question.lower():
115
+ version_match = re.search(r'(\d{4})\s+version\s+of\s+\w+\s+wikipedia', question.lower())
116
+ if version_match:
117
+ wiki_version = version_match.group(1)
118
+ print(f"Using Wikipedia version from {wiki_version}")
119
+
120
+ # Construct a more specific search query for discography questions
121
+ search_query = question
122
+ if "how many" in question.lower() and "album" in question.lower():
123
+ # Extract artist name - look for patterns like "by [Artist Name]" or just the name before "albums"
124
+ artist_match = re.search(r'by\s+([\w\s]+)\s+between', question)
125
+ if not artist_match:
126
+ artist_match = re.search(r'([\w\s]+)\s+albums', question)
127
+
128
+ if artist_match:
129
+ artist_name = artist_match.group(1).strip()
130
+ search_query = f"{artist_name} complete discography studio albums {start_year if start_year else ''} to {end_year if end_year else ''}"
131
+ print(f"Enhanced search query: {search_query}")
132
+
133
+ try:
134
+ wiki_context = self.wiki_tool.run(search_query)
135
+ print("Wikipedia search completed")
136
+ except Exception as e:
137
+ print(f"Wikipedia tool failed: {e}")
138
+
139
+ try:
140
+ ddg_context = self.ddg_tool.run(search_query)
141
+ print("DuckDuckGo search completed")
142
+ except Exception as e:
143
+ print(f"DuckDuckGo tool failed: {e}")
144
+
145
+ # Combine contexts if available
146
+ combined_context = ""
147
+ if wiki_context and not any(x in wiki_context.lower() for x in ["not found", "no results", "does not contain"]):
148
+ combined_context += f"Wikipedia context: {wiki_context}\n\n"
149
+ if ddg_context and not any(x in ddg_context.lower() for x in ["not found", "no results", "does not contain"]):
150
+ combined_context += f"Web search context: {ddg_context}\n\n"
151
+
152
+ # Create a specialized prompt for music/discography questions
153
+ prompt = f"""Based on the following context, answer this question about music or discography:
154
+
155
+ Question: {question}
156
+
157
+ {combined_context}
158
+
159
+ """
160
+
161
+ # Add specific instructions for counting albums in a date range
162
+ if "how many" in question.lower() and "album" in question.lower() and start_year and end_year:
163
+ prompt += f"""Count ONLY the studio albums released between {start_year} and {end_year}, inclusive of both years.
164
+
165
+ Provide ONLY the numeric count as your answer, with no additional text.
166
+
167
+ Make sure to count each album only once, and only count studio albums (not compilations, live albums, or EPs) unless specifically asked for those."""
168
+ else:
169
+ prompt += "Provide ONLY the specific information requested. No explanations or additional context."
170
+
171
+ await self._rate_limit()
172
+ response = self.model.generate_content(
173
+ prompt,
174
+ generation_config=genai.types.GenerationConfig(
175
+ max_output_tokens=50,
176
+ temperature=0.0
177
+ )
178
+ )
179
+ answer = response.text.strip()
180
+
181
+ # Clean up the answer to extract just the number or information
182
+ # Remove common prefixes
183
+ prefixes = ['The answer is', 'Based on', 'According to', 'The number is', 'There were']
184
+ for prefix in prefixes:
185
+ if answer.lower().startswith(prefix.lower()):
186
+ answer = answer[len(prefix):].strip()
187
+ if answer.startswith(','):
188
+ answer = answer[1:].strip()
189
+
190
+ # If the question is asking for a count, extract just the number
191
+ if "how many" in question.lower():
192
+ # Try to extract just the number
193
+ number_match = re.search(r'\b(\d+)\b', answer)
194
+ if number_match:
195
+ answer = number_match.group(1)
196
+
197
+ return answer
198
+
199
  async def _handle_actor_show_question(self, question: str) -> str:
200
  """Handle questions about actors, TV shows, and movies with enhanced search"""
201
  print(f"Processing actor/show question: {question[:50]}...")