-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathrequester.py
2305 lines (1999 loc) · 96.7 KB
/
requester.py
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import time
import logging
from urllib.parse import urlparse
from pydantic import BaseModel, Field
from typing import List, Tuple
from django.conf import settings
from openai import OpenAI
import requests
import google.generativeai as genai
from google.generativeai.types import HarmCategory, HarmBlockThreshold
from abc import ABC, abstractmethod
from firecrawl import FirecrawlApp
from core.exceptions import WebsiteContentExtractionError, WebsiteContentExtractionThrottleError
import asyncio
from crawl4ai import AsyncWebCrawler
from crawl4ai.async_configs import BrowserConfig, CrawlerRunConfig
from crawl4ai.content_filter_strategy import PruningContentFilter
from crawl4ai.markdown_generation_strategy import DefaultMarkdownGenerator
import html2text
logging.getLogger("openai").setLevel(logging.ERROR)
logging.getLogger("httpx").setLevel(logging.ERROR)
from core.exceptions import ThrottlingException
logger = logging.getLogger(__name__)
from core.guru_types import get_guru_type_prompt_map
genai.configure(api_key=settings.GEMINI_API_KEY)
def get_openai_api_key():
from core.utils import get_default_settings
if settings.ENV == 'selfhosted':
try:
default_settings = get_default_settings()
return default_settings.openai_api_key
except Exception:
# Handle cases where the table/column doesn't exist yet (during migrations)
return settings.OPENAI_API_KEY
else:
return settings.OPENAI_API_KEY
def get_firecrawl_api_key():
from core.utils import get_default_settings
if settings.ENV == 'selfhosted':
try:
default_settings = get_default_settings()
return default_settings.firecrawl_api_key
except Exception:
# Handle cases where the table/column doesn't exist yet (during migrations)
return settings.FIRECRAWL_API_KEY
else:
return settings.FIRECRAWL_API_KEY
def get_youtube_api_key():
from core.utils import get_default_settings
if settings.ENV == 'selfhosted':
try:
default_settings = get_default_settings()
return default_settings.youtube_api_key
except Exception:
# Handle cases where the table/column doesn't exist yet (during migrations)
return settings.YOUTUBE_API_KEY
else:
return settings.YOUTUBE_API_KEY
GURU_ENDPOINTS = {
'processed_raw_questions': 'processed_raw_questions'
}
class GptSummary(BaseModel):
question: str
user_question: str
question_slug: str
description: str
valid_question: bool
user_intent: str
answer_length: int
enhanced_question: str
class FollowUpQuestions(BaseModel):
questions: List[str] = Field(..., description="List of follow up questions")
class ContextDetails(BaseModel):
context_num: int = Field(..., description="Context number")
score: float = Field(..., description="Relevance score of the context")
explanation: str = Field(..., description="Explanation of the context relevance")
class ContextRelevance(BaseModel):
overall_explanation: str = Field(..., description="Overall explanation of context relevance")
contexts: List[ContextDetails] = Field(..., description="List of context relevance details")
class ContextDetailsWithoutExplanation(BaseModel):
context_num: int = Field(..., description="Context number")
score: float = Field(..., description="Relevance score of the context")
class ContextRelevanceWithoutExplanation(BaseModel):
contexts: List[ContextDetailsWithoutExplanation] = Field(..., description="List of context relevance details")
class ClaimDetails(BaseModel):
claim: str = Field(..., description="Claim")
score: float = Field(..., description="Groundedness score")
explanation: str = Field(..., description="Explanation of the groundedness")
class Groundedness(BaseModel):
overall_explanation: str = Field(..., description="Overall explanation of groundedness")
claims: List[ClaimDetails] = Field(..., description="List of claim details")
class AnswerRelevance(BaseModel):
overall_explanation: str = Field(..., description="Overall explanation of answer relevance")
score: float = Field(..., description="Answer relevance score")
class MainContent(BaseModel):
main_content: str = Field(..., description="Main content of the website")
class QuestionGenerationResponse(BaseModel):
summary_sufficient: bool = Field(..., description="Whether the summary is sufficient to answer the questions")
questions: List[str] = Field(..., description="List of questions")
class OrderGitHubFilesByImportance(BaseModel):
files: List[str] = Field(..., description="List of files ordered by their importance")
class WebScraper(ABC):
"""Abstract base class for web scrapers"""
@abstractmethod
def scrape_url(self, url: str) -> Tuple[str, str]:
"""
Scrape content from a URL
Returns: Tuple[title: str, content: str]
"""
pass
class FirecrawlScraper(WebScraper):
"""Firecrawl implementation of WebScraper"""
def __init__(self):
self.app = FirecrawlApp(api_key=get_firecrawl_api_key())
def scrape_url(self, url: str) -> Tuple[str, str]:
scrape_status = self.app.scrape_url(
url,
params={'formats': ['markdown'], "onlyMainContent": True}
)
if 'statusCode' in scrape_status['metadata']:
if scrape_status['metadata']['statusCode'] != 200:
if scrape_status['metadata']['statusCode'] == 429:
raise WebsiteContentExtractionThrottleError(
f"Status code: {scrape_status['metadata']['statusCode']}. "
f"Description: {scrape_status['metadata'].get('description', '')}"
)
else:
raise WebsiteContentExtractionError(
f"Status code: {scrape_status['metadata']['statusCode']}"
)
title = scrape_status['metadata'].get('title', url)
if not title:
title = url
if 'markdown' not in scrape_status:
raise WebsiteContentExtractionError("No content found")
return title, scrape_status['markdown']
def _check_throttling(self, response):
"""Check if response indicates throttling and raise appropriate exception"""
if 'metadata' in response and 'statusCode' in response['metadata']:
status_code = response['metadata']['statusCode']
if status_code == 429:
description = response['metadata'].get('description', '')
error_msg = f"Status code: {status_code}. Description: {description}"
raise WebsiteContentExtractionThrottleError(error_msg)
def _process_successful_item(self, item) -> Tuple[str, str, str]:
"""Process a single successful item from batch response"""
url = item.get('metadata', {}).get('sourceURL', '')
title = item.get('metadata', {}).get('title', url) or url
content = item.get('markdown', '')
if not content:
raise ValueError("No content found")
return url, title, content
def _extract_failing_indices(self, error_str: str, urls: List[str]) -> List[Tuple[str, str]]:
"""Extract failing URLs from error message using regex"""
import re
failed_urls = []
try:
path_matches = re.finditer(r"'path':\s*(\[[^\]]+\])", error_str)
failing_indices = {
path_list[1]
for match in path_matches
if len(path_list := eval(match.group(1))) > 1
and isinstance(path_list[1], int)
}
failed_urls = [(urls[i], error_str) for i in failing_indices]
except Exception as parse_error:
logger.error(f"Error parsing failure response: {parse_error}. Original error: {error_str}")
return failed_urls
def scrape_urls_batch(self, urls: List[str]) -> Tuple[List[Tuple[str, str, str]], List[Tuple[str, str]]]:
"""
Scrape multiple URLs in a batch.
Returns: Tuple[
List[Tuple[url: str, title: str, content: str]], # Successful results
List[Tuple[url: str, error: str]] # Failed URLs with their error messages
]
"""
try:
batch_scrape_result = self.app.batch_scrape_urls(
urls,
params={'formats': ['markdown'], 'onlyMainContent': True, 'timeout': settings.FIRECRAWL_TIMEOUT_MS, 'waitFor': 2000}
)
# batch_scrape_result = {'metadata': {'statusCode': 429, 'description': 'Rate limit exceeded'}}
# Check for throttling first
self._check_throttling(batch_scrape_result)
successful_results = []
failed_urls = []
# Process successful results
for item in batch_scrape_result.get('data', []):
try:
result = self._process_successful_item(item)
successful_results.append(result)
except ValueError as e:
url = item.get('metadata', {}).get('sourceURL', '')
failed_urls.append((url, str(e)))
return successful_results, failed_urls
except WebsiteContentExtractionThrottleError:
raise
except Exception as e:
error_str = str(e)
if "Bad Request" in error_str and "no longer supported" in error_str:
failed_urls = self._extract_failing_indices(error_str, urls)
return [], failed_urls or [(url, error_str) for url in urls]
elif "429" in error_str:
raise WebsiteContentExtractionThrottleError(error_str)
logger.error(f"Batch scraping failed: {error_str}")
return [], [(url, f"Batch scraping failed: {error_str}") for url in urls]
class Crawl4AIScraper(WebScraper):
"""Crawl4AI implementation of WebScraper using AsyncWebCrawler"""
def __init__(self):
self.browser_config = BrowserConfig(
headless=True
)
# Configure markdown generator with content filter
md_generator = DefaultMarkdownGenerator(
# content_filter=PruningContentFilter()
)
self.run_config = CrawlerRunConfig(
word_count_threshold=10,
exclude_external_links=True,
remove_overlay_elements=True,
process_iframes=True,
markdown_generator=md_generator,
wait_until='domcontentloaded', # Wait for all these events
page_timeout=60000, # 60 seconds timeout for page operations
wait_for='body', # Wait for body to be present
)
def scrape_url(self, url: str) -> Tuple[str, str]:
async def _scrape():
try:
async with AsyncWebCrawler(config=self.browser_config) as crawler:
result = await crawler.arun(url=url, config=self.run_config)
if not result.success:
status_code = result.status_code or 500
if status_code == 429:
raise WebsiteContentExtractionThrottleError(
f"Status code: {status_code}. Rate limit exceeded."
)
else:
raise WebsiteContentExtractionError(
f"Status code: {status_code}. Error: {result.error_message}"
)
# Get the title from metadata or use URL as fallback
title = result.metadata.get('title', url) if result.metadata else url
# Try different markdown properties in order of preference
content = None
if hasattr(result, 'markdown'):
if hasattr(result.markdown, 'fit_markdown') and result.markdown.fit_markdown:
content = result.markdown.fit_markdown
elif hasattr(result.markdown, 'raw_markdown') and result.markdown.raw_markdown:
content = result.markdown.raw_markdown
else:
content = result.markdown
if not content:
raise WebsiteContentExtractionError("No content found")
return title, content
except Exception as e:
logger.error(f"Error scraping URL {url}: {str(e)}")
if "Page.content: Unable to retrieve content because the page is navigating" in str(e):
# If we hit the navigation error, try one more time with increased timeouts
self.run_config.wait_for_timeout = 10000 # Increase to 10 seconds
self.run_config.page_timeout = 90000 # Increase to 90 seconds
async with AsyncWebCrawler(config=self.browser_config) as crawler:
result = await crawler.arun(url=url, config=self.run_config)
title = result.metadata.get('title', url) if result.metadata else url
content = result.markdown
if not content:
raise WebsiteContentExtractionError("No content found after retry")
return title, content
else:
raise
# Run the async function in the event loop
try:
loop = asyncio.get_event_loop()
except RuntimeError:
# If no event loop exists, create a new one
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return loop.run_until_complete(_scrape())
def get_web_scraper() -> WebScraper:
"""Factory function to get the appropriate web scraper based on settings"""
from core.utils import get_default_settings
if settings.ENV == 'selfhosted':
default_settings = get_default_settings()
scrape_type = default_settings.scrape_type
scrape_type = scrape_type.lower()
else:
scrape_type = settings.WEBSITE_EXTRACTION
if scrape_type == 'crawl4ai':
return Crawl4AIScraper(), scrape_type
elif scrape_type == 'firecrawl':
return FirecrawlScraper(), scrape_type
else:
raise ValueError(f"Invalid website extraction tool: {scrape_type}")
class GuruRequester():
def __init__(self):
self.base_url = settings.SOURCE_GURU_BACKEND_URL
self.headers = {'Authorization': settings.SOURCE_GURU_TOKEN}
def get_processed_raw_questions(self, page_num):
url = f"{self.base_url}/{GURU_ENDPOINTS['processed_raw_questions']}/?page_num={page_num}"
response = requests.get(url, headers=self.headers)
return response.json()
class OpenAIRequester():
def __init__(self):
self.client = None
self._is_ollama = None
def _ensure_client_initialized(self):
if self.client is not None:
return
from core.models import Settings
from core.utils import get_default_settings
from django.conf import settings
from openai import OpenAI
if settings.ENV == 'selfhosted':
default_settings = get_default_settings()
if default_settings.ai_model_provider == Settings.AIProvider.OLLAMA:
self.client = OpenAI(base_url=f'{default_settings.ollama_url}/v1', api_key='ollama')
self._is_ollama = True
else:
self.client = OpenAI(api_key=default_settings.openai_api_key)
self._is_ollama = False
else:
self.client = OpenAI(api_key=settings.OPENAI_API_KEY)
self._is_ollama = False
def _get_model_name(self, model_name):
"""Get the appropriate model name based on whether we're using Ollama"""
self._ensure_client_initialized()
from core.utils import get_default_settings
default_settings = get_default_settings()
if self._is_ollama:
return default_settings.ollama_base_model
else:
return model_name
def get_context_relevance(self, question_text, user_question, enhanced_question, guru_type_slug, contexts, model_name=settings.GPT_MODEL, cot=True):
from core.utils import get_tokens_from_openai_response, prepare_contexts_for_context_relevance, prepare_prompt_for_context_relevance
guru_variables = get_guru_type_prompt_map(guru_type_slug)
prompt = prepare_prompt_for_context_relevance(cot, guru_variables, contexts)
formatted_contexts = prepare_contexts_for_context_relevance(contexts)
single_text_contexts = ''.join(formatted_contexts)
user_prompt = f"QUESTION: {question_text}\n\nUSER QUESTION: {user_question}\n\nENHANCED QUESTION: {enhanced_question}\n\nCONTEXTS\n{single_text_contexts}"
model_name = self._get_model_name(model_name)
response = self.client.beta.chat.completions.parse(
model=model_name,
messages=[
{"role": "system", "content": prompt},
{"role": "user", "content": user_prompt}
],
response_format=ContextRelevance if cot else ContextRelevanceWithoutExplanation,
temperature=0,
)
try:
prompt_tokens, completion_tokens, cached_prompt_tokens = get_tokens_from_openai_response(response)
usage = {
'prompt_tokens': prompt_tokens,
'completion_tokens': completion_tokens,
'cached_prompt_tokens': cached_prompt_tokens,
'total_tokens': prompt_tokens + completion_tokens + cached_prompt_tokens,
'model': model_name,
}
return json.loads(response.choices[0].message.content), usage, prompt, user_prompt
except json.JSONDecodeError:
raise ValueError("Invalid JSON response from OpenAI")
def rewrite_datasource_context(self, scraped_content, page_title, url, model_name="gpt-4o-mini-2024-07-18"):
from .prompts import datasource_context_rewrite_prompt
from core.utils import get_tokens_from_openai_response
prompt = datasource_context_rewrite_prompt
base_url = urlparse(url).scheme + "://" + urlparse(url).netloc
prompt = prompt.format(scraped_content=scraped_content, page_title=page_title, url=base_url)
logger.info(f"Prompt sending to openai for the url: {url}")
model_name = self._get_model_name(model_name)
response = self.client.beta.chat.completions.parse(
model=model_name,
messages=[{"role": "user", "content": prompt}],
response_format=MainContent,
temperature=0,
)
try:
content = json.loads(response.choices[0].message.content)['main_content']
prompt_tokens, completion_tokens, cached_prompt_tokens = get_tokens_from_openai_response(response)
usage = {
'prompt_tokens': prompt_tokens,
'completion_tokens': completion_tokens,
'cached_prompt_tokens': cached_prompt_tokens,
'total_tokens': prompt_tokens + completion_tokens + cached_prompt_tokens
}
return content, usage, prompt
except (KeyError, json.JSONDecodeError):
raise ValueError("Invalid response from OpenAI")
def get_groundedness(self, question, contexts, model_name="gpt-4o"):
from .prompts import groundedness_prompt
from core.utils import get_tokens_from_openai_response
prompt = groundedness_prompt
guru_variables = get_guru_type_prompt_map(question.guru_type.slug)
prompt = prompt.format(**guru_variables)
model_name = self._get_model_name(model_name)
response = self.client.beta.chat.completions.parse(
model=model_name,
messages=[
{"role": "system", "content": prompt},
{"role": "user", "content": f"QUESTION: {question.question}\n\nCONTEXTS: {contexts}"}
],
response_format=Groundedness,
temperature=0,
)
try:
prompt_tokens, completion_tokens, cached_prompt_tokens = get_tokens_from_openai_response(response)
usage = {
'prompt_tokens': prompt_tokens,
'completion_tokens': completion_tokens,
'cached_prompt_tokens': cached_prompt_tokens,
'total_tokens': prompt_tokens + completion_tokens + cached_prompt_tokens
}
return json.loads(response.choices[0].message.content), usage, prompt
except json.JSONDecodeError:
raise ValueError("Invalid JSON response from OpenAI")
def get_answer_relevance(self, question, answer, model_name="gpt-4o"):
from .prompts import answer_relevance_prompt
from core.utils import get_tokens_from_openai_response
prompt = answer_relevance_prompt
guru_variables = get_guru_type_prompt_map(question.guru_type.slug)
prompt = prompt.format(**guru_variables)
model_name = self._get_model_name(model_name)
response = self.client.beta.chat.completions.parse(
model=model_name,
messages=[
{"role": "system", "content": prompt},
{"role": "user", "content": f"QUESTION: {question.question}\n\nANSWER: {answer}"}
],
response_format=AnswerRelevance,
temperature=0,
)
try:
prompt_tokens, completion_tokens, cached_prompt_tokens = get_tokens_from_openai_response(response)
usage = {
'prompt_tokens': prompt_tokens,
'completion_tokens': completion_tokens,
'cached_prompt_tokens': cached_prompt_tokens,
'total_tokens': prompt_tokens + completion_tokens + cached_prompt_tokens
}
return json.loads(response.choices[0].message.content), usage, prompt
except json.JSONDecodeError:
raise ValueError("Invalid JSON response from OpenAI")
def embed_texts(self, texts, model_name=settings.OPENAI_TEXT_EMBEDDING_MODEL):
while '' in texts:
texts.remove('')
model_name = self._get_model_name(model_name)
response = self.client.embeddings.create(input=texts, model=model_name)
embeddings = []
for embedding in response.data:
embeddings.append(embedding.embedding)
return embeddings
def embed_text(self, text, model_name=settings.OPENAI_TEXT_EMBEDDING_MODEL):
model_name = self._get_model_name(model_name)
response = self.client.embeddings.create(input=[text], model=model_name)
return response.data[0].embedding
def summarize_text(self, text, guru_type, model_name=settings.GPT_MODEL):
from .prompts import summarize_data_sources_prompt
from core.utils import get_llm_usage_from_response
prompt_map = get_guru_type_prompt_map(guru_type.slug)
prompt = summarize_data_sources_prompt.format(**prompt_map, content=text)
try:
model_name = self._get_model_name(model_name)
response = self.client.beta.chat.completions.parse(
model=model_name,
messages=[{"role": "user", "content": prompt}],
response_format=MainContent,
temperature=0,
)
return json.loads(response.choices[0].message.content)['main_content'], get_llm_usage_from_response(response, model_name)
except json.JSONDecodeError:
raise ValueError("Invalid JSON response from OpenAI")
def summarize_guru_type(self, summarizations, guru_type, model_name=settings.GPT_MODEL):
from .prompts import summarize_data_sources_prompt
from core.utils import get_llm_usage_from_response
prompt_map = get_guru_type_prompt_map(guru_type.slug)
prompt = summarize_data_sources_prompt.format(**prompt_map, content=summarizations)
try:
model_name = self._get_model_name(model_name)
response = self.client.beta.chat.completions.parse(
model=model_name,
messages=[{"role": "user", "content": prompt}],
response_format=MainContent,
temperature=0,
)
return json.loads(response.choices[0].message.content)['main_content'], get_llm_usage_from_response(response, model_name)
except json.JSONDecodeError:
raise ValueError("Invalid JSON response from OpenAI")
def generate_questions_from_summary(self, summary, guru_type, model_name=settings.GPT_MODEL):
from .prompts import generate_questions_from_summary_prompt
from core.utils import get_llm_usage_from_response
prompt_map = get_guru_type_prompt_map(guru_type.slug)
prompt = generate_questions_from_summary_prompt.format(**prompt_map, summary=summary)
try:
model_name = self._get_model_name(model_name)
response = self.client.beta.chat.completions.parse(
model=model_name,
messages=[{"role": "user", "content": prompt}],
response_format=QuestionGenerationResponse,
temperature=0,
)
return json.loads(response.choices[0].message.content), get_llm_usage_from_response(response, model_name)
except json.JSONDecodeError:
raise ValueError("Invalid JSON response from OpenAI")
def generate_follow_up_questions(
self,
questions,
last_content,
guru_type,
contexts,
model_name=settings.GPT_MODEL):
"""
Generate follow-up questions based on question history and available contexts.
Args:
questions (list): List of previous questions in the conversation
last_content (str): Content of the last answer
guru_type (GuruType): The guru type object
contexts (list): List of relevant contexts from the last question
model_name (str): The model to use for generation
Returns:
list: List of generated follow-up questions
"""
from .prompts import generate_follow_up_questions_prompt
prompt_map = get_guru_type_prompt_map(guru_type.slug)
# Process custom instruction prompt
custom_follow_up_prompt = prompt_map.get('custom_follow_up_prompt', '')
if custom_follow_up_prompt and custom_follow_up_prompt.strip():
custom_follow_up_section = f"\nCUSTOM INSTRUCTIONS (These take priority if there are conflicts with other guidelines):\n\n{custom_follow_up_prompt}\n\nDEFAULT INSTRUCTIONS (These are the default instructions that will be used if there are no conflicts with the custom instructions):\n"
else:
custom_follow_up_section = ""
prompt = generate_follow_up_questions_prompt.format(
**prompt_map,
questions=json.dumps(questions, indent=2),
answer=last_content,
contexts=json.dumps(contexts, indent=2),
num_questions=settings.FOLLOW_UP_EXAMPLE_COUNT,
custom_follow_up_section=custom_follow_up_section
)
try:
model_name = self._get_model_name(model_name)
response = self.client.beta.chat.completions.parse(
model=model_name,
messages=[{"role": "user", "content": prompt}],
response_format=FollowUpQuestions,
temperature=0,
)
return json.loads(response.choices[0].message.content)['questions']
except json.JSONDecodeError:
logger.error("Invalid JSON response from OpenAI while generating follow-up questions")
return []
except Exception as e:
logger.error(f"Error generating follow-up questions: {str(e)}")
return []
def ask_question_with_stream(self, messages, model_name=settings.GPT_MODEL):
"""
Ask a question with streaming response from OpenAI.
Args:
messages (list): List of message dictionaries with role and content
model_name (str): The model to use for generation
Returns:
Generator: Stream of response chunks
"""
model_name = self._get_model_name(model_name)
return self.client.chat.completions.create(
model=model_name,
temperature=0,
messages=messages,
stream=True,
stream_options={"include_usage": True},
)
def get_summary(self, prompt, question, model_name=settings.GPT_MODEL):
"""
Get a summary response from OpenAI.
Args:
prompt (str): The system prompt
question (str): The user question
model_name (str): The model to use for generation
Returns:
dict: The parsed response from OpenAI
"""
model_name = self._get_model_name(model_name)
return self.client.beta.chat.completions.parse(
model=model_name,
temperature=0,
messages=[
{
'role': 'system',
'content': prompt
},
{
'role': 'user',
'content': question
}
],
response_format=GptSummary
)
class GeminiEmbedder():
def __init__(self):
from google import genai
self.client = genai.Client(api_key=settings.GEMINI_API_KEY)
def embed_texts(self, texts):
time.sleep(0.5)
response = self.client.models.embed_content(model="embedding-001", contents=texts)
embeddings = response.embeddings
if type(texts) == str:
return embeddings[0].values
else:
return [embedding.values for embedding in embeddings]
class GeminiRequester():
def __init__(self, model_name):
self.client = genai.GenerativeModel(model_name)
self.model_name = model_name
# Added safety settings because sometimes Gemini does not complete the json response
self.safety_settings = {
HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE,
HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE,
HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,
HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE,
}
def scrape_main_content(self, content):
from .prompts import scrape_main_content_prompt
prompt = scrape_main_content_prompt.format(content=content)
response = self.client.generate_content(prompt)
return response.text
def summarize_text(self, text, guru_type):
from .prompts import summarize_data_sources_prompt
from core.utils import get_llm_usage_from_response
self.client = genai.GenerativeModel(
model_name=self.model_name,
generation_config={
"temperature": 0.2,
"top_p": 0.95,
"top_k": 40,
"max_output_tokens": 8192,
"response_schema": {
"type": "object",
"properties": {
"summary_suitable": {
"type": "boolean"
},
"reasoning": {
"type": "string"
},
"summary": {
"type": "string"
}
},
"required": ["summary_suitable", "reasoning", "summary"]
},
"response_mime_type": "application/json",
}
)
prompt_map = get_guru_type_prompt_map(guru_type.slug, only_active=False)
prompt = summarize_data_sources_prompt.format(**prompt_map, content=text)
time.sleep(0.2)
response = self.client.generate_content(prompt, safety_settings=self.safety_settings)
try:
response_json = json.loads(response.text)
except Exception as e:
logger.error(f"Error parsing JSON response from Gemini. Guru type: {guru_type.slug}. Text: {text[:100]}.... Response: {response.text}", exc_info=True)
raise ValueError("Invalid JSON response from Gemini")
return response_json, get_llm_usage_from_response(response, self.model_name)
def generate_questions_from_summary(self, summary, guru_type):
from .prompts import generate_questions_from_summary_prompt
from core.utils import get_llm_usage_from_response
self.client = genai.GenerativeModel(
model_name=self.model_name,
generation_config={
"temperature": 0.2,
"top_p": 0.95,
"top_k": 40,
"max_output_tokens": 8192,
"response_schema": {
"type": "object",
"properties": {
"summary_sufficient": {
"type": "boolean"
},
"questions": {
"type": "array",
"items": {
"type": "string"
}
}
},
"required": ["summary_sufficient", "questions"]
},
"response_mime_type": "application/json",
}
)
prompt_map = get_guru_type_prompt_map(guru_type.slug)
prompt = generate_questions_from_summary_prompt.format(**prompt_map, summary=summary)
time.sleep(0.2)
response = self.client.generate_content(prompt, safety_settings=self.safety_settings)
try:
response_json = json.loads(response.text)
except Exception as e:
logger.error(f"Error parsing JSON response from Gemini. Guru type: {guru_type.slug}. Summary: {summary[:100]}.... Response: {response.text}", exc_info=True)
raise ValueError("Invalid JSON response from Gemini")
return response_json, get_llm_usage_from_response(response, self.model_name)
def generate_topics_from_summary(self, summary, guru_type_name, github_topics, github_description):
from .prompts import generate_topics_from_summary_prompt
self.client = genai.GenerativeModel(
model_name=self.model_name,
generation_config={
"temperature": 0.2,
"top_p": 0.95,
"top_k": 40,
"max_output_tokens": 8192,
"response_schema": {
"type": "object",
"properties": {
"topics": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"response_mime_type": "application/json",
}
)
prompt = generate_topics_from_summary_prompt.format(guru_type=guru_type_name, summary=summary, github_topics=github_topics, github_description=github_description)
time.sleep(0.2)
response = self.client.generate_content(prompt, safety_settings=self.safety_settings)
try:
response_json = json.loads(response.text)
except Exception as e:
logger.error(f"generate_topics_from_summary: Error parsing JSON response from Gemini. Guru type: {guru_type_name}. Summary: {summary[:100]}.... Response: {response.text}", exc_info=True)
raise ValueError("Invalid JSON response from Gemini")
return response_json
def generate_follow_up_questions(
self,
questions,
last_content,
guru_type,
contexts,
model_name=None):
"""
Generate follow-up questions based on question history and available contexts using Gemini.
Args:
questions (list): List of previous questions in the conversation
last_content (str): Content of the last answer
guru_type (GuruType): The guru type object
contexts (list): List of relevant contexts from the last question
model_name (str): Optional model override (unused, kept for compatibility)
Returns:
list: List of generated follow-up questions
"""
from .prompts import generate_follow_up_questions_prompt
self.client = genai.GenerativeModel(
model_name=self.model_name,
generation_config={
"temperature": 0.2,
"top_p": 0.95,
"top_k": 40,
"max_output_tokens": 8192,
"response_schema": {
"type": "object",
"properties": {
"questions": {
"type": "array",
"items": {
"type": "string"
}
}
},
"required": ["questions"]
},
"response_mime_type": "application/json",
}
)
prompt_map = get_guru_type_prompt_map(guru_type.slug)
# Process custom instruction prompt
custom_follow_up_prompt = prompt_map.get('custom_follow_up_prompt', '')
if custom_follow_up_prompt and custom_follow_up_prompt.strip():
custom_follow_up_section = f"\nCUSTOM INSTRUCTIONS (These take priority if there are conflicts with other guidelines):\n\n{custom_follow_up_prompt}\n\nDEFAULT INSTRUCTIONS (These are the default instructions that will be used if there are no conflicts with the custom instructions):\n"
else:
custom_follow_up_section = ""
prompt = generate_follow_up_questions_prompt.format(
**prompt_map,
questions=json.dumps(questions, indent=2),
answer=last_content,
contexts=json.dumps(contexts, indent=2),
num_questions=settings.FOLLOW_UP_EXAMPLE_COUNT,
custom_follow_up_section=custom_follow_up_section
)
try:
response = self.client.generate_content(prompt, safety_settings=self.safety_settings)
response_json = json.loads(response.text)
return response_json.get('questions', [])
except Exception as e:
logger.error(f"Error generating follow-up questions with Gemini: {str(e)}", exc_info=True)
return []
class GitHubRequester():
def __init__(self):
self.base_url = "https://api.github.com/repos"
self.headers = {
'Accept': 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28'
}
if settings.GITHUB_TOKEN:
self.headers['Authorization'] = f'Bearer {settings.GITHUB_TOKEN}'
def get_github_repo_details(self, github_url):
owner = github_url.split('https://github.com/')[1].split('/')[0]
repo = github_url.split('https://github.com/')[1].split('/')[1]
url = f"{self.base_url}/{owner}/{repo}"
response = requests.get(url, headers=self.headers, timeout=10)
if response.status_code != 200:
raise ValueError(f"Error getting GitHub repo details for {github_url}. Status code: {response.status_code}. Response: {response.text}")
# {"status": "403", "message": "API rate limit exceeded for 34.66.36.109. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)"}
if response.json().get('status') == '403':
raise ValueError(f"GitHub API rate limit exceeded for {github_url}")
return response.json()
class JiraRequester():
def __init__(self, integration):
"""
Initialize Jira Requester with integration credentials
Args:
integration (Integration): Integration model instance containing Jira credentials
"""
from atlassian import Jira
self.url = f"https://{integration.jira_domain}"
self.jira = Jira(
url=self.url,
username=integration.jira_user_email,
password=integration.jira_api_key
)
def list_issues(self, jql_query, start=0, max_results=50):
"""
List Jira issues using JQL query with pagination
Args:
jql_query (str): JQL query string to filter issues
start (int): Starting index for pagination (unused, kept for compatibility)
max_results (int): Maximum number of results to fetch per request
Returns:
list: List of Jira issues matching the query
Raises:
ValueError: If API request fails
"""
try:
all_issues = []
current_start = 0
page_size = max_results
while True:
# Get issues using JQL
issues_data = self.jira.jql(jql_query, start=current_start, limit=page_size)
issues = issues_data.get('issues', [])
if not issues:
break
for issue in issues:
formatted_issue = {
'id': issue.get('id'),
# 'key': issue.get('key'),
# 'summary': issue.get('fields', {}).get('summary'),
# 'issue_type': issue.get('fields', {}).get('issuetype', {}).get('name'),
# 'status': issue.get('fields', {}).get('status', {}).get('name'),
# 'priority': issue.get('fields', {}).get('priority', {}).get('name'),
# 'assignee': issue.get('fields', {}).get('assignee', {}).get('displayName'),
'link': f"{self.url}/browse/{issue.get('key')}"
}
all_issues.append(formatted_issue)
# If we got fewer issues than requested, we've reached the end
if len(issues) < page_size:
break
# Move to the next page
current_start += page_size
return all_issues
except Exception as e:
logger.error(f"Error listing Jira issues: {str(e)}", exc_info=True)
if "401" in str(e):
raise ValueError("Invalid Jira credentials")
elif "403" in str(e):
raise ValueError("Jira API access forbidden")
else:
raise ValueError(str(e))
def get_issue(self, issue_key):