-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresearch_crew_NO_CREWAI_simplified_github.py
More file actions
5322 lines (4569 loc) · 229 KB
/
research_crew_NO_CREWAI_simplified_github.py
File metadata and controls
5322 lines (4569 loc) · 229 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
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 os
import json
import logging
import asyncio
import openai
from dotenv import load_dotenv
from datetime import datetime
from serper_tool import SerperSearchTool
import requests
from bs4 import BeautifulSoup
from io import BytesIO
from pypdf import PdfReader
import re
import random
import aiohttp
from typing import Tuple, Dict, Set, Any, List, Optional
from urllib.parse import urlparse
from html import unescape
from pydantic import BaseModel
import semanticscholar as sch # Add this import line
import habanero # Add this import for Crossref API
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import html2text
import httpx
# Add to imports at top of file
from scrapingbee import ScrapingBeeClient
import base64
import json
import time
import chardet
import fitz
from google import genai
from google.genai.types import GenerateContentConfig
import json
import time
from openai import OpenAI
import httpx
import os
from enum import Enum
import traceback
import brotli
from typing import Union
import anthropic
# Model selection configuration
class ModelChoice(Enum):
O3MINI = "o3mini"
GEMINI = "gemini" # Original Gemini Flash
GEMINI_PRO = "gemini_pro" # New Gemini Pro option
DEEPSEEK = "deepseek"
# Set your preferred model here
PREFERRED_MODEL = ModelChoice.O3MINI # Set to GEMINI_PRO for Gemini Pro, O3MINI for O3Mini, GEMINI for Gemini Flash, DEEPSEEK for DeepSeek (FIREWORKS)
# Load environment variables
load_dotenv()
# Initialize API keys from environment variables
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
FIREWORKS_API_KEY = os.getenv("FIREWORKS_API_KEY")
SCRAPINGBEE_API_KEY = os.getenv("SCRAPINGBEE_API_KEY")
PARSEHUB_API_KEY = os.getenv("PARSEHUB_API_KEY")
PARSEHUB_PROJECT_TOKEN = os.getenv("PARSEHUB_PROJECT_TOKEN")
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
# Validate required API keys
if not OPENAI_API_KEY:
raise ValueError("OPENAI_API_KEY not found in environment variables")
# Initialize clients
anthropic_client = anthropic.Client(api_key=ANTHROPIC_API_KEY)
gemini_client = genai.Client(api_key=GEMINI_API_KEY)
# Add to the model constants at the top
GEMINI_FLASH_THINKING_ID="gemini-2.0-flash-thinking-exp-01-21"
GEMINI_PRO_ID = "gemini-2.0-pro-exp-02-05"
# Initialize root logger at module level
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)
# Move these variables to the top but don't set LOG_FILE yet
BASE_OUTPUT_FOLDER = os.path.join("C:\\", "research_outputs")
OUTPUT_FOLDER = None
LOG_FOLDER = None
CONTENT_FOLDER = None
SEARCH_FOLDER = None
# Search configuration
MAX_SEARCH_ROUNDS = 7
MAX_REFERENCES = 12
from logging.handlers import RotatingFileHandler
def setup_logging():
"""Set up logging configuration using a rotating file handler."""
global LOG_FILE
LOG_FILE = os.path.join(LOG_FOLDER, f"research_log_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt")
root_logger.handlers.clear()
# Set the root logger level to DEBUG to capture everything
root_logger.setLevel(logging.DEBUG)
# Use RotatingFileHandler (max 10 MB per file, with up to 5 backups)
file_handler = RotatingFileHandler(LOG_FILE, maxBytes=10*1024*1024, backupCount=5, encoding='utf-8')
file_formatter = logging.Formatter(
'%(asctime)s [%(levelname)s] %(funcName)s:%(lineno)d - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
file_handler.setFormatter(file_formatter)
file_handler.setLevel(logging.DEBUG) # Ensure file handler captures all levels
root_logger.addHandler(file_handler)
# Console handler with different formatting and level
console_handler = logging.StreamHandler()
console_formatter = logging.Formatter('%(message)s')
console_handler.setFormatter(console_formatter)
console_handler.setLevel(logging.INFO) # Console shows INFO and above
root_logger.addHandler(console_handler)
# Log initial setup message
root_logger.info(f"Logging initialized: {LOG_FILE}")
root_logger.debug("Debug logging enabled")
def setup_folders():
"""Set up and create necessary folders"""
global OUTPUT_FOLDER, LOG_FOLDER, CONTENT_FOLDER, SEARCH_FOLDER
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
OUTPUT_FOLDER = os.path.join(BASE_OUTPUT_FOLDER, f"research_session_{timestamp}")
LOG_FOLDER = os.path.join(OUTPUT_FOLDER, "logs")
CONTENT_FOLDER = os.path.join(OUTPUT_FOLDER, "content")
SEARCH_FOLDER = os.path.join(OUTPUT_FOLDER, "search_results")
# Log folder creation
print(f"Creating folders for session {timestamp}")
for folder in [OUTPUT_FOLDER, LOG_FOLDER, CONTENT_FOLDER, SEARCH_FOLDER]:
os.makedirs(folder, exist_ok=True)
# Initialize session-specific files with correct structure
session_files = {
"session_search_results.json": {
"metadata": {
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"session_id": os.path.basename(OUTPUT_FOLDER),
"total_results": 0
},
"url_map": {}
},
"session_picked_references.json": [],
"session_citations_check.json": []
}
for filename, initial_data in session_files.items():
filepath = os.path.join(SEARCH_FOLDER, filename)
if not os.path.exists(filepath):
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(initial_data, f, indent=2)
# Set up logging after folders are created
setup_logging()
# Log successful setup
root_logger.info(f"Session folders created at: {OUTPUT_FOLDER}")
root_logger.debug(f"Log folder: {LOG_FOLDER}")
root_logger.debug(f"Content folder: {CONTENT_FOLDER}")
root_logger.debug(f"Search results folder: {SEARCH_FOLDER}")
def sanitize_json_content(content: str, strict: bool = True) -> str:
"""
Clean and optionally validate a JSON-like string.
If the string starts with { or [, assume it is meant to be JSON.
"""
if not isinstance(content, str):
return str(content)
content = content.strip()
# If it doesn't look like JSON, return it as is
if not (content.startswith('{') or content.startswith('[')):
return content
# Remove markdown code blocks and headers
content = re.sub(r'```.*?```', '', content, flags=re.DOTALL)
content = re.sub(r'#.*?\n', '', content)
content = content.strip()
if strict:
try:
# Try parsing and then re-stringifying
parsed = json.loads(content)
return json.dumps(parsed, ensure_ascii=False)
except json.JSONDecodeError as e:
root_logger.debug(f"sanitize_json_content: JSON parsing failed: {e}")
return content
def clean_special_chars(text: str) -> str:
"""Clean special characters from text, including Unicode box-drawing characters."""
# Replace Unicode box-drawing characters and other special formatting
replacements = {
'\u2500': '-', # ─
'\u2502': '|', # │
'\u2503': '|', # ┃
'\u2504': '-', # ┄
'\u2505': '-', # ┅
'\u2506': '|', # ┆
'\u2507': '|', # ┇
'\u2508': '-', # ┈
'\u2509': '-', # ┉
'\u250A': '|', # ┊
'\u250B': '|', # ┋
'\u250C': '+', # ┌
'\u250D': '+', # ┍
'\u250E': '+', # ┎
'\u250F': '+', # ┏
'\u2510': '+', # ┐
'\u2511': '+', # ┑
'\u2512': '+', # ┒
'\u2513': '+', # ┓
'\u2514': '+', # └
'\u2515': '+', # ┕
'\u2516': '+', # ┖
'\u2517': '+', # ┗
'\u2518': '+', # ┘
'\u2519': '+', # ┙
'\u251A': '+', # ┚
'\u251B': '+', # ┛
'\u251C': '+', # ├
'\u251D': '+', # ┝
'\u251E': '+', # ┞
'\u251F': '+', # ┟
'\u2520': '+', # ┠
'\u2521': '+', # ┡
'\u2522': '+', # ┢
'\u2523': '+', # ┣
'\u2524': '+', # ┤
'\u2525': '+', # ┥
'\u2526': '+', # ┦
'\u2527': '+', # ┧
'\u2528': '+', # ┨
'\u2529': '+', # ┩
'\u252A': '+', # ┪
'\u252B': '+', # ┫
'\u252C': '+', # ┬
'\u252D': '+', # ┭
'\u252E': '+', # ┮
'\u252F': '+', # ┯
'\u2530': '+', # ┰
'\u2531': '+', # ┱
'\u2532': '+', # ┲
'\u2533': '+', # ┳
'\u2534': '+', # ┴
'\u2535': '+', # ┵
'\u2536': '+', # ┶
'\u2537': '+', # ┷
'\u2538': '+', # ┸
'\u2539': '+', # ┹
'\u253A': '+', # ┺
'\u253B': '+', # ┻
'\u253C': '+', # ┼
'\u253D': '+', # ┽
'\u253E': '+', # ┾
'\u253F': '+', # ┿
'\u2540': '+', # ╀
'\u2541': '+', # ╁
'\u2542': '+', # ╂
'\u2543': '+', # ╃
'\u2544': '+', # ╄
'\u2545': '+', # ╅
'\u2546': '+', # ╆
'\u2547': '+', # ╇
'\u2548': '+', # ╈
'\u2549': '+', # ╉
'\u254A': '+', # ╊
'\u254B': '+', # ╋
'\u2003': ' ', # EM SPACE
'\u25ab': '-', # WHITE SMALL SQUARE
'\u25aa': '-', # BLACK SMALL SQUARE
'\u2022': '-', # BULLET
}
for char, replacement in replacements.items():
text = text.replace(char, replacement)
# Remove any remaining unicode characters
text = text.encode('ascii', 'ignore').decode('ascii')
return text
def validate_response(content: str, min_length: int = 50, is_search_query: bool = False) -> bool:
"""
Return True if content is nonempty, long enough, and does not indicate an error.
For search queries, uses different validation rules.
"""
if not content:
return False
# Special handling for search queries
if is_search_query:
if len(content.strip()) < 1: # Search queries just need to be non-empty
return False
if "[error]" in content.lower():
return False
return True
# Standard validation for non-search-query content
if len(content.strip()) < min_length:
return False
if "[error]" in content.lower():
return False
try:
# If it appears to be JSON, try parsing it after sanitization.
if content.strip().startswith(('{', '[')):
json.loads(sanitize_json_content(content, strict=True))
except Exception as e:
root_logger.debug(f"validate_response: JSON check failed: {e}")
return True
def flatten_messages(messages: List[Dict[str, str]]) -> str:
"""
Convert a list of message dictionaries into a single formatted string.
"""
flattened = []
for msg in messages:
role = msg["role"].upper()
content = msg["content"]
if role == "SYSTEM":
flattened.append(f"Instructions: {content}")
elif role == "USER":
flattened.append(f"User: {content}")
elif role == "ASSISTANT":
flattened.append(f"Assistant: {content}")
return "\n".join(flattened)
def update_search_results(new_results: list) -> Dict:
"""
Update session search results additively.
Preserves existing results while adding new ones.
Returns: Dict of all accumulated results
"""
results_file = os.path.join(OUTPUT_FOLDER, "search_results", "session_search_results.json")
# Load existing results
existing_results = {}
if os.path.exists(results_file):
with open(results_file, 'r', encoding='utf-8') as f:
try:
file_content = json.load(f)
# Handle both possible structures (direct or nested in url_map)
existing_results = file_content.get('url_map', file_content)
except json.JSONDecodeError:
root_logger.error("Error reading existing results file")
existing_results = {}
# Update with new results
for search_item in new_results:
results = search_item.get('results', {})
if isinstance(results, str):
try:
results = json.loads(results)
except json.JSONDecodeError:
continue
# Handle both possible result structures
results_list = []
if isinstance(results, dict):
results_list = results.get('results', [])
elif isinstance(results, list):
results_list = results
for entry in results_list:
url = entry.get('url')
if url:
if url in existing_results:
# Append new query to existing entry's history
if 'queries' not in existing_results[url]:
existing_results[url]['queries'] = []
if search_item.get('query') not in existing_results[url]['queries']:
existing_results[url]['queries'].append(search_item.get('query'))
# Update metadata if new info available
if 'metadata' not in existing_results[url]:
existing_results[url]['metadata'] = {}
existing_results[url]['metadata'].update(entry)
else:
# Create new entry
existing_results[url] = {
'metadata': entry,
'queries': [search_item.get('query')],
'first_found': datetime.now().isoformat(),
'session_id': os.path.basename(OUTPUT_FOLDER)
}
# Save accumulated results with metadata
output_data = {
"metadata": {
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"session_id": os.path.basename(OUTPUT_FOLDER),
"total_results": len(existing_results),
"last_query": new_results[-1].get('query') if new_results else None
},
"url_map": existing_results
}
with open(results_file, 'w', encoding='utf-8') as f:
json.dump(output_data, f, indent=2)
return existing_results
def log_session_data(data: dict, filename: str):
"""
Log session-specific data additively.
"""
filepath = os.path.join(SEARCH_FOLDER, filename) # Use SEARCH_FOLDER directly
# Load existing data
existing_data = []
if os.path.exists(filepath):
with open(filepath, 'r', encoding='utf-8') as f:
existing_data = json.load(f)
# Add new data with timestamp and session ID
data['timestamp'] = datetime.now().isoformat()
data['session_id'] = os.path.basename(OUTPUT_FOLDER)
existing_data.append(data)
# Save updated data
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(existing_data, f, indent=2)
# Replace the custom print function with a proper logging wrapper
def log_print(*args: Any, **kwargs: Any) -> None:
"""
Wrapper function that both logs and prints messages.
"""
output = " ".join(map(str, args))
root_logger.info(output)
# Replace all instances of print with log_print
print = log_print
# Initialize search tool
search_tool = SerperSearchTool()
# Add these constants near other configurations
MAX_CONCURRENT_REQUESTS = 5
REQUEST_TIMEOUT = 90 # seconds - increased from 30
def call_o3mini(messages, model="o3-mini", temperature=0.1, fast_mode=False, max_retries=1, base_delay=2, timeout=90):
"""
Enhanced o3-mini caller with retry logic, timeout, and response sanitization.
Args:
messages: List of message dictionaries
model: Model identifier (default: "o3-mini")
temperature: Temperature for generation (ignored as not supported by o3-mini)
fast_mode: If True, uses faster configuration (ignored for now as o3-mini is already fast)
max_retries: Maximum number of retry attempts (default: 1)
base_delay: Base delay in seconds for exponential backoff (default: 2)
timeout: Timeout in seconds for each request (default: 90)
"""
# Determine if this is a search query request
is_search_query = any(role['role'] == 'system' and 'search query generator' in role['content'].lower()
for role in messages)
# Since o3-mini is already fast, we don't need different configurations for fast_mode
for attempt in range(max_retries):
try:
if attempt > 0:
delay = base_delay * (2 ** (attempt - 1))
root_logger.info(f"Retry attempt {attempt + 1}/{max_retries} after {delay}s delay")
time.sleep(delay)
# Clean special characters from input messages
cleaned_messages = []
for msg in messages:
cleaned_msg = msg.copy()
cleaned_msg['content'] = clean_special_chars(msg['content'])
cleaned_messages.append(cleaned_msg)
print("\n=== O3-MINI INPUT ===")
messages_str = json.dumps(cleaned_messages, indent=2)
if len(messages_str) > 5000:
print(messages_str[:3000] + "\n...[TRUNCATED]...\n" + messages_str[-2000:])
else:
print(messages_str)
print("=====================\n")
# Create OpenAI client configuration
client = OpenAI(
api_key=os.environ["OPENAI_API_KEY"],
base_url="https://api.openai.com/v1",
http_client=httpx.Client(
trust_env=False, # Disable environment-based proxy settings
timeout=httpx.Timeout(
timeout, # Total timeout
connect=timeout, # Connection timeout
read=timeout, # Read timeout
write=timeout # Write timeout
)
),
max_retries=0 # We handle retries ourselves
)
response = client.chat.completions.create(
model=model,
messages=cleaned_messages,
#max_tokens=8192 # Removed as it's not a valid parameter for o3-mini
)
# Try to parse the response
try:
content = response.choices[0].message.content
except (AttributeError, IndexError, json.JSONDecodeError) as e:
root_logger.error(f"Failed to parse response: {str(e)}", exc_info=False)
root_logger.debug(f"Raw response: {response}", exc_info=False)
if attempt < max_retries - 1:
continue
return "[Error: Failed to parse response]"
# Clean special characters from output
content = clean_special_chars(content.strip())
# For search queries, extract just the first non-empty line
if is_search_query:
content = next((line.strip() for line in content.split('\n')
if line.strip() and not line.strip().startswith('```')), content)
# Sanitize and validate the output
content = sanitize_json_content(content)
if not validate_response(content, is_search_query=is_search_query):
if attempt < max_retries - 1:
root_logger.warning("Response validation failed, retrying...", exc_info=False)
continue
return "[Error: Response validation failed]"
print("\n=== O3-MINI OUTPUT ===")
print(content)
print("=====================\n")
return content
except httpx.TimeoutException:
error_msg = f"O3-mini API timeout after {timeout}s"
root_logger.error(f"{error_msg} (attempt {attempt + 1}/{max_retries})", exc_info=False)
if attempt < max_retries - 1:
continue
return f"[Error: {error_msg}]"
except openai.APIError as e:
error_msg = f"O3-mini API error: {str(e)}"
root_logger.error(f"{error_msg} (attempt {attempt + 1}/{max_retries})", exc_info=False)
if attempt < max_retries - 1:
continue
return f"[Error: {error_msg}]"
except openai.RateLimitError as e:
error_msg = f"O3-mini rate limit exceeded: {str(e)}"
root_logger.error(f"{error_msg} (attempt {attempt + 1}/{max_retries})", exc_info=False)
if attempt < max_retries - 1:
time.sleep(base_delay * 4) # Longer delay for rate limits
continue
return f"[Error: {error_msg}]"
except json.JSONDecodeError as e:
error_msg = f"Failed to parse JSON response: {str(e)}"
root_logger.error(f"{error_msg} (attempt {attempt + 1}/{max_retries})", exc_info=False)
if attempt < max_retries - 1:
continue
return f"[Error: {error_msg}]"
except Exception as e:
error_msg = f"O3-mini API call failed: {str(e)}"
root_logger.error(f"{error_msg} (attempt {attempt + 1}/{max_retries})", exc_info=False)
if attempt < max_retries - 1:
continue
return f"[Error: {error_msg}]"
return "[Error: All retry attempts failed]"
def call_claude35_sonnet(
messages: list,
temperature: float = 0.0,
max_tokens: int = 4096,
max_retries: int = 1,
base_delay: int = 2,
timeout: int = 90
) -> str:
"""
Calls Claude 3.5 Sonnet via the Anthropic API using the messages-based interface.
Converts the provided list of messages into a system message and conversational context,
then calls the API with the appropriate parameters.
Args:
messages: List of messages ({'role': 'system'|'user'|'assistant', 'content': str }).
temperature: Generation temperature.
max_tokens: Maximum tokens to generate.
max_retries: Number of retry attempts for error handling.
base_delay: Base delay in seconds for exponential backoff.
timeout: (Not used directly in anthropic.Client but kept for consistency.)
Returns:
The model's string response or an error message.
"""
# Separate the system prompt from the conversation messages. The first system message is used.
system_message = ""
conversation_messages = []
for msg in messages:
if msg["role"].lower() == "system" and not system_message:
system_message = msg["content"].strip()
else:
conversation_messages.append(msg)
# Log input
print("\n=== CLAUDE 3.5 SONNET INPUT ===")
print(f"System message:\n{system_message}\n")
print("Conversation messages:")
messages_str = json.dumps(conversation_messages, indent=2)
if len(messages_str) > 5000:
print(messages_str[:3000] + "\n...[TRUNCATED]...\n" + messages_str[-2000:])
else:
print(messages_str)
print("=====================\n")
for attempt in range(max_retries):
try:
if attempt > 0:
delay = base_delay * (2 ** (attempt - 1))
root_logger.info(f"[Claude 3.5 Sonnet] Retry attempt {attempt+1}/{max_retries} after {delay}s delay...")
time.sleep(delay)
response = anthropic_client.messages.create(
model="claude-3-5-sonnet-latest",
max_tokens=max_tokens,
temperature=temperature,
system=system_message,
messages=conversation_messages
)
# The content is now in response.content, not response.completion
content = response.content[0].text.strip()
if not content:
if attempt < max_retries - 1:
continue
return "[Error: Empty Claude 3.5 Sonnet response]"
# Log output
print("\n=== CLAUDE 3.5 SONNET OUTPUT ===")
print(content)
print("=====================\n")
return content
except Exception as e:
root_logger.error(f"[Claude 3.5 Sonnet] Error on attempt {attempt+1}: {e}")
if attempt == max_retries - 1:
return f"[Error: Claude 3.5 Sonnet call failed after {max_retries} attempts: {str(e)}]"
return "[Error: Unknown error in call_claude35_sonnet]"
def call_gemini(messages, model=GEMINI_FLASH_THINKING_ID, temperature=0.1, fast_mode=False, max_retries=1, base_delay=2, timeout=90):
"""
Gemini version of the caller with retry logic and response sanitization.
Args:
messages: List of message dictionaries (will be converted to appropriate Gemini format)
model: Model identifier (default: GEMINI_FLASH_THINKING_ID)
temperature: Temperature for generation (default: 0.1)
fast_mode: Ignored for Gemini
max_retries: Maximum number of retry attempts (default: 1)
base_delay: Base delay in seconds for exponential backoff (default: 2)
timeout: Currently ignored for Gemini as it uses its own timeout handling
"""
# Convert messages to Gemini format
prompt_parts = []
for msg in messages:
role = msg["role"].upper()
content = msg["content"]
prompt_parts.append(f"{role}: {content}")
prompt = "\n".join(prompt_parts)
print("\n=== GEMINI 2.0 Flash Thinking INPUT ===")
if len(prompt) > 5000:
print(prompt[:3000] + "\n...[TRUNCATED]...\n" + prompt[-2000:])
else:
print(prompt)
print("=====================\n")
for attempt in range(max_retries):
try:
if attempt > 0:
delay = base_delay * (2 ** (attempt - 1))
root_logger.info(f"Retry attempt {attempt + 1}/{max_retries} after {delay}s delay")
time.sleep(delay)
response = gemini_client.models.generate_content(
model=model,
contents=prompt,
config=GenerateContentConfig(
tools=[], # no tools => no searching
response_modalities=["TEXT"],
temperature=temperature
)
)
# Extract text from response
content = "".join(part.text for part in response.candidates[0].content.parts)
content = content.strip()
# Sanitize and validate the output
content = sanitize_json_content(content)
if not validate_response(content):
if attempt < max_retries - 1:
root_logger.warning("Response validation failed, retrying...")
continue
return "[Error: Response validation failed]"
print("\n=== GEMINI OUTPUT ===")
print(content)
print("=====================\n")
return content
except Exception as e:
error_msg = f"Gemini API call failed: {str(e)}"
root_logger.error(f"{error_msg} (attempt {attempt + 1}/{max_retries})")
if attempt < max_retries - 1:
continue
return f"[Error: {error_msg}]"
return "[Error: All retry attempts failed]"
def call_gemini_pro(messages, model=GEMINI_PRO_ID, temperature=0.1, fast_mode=False, max_retries=1, base_delay=2, timeout=90):
"""
Gemini Pro 2.0 caller with retry logic and response sanitization.
Maintains same interface as call_gemini for compatibility.
Args:
messages: List of message dictionaries (will be converted to appropriate Gemini format)
model: Model identifier (default: GEMINI_PRO_ID)
temperature: Temperature for generation (default: 0.1)
fast_mode: Ignored for Gemini Pro
max_retries: Maximum number of retry attempts (default: 1)
base_delay: Base delay in seconds for exponential backoff (default: 2)
timeout: Currently ignored for Gemini as it uses its own timeout handling
"""
# Convert messages to Gemini format
prompt_parts = []
for msg in messages:
role = msg["role"].upper()
content = msg["content"]
prompt_parts.append(f"{role}: {content}")
prompt = "\n".join(prompt_parts)
print("\n=== GEMINI PRO INPUT ===")
if len(prompt) > 5000:
print(prompt[:3000] + "\n...[TRUNCATED]...\n" + prompt[-2000:])
else:
print(prompt)
print("=====================\n")
for attempt in range(max_retries):
try:
if attempt > 0:
delay = base_delay * (2 ** (attempt - 1))
root_logger.info(f"Retry attempt {attempt + 1}/{max_retries} after {delay}s delay")
time.sleep(delay)
response = gemini_client.models.generate_content(
model=model,
contents=prompt,
config=GenerateContentConfig(
tools=[], # no tools => no searching
response_modalities=["TEXT"],
temperature=temperature
)
)
# Extract text from response
content = "".join(part.text for part in response.candidates[0].content.parts)
content = content.strip()
# Sanitize and validate the output
content = sanitize_json_content(content)
if not validate_response(content):
if attempt < max_retries - 1:
root_logger.warning("Response validation failed, retrying...")
continue
return "[Error: Response validation failed]"
print("\n=== GEMINI PRO OUTPUT ===")
print(content)
print("=====================\n")
return content
except Exception as e:
error_msg = f"Gemini Pro API call failed: {str(e)}"
root_logger.error(f"{error_msg} (attempt {attempt + 1}/{max_retries})")
if attempt < max_retries - 1:
continue
return f"[Error: {error_msg}]"
return "[Error: All retry attempts failed]"
def call_deepseek_original(messages, model="deepseek-reasoner", temperature=0.1, fast_mode=False, max_retries=1, base_delay=2, timeout=90):
"""
Original DeepSeek caller with retry logic, timeout, model fallback, and response sanitization.
"""
# Override model choice if fast_mode is enabled
if fast_mode:
model = "deepseek-chat"
original_model = model # Store original model choice for potential fallback
for attempt in range(max_retries):
try:
if attempt > 0:
delay = base_delay * (2 ** (attempt - 1))
root_logger.info(f"Retry attempt {attempt + 1}/{max_retries} after {delay}s delay")
# If we've failed twice with reasoner, switch to chat model
if attempt >= 2 and original_model == "deepseek-reasoner":
model = "deepseek-chat"
root_logger.info("Switching to faster chat model after repeated failures")
time.sleep(delay)
print("\n=== DEEPSEEK INPUT ===")
messages_str = json.dumps(messages, indent=2)
if len(messages_str) > 5000:
print(messages_str[:3000] + "\n...[TRUNCATED]...\n" + messages_str[-2000:])
else:
print(messages_str)
print("=====================\n")
# Create a clean configuration for Fireworks API
client = openai.OpenAI(
api_key=FIREWORKS_API_KEY,
base_url="https://api.fireworks.ai/inference/v1",
http_client=httpx.Client(
trust_env=False,
timeout=httpx.Timeout(
timeout + 30, # Add 30 seconds buffer to the timeout
connect=min(30, timeout), # Cap connect timeout at 30s
read=timeout + 30, # Add buffer for read operations
write=min(30, timeout) # Cap write timeout at 30s
)
),
max_retries=0 # We handle retries ourselves
)
# Map DeepSeek model names to Fireworks model path
model_map = {
"deepseek-reasoner": "accounts/fireworks/models/deepseek-r1",
"deepseek-chat": "accounts/fireworks/models/deepseek-r1"
}
fireworks_model = model_map.get(model, "accounts/fireworks/models/deepseek-r1")
response = client.chat.completions.create(
model=fireworks_model,
messages=messages,
temperature=temperature,
#max_tokens=20480, # Removed as it's not a valid parameter
top_p=1,
presence_penalty=0,
frequency_penalty=0
)
try:
content = response.choices[0].message.content
except (AttributeError, IndexError, json.JSONDecodeError) as e:
root_logger.error(f"Failed to parse response: {str(e)}")
root_logger.debug(f"Raw response: {response}")
if attempt < max_retries - 1:
continue
return "[Error: Failed to parse response]"
content = sanitize_json_content(content)
if not validate_response(content):
if attempt < max_retries - 1:
root_logger.warning("Response validation failed, retrying...")
continue
return "[Error: Response validation failed]"
print("\n=== DEEPSEEK OUTPUT ===")
print(content)
print("=====================\n")
return content
except httpx.TimeoutException:
error_msg = f"DeepSeek API timeout after {timeout}s"
root_logger.error(f"{error_msg} (attempt {attempt + 1}/{max_retries})")
if model == "deepseek-reasoner":
model = "deepseek-chat"
root_logger.info("Timeout with reasoner model, switching to chat model")
if attempt < max_retries - 1:
continue
return f"[Error: {error_msg}]"
except openai.APIError as e:
error_msg = f"DeepSeek API error: {str(e)}"
root_logger.error(f"{error_msg} (attempt {attempt + 1}/{max_retries})")
if attempt < max_retries - 1:
continue
return f"[Error: {error_msg}]"
except openai.RateLimitError as e:
error_msg = f"DeepSeek rate limit exceeded: {str(e)}"
root_logger.error(f"{error_msg} (attempt {attempt + 1}/{max_retries})")
if attempt < max_retries - 1:
time.sleep(base_delay * 4) # Longer delay for rate limits
continue
return f"[Error: {error_msg}]"
except json.JSONDecodeError as e:
error_msg = f"Failed to parse JSON response: {str(e)}"
root_logger.error(f"{error_msg} (attempt {attempt + 1}/{max_retries})")
if attempt < max_retries - 1:
if model == "deepseek-reasoner":
model = "deepseek-chat"
root_logger.info("JSON parse error with reasoner model, switching to chat model")
continue
return f"[Error: {error_msg}]"
except Exception as e:
error_msg = f"DeepSeek API call failed: {str(e)}"
root_logger.error(f"{error_msg} (attempt {attempt + 1}/{max_retries})")
if attempt < max_retries - 1:
continue
return f"[Error: {error_msg}]"
return "[Error: All retry attempts failed]"
# Main interface function that routes to the appropriate implementation
def call_deepseek(*args, **kwargs):
"""
Main interface that routes to the chosen model implementation based on PREFERRED_MODEL setting.
You can also override via environment variable MODEL_CHOICE=o3mini|gemini|gemini_pro|deepseek
"""
# Check environment variable first, then fall back to PREFERRED_MODEL
model_choice = os.getenv("MODEL_CHOICE", PREFERRED_MODEL.value).lower()
if model_choice == ModelChoice.GEMINI_PRO.value:
return call_gemini_pro(*args, **kwargs)
elif model_choice == ModelChoice.GEMINI.value:
return call_gemini(*args, **kwargs)
elif model_choice == ModelChoice.DEEPSEEK.value:
return call_deepseek_original(*args, **kwargs)
else: # Default to O3MINI
return call_o3mini(*args, **kwargs)
def project_manager_agent(context, question, max_retries=3):
"""
Research Question Analyst with retry logic.
Uses the slower but more thorough reasoner model by default.
"""
messages = [
{"role": "system", "content": (
"You are a Research Question Analyst. Your role is to:\n"
"1. Break down complex research questions into their core components\n"
"2. Identify key concepts and relationships to be investigated\n"
"3. Highlight potential challenges in answering the question\n"