-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcate.py
More file actions
1954 lines (1619 loc) · 79.3 KB
/
cate.py
File metadata and controls
1954 lines (1619 loc) · 79.3 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 json
import json5
import random
import requests
import os
import sys
import time
import urllib3
from result import Ok, Err
from prompts import BUG_CATEGORIZATION_PROMPT
from cates import IS_REALLY_BUG_LOOKUP, USER_PERSPECTIVE_LOOKUP, DEVELOPER_PERSPECTIVE_LOOKUP, ACCELERATOR_SPECIFIC_LOOKUP, PLATFORM_SPECIFICITY_LOOKUP
from results_loader import load_categorized_results, get_categorized_urls
from issue import Issue
# Suppress SSL warnings when we fallback to unverified requests
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
CATEGORIZED_FILE_PATH = 'reference65.json'
USE_CATEGORIZED_FILE = True # Set to False to select fresh issues
# USE_CATEGORIZED_FILE = False # Set to False to select fresh issues
NUM_PER_FRAMEWORK = 10
# Options: "gemini", "gemini-pro", "ollama", "opus", "gpt5", "dummy"
# LLM_CHOICE = "gemini-pro"
# LLM_CHOICE = "dummy"
# LLM_CHOICE = "gpt5"
LLM_CHOICE = "opus"
# Conversation mode: When True, LLM can request additional information about mentioned issues/PRs
# When False, uses the old one-shot mode with all related content pre-fetched
CONVERSATION_MODE = True
# Verbose streaming: When True, prints ALL streaming data without truncation
VERBOSE_STREAMING = True
# GPT-5/OpenAI API Configuration
# Set to "openai" for official OpenAI API or "neko" for NekoAPI alternative
GPT_API_PROVIDER = "neko" # Options: "openai" or "neko"
NEKO_API_BASE = "https://nekoapi.com/v1" # NekoAPI endpoint
# Opus/Claude API Configuration
# Set to "anthropic" for official Anthropic API or "neko" for NekoAPI alternative
OPUS_API_PROVIDER = "neko" # Options: "anthropic" or "neko"
OLLAMA_MODEL = "qwen3:235b" # Change this to match your available model
def load_issues_from_categorized_file(categorized_file_path, issue_groups):
"""Load issues from a previously categorized JSON file."""
try:
with open(categorized_file_path, 'r') as f:
categorized_data = json5.load(f)
# Extract URLs from categorized data
all_selected_issues = []
for item in categorized_data:
# Find the original issue from issue_groups
found = False
for issues in issue_groups:
for issue in issues:
if issue.html_url == item['url']:
all_selected_issues.append(issue)
found = True
break
if found:
break
print(f"Loaded {len(all_selected_issues)} issues from {categorized_file_path}")
return all_selected_issues
except FileNotFoundError:
print(f"File not found: {categorized_file_path}")
return []
except json.JSONDecodeError:
print(f"Error decoding JSON from: {categorized_file_path}")
return []
def has_unwanted_labels(issue):
"""Check if issue has stale or awaiting response labels."""
if not hasattr(issue, 'labels'):
return False
for label in issue.labels:
label_name = label.get('name', '').lower()
if 'stale' in label_name or 'awaiting response' in label_name:
return True
return False
def has_closing_no_activity_comment(issue):
"""Check if the issue's last comment starts with 'Closing since no activity'."""
# First fetch comments if not already fetched
if not hasattr(issue, 'comments_data'):
fetch_issue_comments(issue)
# Check if there are any comments
if not hasattr(issue, 'comments_data') or not issue.comments_data:
return False
# Get the last comment
last_comment = issue.comments_data[-1]
comment_body = last_comment.get('body', '').strip()
# Check if it starts with "Closing since no activity" (case-insensitive)
return comment_body.lower().startswith('closing since no activity')
def select_random_uncategorized_issues(issue_groups, categorized_urls, num_per_framework=NUM_PER_FRAMEWORK):
"""Select random uncategorized issues from each framework."""
all_selected_issues = []
for issues in issue_groups:
# Find issues that haven't been categorized yet, have at least one comment,
# don't have unwanted labels, and don't have "closing since no activity" as last comment
uncategorized_issues = [issue for issue in issues
if issue.html_url not in categorized_urls
and hasattr(issue, 'comments_count')
and issue.comments_count > 0
and not has_unwanted_labels(issue)
and not has_closing_no_activity_comment(issue)]
num_to_select = min(num_per_framework, len(uncategorized_issues))
if num_to_select > 0:
selected_issues = random.sample(uncategorized_issues, num_to_select)
all_selected_issues.extend(selected_issues)
print(f"Selected {num_to_select} uncategorized issues with comments from framework")
else:
print(f"No uncategorized issues with comments available in this framework")
return all_selected_issues
def fetch_issue_comments(issue):
"""Fetch comments for a GitHub issue and store in the Issue object."""
# Extract owner, repo, and issue number from URL
# Example: https://github.com/pytorch/pytorch/issues/12345
parts = issue.html_url.replace('https://github.com/', '').split('/')
if len(parts) < 4 or parts[2] != 'issues':
return
owner = parts[0]
repo = parts[1]
issue_number = parts[3]
# Construct API URL for comments
api_url = f"https://api.github.com/repos/{owner}/{repo}/issues/{issue_number}/comments"
headers = {
'Accept': 'application/vnd.github.v3+json',
}
# Add GitHub token if available
github_token = os.getenv('GITHUB_TOKEN')
if github_token:
headers['Authorization'] = f'token {github_token}'
try:
response = requests.get(api_url, headers=headers)
# Handle rate limiting
if response.status_code == 403:
print(f"Rate limited when fetching comments. Waiting...")
time.sleep(60)
return
response.raise_for_status()
issue.comments_data = response.json()
except Exception as e:
print(f"Error fetching comments: {e}")
issue.comments_data = []
def print_issue(issue):
"""Pretty print a single issue in markdown format."""
print(f"### [{issue.title}]({issue.html_url})")
print()
# Print metadata
print(f"**Created:** {issue.created_at or 'Unknown'}")
print()
# Extract tag names from labels
tags = [label['name'] for label in issue.labels]
if tags:
print(f"**Tags:** `{' '.join(tags)}`")
else:
print("**Tags:** _(none)_")
print()
# Print issue body/content
if issue.body:
print("**Content:**")
print()
# Print full content without truncation
print("> " + issue.body.replace('\n', '\n> '))
else:
print("**Content:** _(empty)_")
# Print comments if available
if issue.comments_data:
print()
print(f"**Comments ({len(issue.comments_data)}):**")
print()
for i, comment in enumerate(issue.comments_data, 1):
print(f"#### Comment {i} by {comment.get('user', {}).get('login', 'Unknown')} at {comment.get('created_at', 'Unknown')}")
print()
if comment.get('body'):
print("> " + comment['body'].replace('\n', '\n> '))
else:
print("> _(empty comment)_")
print()
print()
print("---")
print() # Empty line for readability
def print_issues(issues):
"""Pretty print a list of issues in markdown format."""
for issue in issues:
print_issue(issue)
def load_framework_issues(fetch_timelines=False):
"""Load issues from all framework JSON files as Issue objects."""
frameworks = ['pytorch', 'tensorflow', 'jax', 'tensorrt', 'triton']
issue_groups = []
for framework in frameworks:
try:
with open(f'./issues/{framework}_issues.json', 'r') as f:
json_issues = json.load(f)
issues = [Issue.from_json(issue_data, fetch_timeline=fetch_timelines)
for issue_data in json_issues]
issue_groups.append(issues)
except FileNotFoundError:
print(f"{framework}: file not found")
return issue_groups
def parse_is_really_bug(code):
return IS_REALLY_BUG_LOOKUP.get(code)
def parse_user_perspective(code):
return USER_PERSPECTIVE_LOOKUP.get(code)
def parse_developer_perspective(code):
return DEVELOPER_PERSPECTIVE_LOOKUP.get(code)
def parse_accelerator_specific(code):
return ACCELERATOR_SPECIFIC_LOOKUP.get(code)
def parse_platform_specificity(code):
return PLATFORM_SPECIFICITY_LOOKUP.get(code)
def extract_github_urls_from_text(text, base_repo_url=None):
"""Extract GitHub issue and PR URLs from text content, including shorthand references.
Args:
text: Text content to search for URLs
base_repo_url: Base repository URL (e.g., "https://github.com/pytorch/pytorch")
for resolving shorthand references like #123
Returns:
List of GitHub issue/PR URLs found in the text
"""
import re
urls = []
# Debug: Check if we're looking at text with #10394 or #10395
# if '#10394' in text or '#10395' in text:
# print(f"DEBUG: Found #10394 or #10395 in text! Base repo: {base_repo_url}")
# print(f"DEBUG: Text snippet: {text[:200]}...")
# 1. Extract full GitHub URLs
full_url_pattern = r'https://github\.com/([\w\-]+)/([\w\-]+)/(?:issues|pull)/(\d+)'
full_urls = re.findall(full_url_pattern, text)
for owner, repo, number in full_urls:
urls.append(f'https://github.com/{owner}/{repo}/issues/{number}')
# 2. Extract cross-repo references (owner/repo#123)
cross_repo_pattern = r'(?:^|[^/\w])([\w\-]+)/([\w\-]+)#(\d+)'
cross_refs = re.findall(cross_repo_pattern, text)
for owner, repo, number in cross_refs:
# Validate that these look like real GitHub owner/repo names
if len(owner) > 0 and len(repo) > 0 and not owner.isdigit():
urls.append(f'https://github.com/{owner}/{repo}/issues/{number}')
# 3. Extract same-repo references (#123) - only if base_repo_url is provided
if base_repo_url:
# Clean up base URL to ensure it's in the right format
base_match = re.match(r'https://github\.com/([\w\-]+)/([\w\-]+)', base_repo_url)
if base_match:
base_owner, base_repo = base_match.groups()
# Match #123 style references (but not if part of owner/repo#123)
# Also exclude stack trace patterns like "#10 0x00007..."
# Stack traces have #N followed by space and hex address (0x...)
# Use word boundary after the number to ensure we get the full number
same_repo_pattern = r'(?:^|[^/\w])#(\d+)\b(?!\s+0x)'
same_repo_refs = re.findall(same_repo_pattern, text)
for number in same_repo_refs:
url = f'https://github.com/{base_owner}/{base_repo}/issues/{number}'
# if '10394' in number or '10395' in number:
# print(f"DEBUG: Extracted #{number} -> {url}")
urls.append(url)
# Remove duplicates while preserving order
seen = set()
unique_urls = []
for url in urls:
# Normalize /pull/ to /issues/ for consistency
url = url.replace('/pull/', '/issues/')
if url not in seen:
seen.add(url)
unique_urls.append(url)
return unique_urls
def fetch_mentioned_issue_content_recursive(url, cache={}, visited=None, depth=0, max_depth=3):
"""Recursively fetch content of mentioned issues/PRs with cycle detection.
Args:
url: GitHub issue/PR URL
cache: Dictionary to cache fetched content
visited: Set of URLs already being processed (for cycle detection)
depth: Current recursion depth
max_depth: Maximum recursion depth allowed
Returns:
Dictionary with 'content' (string) and 'related' (list of related content)
"""
# Initialize visited set if not provided
if visited is None:
visited = set()
# Debug: Track recursion for specific issues
# if '10394' in url or '10395' in url:
# print(f"DEBUG: Recursive fetch for {url} at depth {depth}")
# Check if we've reached max depth
if depth >= max_depth:
# if '10394' in url or '10395' in url:
# print(f"DEBUG: Max depth reached for {url}!")
return None
# Check for cycles
if url in visited:
print(f"Cycle detected: {url} already being processed")
return None
# Add to visited set
visited.add(url)
# Fetch the main content
content = fetch_mentioned_issue_content(url, cache)
if not content:
visited.remove(url) # Remove from visited if fetch failed
return None
# Extract base repo URL from the current URL for resolving shorthand references
import re
base_repo_match = re.match(r'(https://github\.com/[\w\-]+/[\w\-]+)', url)
base_repo_url = base_repo_match.group(1) if base_repo_match else None
# Extract URLs from the fetched content, including shorthand references
mentioned_urls = extract_github_urls_from_text(content, base_repo_url)
# Debug: Show what URLs were extracted
# if mentioned_urls and depth < 3:
# print(f"DEBUG: At depth {depth}, extracted {len(mentioned_urls)} URLs from {url}")
# for i, u in enumerate(mentioned_urls[:5]):
# print(f" {i+1}. {u}")
# Recursively fetch mentioned issues/PRs
related_content = []
# Debug: Show which URLs will be processed
# if mentioned_urls:
# print(f"DEBUG: Processing first 3 of {len(mentioned_urls)} URLs at depth {depth}")
# for i, u in enumerate(mentioned_urls[:3]):
# status = "SKIP (visited)" if u in visited else "FETCH"
# print(f" {i+1}. {u} - {status}")
for mentioned_url in mentioned_urls[:3]: # Limit to 3 related items per level
if mentioned_url not in visited: # Skip if already visited
# if '10394' in mentioned_url or '10395' in mentioned_url:
# print(f"DEBUG: About to recursively fetch {mentioned_url} at depth {depth+1}")
related = fetch_mentioned_issue_content_recursive(
mentioned_url, cache, visited, depth + 1, max_depth
)
if related:
# Extract issue/PR number from URL for labeling
import re
match = re.search(r'/(\d+)$', mentioned_url)
number = match.group(1) if match else "Unknown"
issue_or_pr = "PULL REQUEST" if '/pull/' in mentioned_url else "ISSUE"
related_item = {
'url': mentioned_url,
'number': number,
'type': issue_or_pr,
'depth': depth + 1,
'content': related['content'] if isinstance(related, dict) else related,
'related': related.get('related', []) if isinstance(related, dict) else []
}
related_content.append(related_item)
# Remove from visited set after processing
visited.remove(url)
return {
'content': content,
'related': related_content
}
def fetch_mentioned_issue_content(url, cache={}):
"""Fetch the content of a mentioned issue or PR from GitHub API.
Args:
url: GitHub issue/PR URL
cache: Dictionary to cache fetched content
Returns:
String containing the issue/PR content or None if failed
"""
# Check cache first
if url in cache:
return cache[url]
# Convert HTML URL to API URL
# Example: https://github.com/pytorch/pytorch/issues/123 -> https://api.github.com/repos/pytorch/pytorch/issues/123
if not url.startswith('https://github.com/'):
return None
api_url = url.replace('https://github.com/', 'https://api.github.com/repos/')
api_url = api_url.replace('/pull/', '/pulls/') # Handle PRs
headers = {'Accept': 'application/vnd.github.v3+json'}
github_token = os.getenv('GITHUB_TOKEN')
if github_token:
headers['Authorization'] = f'token {github_token}'
# Retry logic for SSL and connection errors
max_retries = 3
retry_delay = 1
for attempt in range(max_retries):
try:
# Add timeout to prevent hanging
response = requests.get(api_url, headers=headers, timeout=30)
# Handle rate limiting
if response.status_code == 403:
print(f"Rate limited when fetching {url}")
return None
if response.status_code == 200:
data = response.json()
# Build content string
content = f"Title: {data.get('title', 'Unknown')}\n"
content += f"State: {data.get('state', 'unknown')}\n"
content += f"Created: {data.get('created_at', 'unknown')}\n"
# Add labels
labels = data.get('labels', [])
if labels:
label_names = [label['name'] for label in labels]
content += f"Labels: {', '.join(label_names)}\n"
# Add body
body = data.get('body', '')
if body:
content += f"\nDescription:\n{body}\n"
else:
content += "\nDescription: (empty)\n"
# Fetch first few comments (limit to 3 to avoid huge prompts)
comments_url = data.get('comments_url')
if comments_url:
try:
comments_response = requests.get(comments_url, headers=headers, timeout=30)
if comments_response.status_code == 200:
comments = comments_response.json()[:3] # Limit to first 3 comments
if comments:
content += f"\nFirst {len(comments)} comments:\n"
for i, comment in enumerate(comments, 1):
user = comment.get('user', {}).get('login', 'Unknown')
body = comment.get('body', '(empty)')
content += f"\nComment {i} by {user}:\n{body}\n"
# Debug: Check if this comment mentions our issues
# if '#10394' in body or '#10395' in body:
# print(f"DEBUG: Comment {i} by {user} mentions #10394 or #10395!")
# print(f"DEBUG: Comment text: {body[:200]}...")
except:
pass # Ignore comment fetching errors
# For Pull Requests, fetch the diff
if '/pull/' in url:
try:
# Use the diff endpoint for the PR
diff_headers = headers.copy()
diff_headers['Accept'] = 'application/vnd.github.v3.diff'
diff_response = requests.get(api_url, headers=diff_headers, timeout=30)
if diff_response.status_code == 200:
diff_text = diff_response.text
# Limit diff size to avoid overwhelming the prompt
max_diff_length = 3000
if len(diff_text) > max_diff_length:
diff_text = diff_text[:max_diff_length] + "\n... (diff truncated)"
content += "\n=== CODE CHANGES (DIFF) ===\n"
content += diff_text
content += "\n"
except Exception as e:
print(f"Failed to fetch diff for PR {url}: {e}")
# Continue without diff if it fails
# Cache the result
cache[url] = content
return content
except requests.exceptions.SSLError as e:
if attempt < max_retries - 1:
print(f"SSL error fetching {url}, retrying in {retry_delay}s... (attempt {attempt + 1}/{max_retries})")
time.sleep(retry_delay)
retry_delay *= 2
else:
# Last attempt - try without SSL verification
try:
print(f"SSL verification failed for {url}, trying without verification...")
response = requests.get(api_url, headers=headers, timeout=30, verify=False)
if response.status_code == 200:
data = response.json()
# Build minimal content without comments
content = f"Title: {data.get('title', 'Unknown')}\n"
content += f"State: {data.get('state', 'unknown')}\n"
body = data.get('body', '')
if body:
content += f"\nDescription:\n{body[:500]}...\n" if len(body) > 500 else f"\nDescription:\n{body}\n"
cache[url] = content
return content
except:
print(f"Failed to fetch {url} even without SSL verification")
return None
except requests.exceptions.Timeout:
print(f"Timeout fetching {url} (attempt {attempt + 1}/{max_retries})")
if attempt >= max_retries - 1:
return None
time.sleep(retry_delay)
retry_delay *= 2
except requests.exceptions.ConnectionError as e:
print(f"Connection error fetching {url}: {e}")
if attempt >= max_retries - 1:
return None
time.sleep(retry_delay)
retry_delay *= 2
except Exception as e:
print(f"Unexpected error fetching {url}: {e}")
return None
return None
def parse_information_request(text):
"""Parse LLM response to extract requested issue/PR numbers.
Returns:
List of issue/PR numbers that the LLM is requesting information about, or None if this is a final answer
"""
import re
# Check if this looks like a final answer (contains the categorization codes)
if is_final_answer(text):
return None
matches = []
# Look for explicit requests in format "REQUEST: issue #1234" or "REQUEST: PR #5678"
request_pattern = r'REQUEST:\s*(?:issue|pr|pull request)\s*#(\d+)'
matches.extend(re.findall(request_pattern, text, re.IGNORECASE))
# Also look for questions about specific issues/PRs
question_pattern = r'(?:can you|could you|please)\s+(?:provide|show|fetch|get).*?(?:issue|pr|pull request)\s*#(\d+)'
matches.extend(re.findall(question_pattern, text, re.IGNORECASE))
# Look for "I need more information about #1234" patterns
info_pattern = r'(?:need|want|require)\s+(?:more\s+)?(?:information|details|context).*?#(\d+)'
matches.extend(re.findall(info_pattern, text, re.IGNORECASE))
return list(set(matches)) if matches else None # Remove duplicates and return None if empty
def is_final_answer(text):
"""Check if the LLM response contains a final categorization answer."""
import re
# Look for the expected final line format: "1.x, 2.x, 3.x, 4.x, 5.x"
pattern = r'[1-5]\.[a-i],\s*[1-5]\.[a-i],\s*[1-5]\.[a-i],\s*[1-5]\.[a-i],\s*[1-5]\.[a-i]'
# Check if pattern exists in the text
return bool(re.search(pattern, text))
def is_acknowledgment(text):
"""Check if the LLM response is acknowledging understanding of the framework."""
text_lower = text.lower()
# Check for various acknowledgment patterns
acknowledgment_phrases = [
"acknowledged",
"i understand",
"understood",
"ready to analyze",
"please provide the",
"provide the github issue",
"send the issue",
"ready to categorize",
"i'm ready",
"framework understood"
]
return any(phrase in text_lower for phrase in acknowledgment_phrases)
def prepare_minimal_prompt(issue):
"""Prepare a minimal prompt with just the issue content (no related issues)."""
# Fetch timeline and comments for this specific issue
if hasattr(issue, 'fetch_timeline'):
issue.fetch_timeline()
# Collect mentions but don't fetch them
issue.collect_all_mentions()
issue_content = issue.to_string_pretty()
return issue_content
class SSEStreamHandler:
"""Handle Server-Sent Events from Claude API streaming responses."""
def __init__(self, debug_mode=False):
self.text_content = ""
self.thinking_content = ""
self.current_block_type = None
self.debug_mode = debug_mode
self.event_count = 0
self.error_occurred = False
self.error_message = None
# Stream metadata tracking
self.stream_start_time = None
self.stream_end_time = None
self.first_token_time = None
self.chunk_count = 0
self.chunk_sizes = []
self.event_types_seen = {}
self.message_id = None
self.model = None
self.usage_stats = {}
def process_stream(self, response):
"""Process the entire SSE stream from the response."""
import datetime
self.stream_start_time = datetime.datetime.now()
buffer = ""
line_count = 0
if VERBOSE_STREAMING:
print(f"\n{'='*100}")
print("[STREAM PROCESSING START]")
print(f"[START TIME] {self.stream_start_time.isoformat()}")
print(f"[RESPONSE HEADERS]")
for header, value in response.headers.items():
print(f" {header}: {value}")
print(f"{'='*100}")
try:
# Process stream line by line
for line in response.iter_lines():
line_count += 1
# Decode line if it's bytes
line_str = line.decode('utf-8') if isinstance(line, bytes) else line if line else ''
if VERBOSE_STREAMING and line_str:
print(f"[RAW LINE #{line_count}] {line_str}")
elif VERBOSE_STREAMING and not line_str:
print(f"[RAW LINE #{line_count}] <empty line>")
# Check for empty line FIRST (signals end of SSE message)
if not line_str or line_str == '':
if buffer:
if VERBOSE_STREAMING:
print(f"\n[SSE MESSAGE COMPLETE] Processing buffered message:")
print(f"[BUFFER CONTENT]\n{buffer}")
self._process_sse_message(buffer)
buffer = ""
# SSE format: lines starting with "event:" or "data:"
elif line_str.startswith('event:') or line_str.startswith('data:'):
buffer += line_str + '\n'
# Process any remaining buffer
if buffer:
if VERBOSE_STREAMING:
print(f"\n[FINAL BUFFER] Processing remaining buffer:")
print(f"[BUFFER CONTENT]\n{buffer}")
self._process_sse_message(buffer)
# Stream completed
self.stream_end_time = datetime.datetime.now()
if VERBOSE_STREAMING:
self._print_final_stream_statistics()
except Exception as e:
self.error_occurred = True
self.error_message = f"Stream processing error: {e}"
self.stream_end_time = datetime.datetime.now()
print(f"[ERROR] {self.error_message}")
import traceback
print(f"[TRACEBACK]\n{traceback.format_exc()}")
if VERBOSE_STREAMING and not self.stream_end_time:
self.stream_end_time = datetime.datetime.now()
print(f"\n{'='*80}")
print("[STREAM PROCESSING END]")
print(f" Processed {line_count} total lines")
print(f" Final text length: {len(self.text_content)} chars")
print(f" Final thinking length: {len(self.thinking_content)} chars")
print(f"{'='*80}")
return self.text_content, self.thinking_content
def _process_sse_message(self, message):
"""Process a single SSE message (event + data pair)."""
if VERBOSE_STREAMING:
print(f"\n[PARSING SSE MESSAGE]")
lines = message.strip().split('\n')
event_type = None
event_data = None
for line in lines:
if VERBOSE_STREAMING:
print(f" [PARSING LINE] {line}")
if line.startswith('event:'):
event_type = line[6:].strip()
if VERBOSE_STREAMING:
print(f" [EVENT TYPE FOUND] {event_type}")
elif line.startswith('data:'):
try:
data_str = line[5:].strip()
if data_str:
event_data = json.loads(data_str)
if VERBOSE_STREAMING:
print(f" [DATA PARSED] Success")
# Print FULL JSON without truncation
print(f" [FULL JSON DATA]\n{json.dumps(event_data, indent=2)}")
except json.JSONDecodeError as e:
print(f" [WARNING] Failed to parse JSON: {e}")
print(f" [RAW DATA STRING] {data_str}")
continue
if event_type and event_data:
if VERBOSE_STREAMING:
print(f" [HANDLING EVENT] Type: {event_type}")
self._handle_event(event_type, event_data)
else:
if VERBOSE_STREAMING:
print(f" [SKIPPED] Missing event_type or event_data")
def _handle_event(self, event_type, data):
"""Handle specific SSE events based on Anthropic's streaming format."""
self.event_count += 1
import datetime
# Track event types
if event_type not in self.event_types_seen:
self.event_types_seen[event_type] = 0
self.event_types_seen[event_type] += 1
if VERBOSE_STREAMING:
# Print FULL event details
print(f"\n{'='*80}")
print(f"[EVENT #{self.event_count}] Type: {event_type}")
print(f"[TIMESTAMP] {datetime.datetime.now().isoformat()}")
print(f"[FULL EVENT DATA]")
print(json.dumps(data, indent=2))
print(f"{'='*80}")
# Handle different event types according to Anthropic's SSE format
if event_type == 'message_start':
# Initial message with metadata
message_data = data.get('message', {})
self.message_id = message_data.get('id')
self.model = message_data.get('model')
self.usage_stats = message_data.get('usage', {})
if VERBOSE_STREAMING:
print(f"[MESSAGE START] Initial message with metadata")
print(f"[MESSAGE ID] {self.message_id}")
print(f"[MODEL] {self.model}")
print(f"[ROLE] {message_data.get('role', 'N/A')}")
print(f"[STOP REASON] {message_data.get('stop_reason', 'N/A')}")
print(f"[INITIAL USAGE] {json.dumps(self.usage_stats, indent=2)}")
elif event_type == 'content_block_start':
# Start of a new content block
block = data.get('content_block', {})
self.current_block_type = block.get('type')
if VERBOSE_STREAMING:
print(f"[CONTENT BLOCK START] Type: {self.current_block_type}")
print(f"[BLOCK INDEX] {data.get('index', 'N/A')}")
print(f"[FULL BLOCK DATA] {json.dumps(block, indent=2)}")
elif event_type == 'content_block_delta':
# Incremental content updates
delta = data.get('delta', {})
delta_type = delta.get('type')
if delta_type == 'text_delta':
text = delta.get('text', '')
self.text_content += text
self.chunk_count += 1
self.chunk_sizes.append(len(text))
# Track time to first token
if not self.first_token_time and text:
self.first_token_time = datetime.datetime.now()
if VERBOSE_STREAMING:
print(f"[TEXT DELTA RECEIVED - Chunk #{self.chunk_count}]")
print(f" Chunk size: {len(text)} chars")
print(f" Chunk content (repr): {repr(text)}") # Using repr to see escape chars
print(f" Total text accumulated: {len(self.text_content)} chars")
print(f" Average chunk size: {sum(self.chunk_sizes)/len(self.chunk_sizes):.1f} chars")
if self.first_token_time:
elapsed = (datetime.datetime.now() - self.first_token_time).total_seconds()
print(f" Time since first token: {elapsed:.2f}s")
# Print FULL accumulated text so far
print(f"[ACCUMULATED TEXT SO FAR - COMPLETE]\n{self.text_content}")
elif not self.debug_mode:
# Still print text as it arrives for non-verbose mode
print(text, end='', flush=True)
elif delta_type == 'thinking_delta':
thinking_text = delta.get('text', '')
self.thinking_content += thinking_text
self.chunk_count += 1
self.chunk_sizes.append(len(thinking_text))
if VERBOSE_STREAMING:
print(f"[THINKING DELTA RECEIVED]")
print(f" Chunk size: {len(thinking_text)} chars")
# Print FULL thinking chunk
print(f" Chunk content (repr): {repr(thinking_text)}")
print(f" Total thinking accumulated: {len(self.thinking_content)} chars")
# Print FULL accumulated thinking (no truncation)
print(f"[ACCUMULATED THINKING SO FAR - COMPLETE]\n{self.thinking_content}")
elif event_type == 'content_block_stop':
# End of content block
if VERBOSE_STREAMING:
print(f"[CONTENT BLOCK STOP] Block type was: {self.current_block_type}")
print(f"[BLOCK INDEX] {data.get('index', 'N/A')}")
self.current_block_type = None
elif event_type == 'message_delta':
# Top-level message changes (usage stats, etc.)
new_usage = data.get('usage', {})
if new_usage:
self.usage_stats.update(new_usage)
if VERBOSE_STREAMING:
print(f"[MESSAGE DELTA] Top-level message changes")
if new_usage:
print(f" Updated usage stats:")
print(f" Output tokens: {new_usage.get('output_tokens', 'N/A')}")
print(f" Cache creation input tokens: {new_usage.get('cache_creation_input_tokens', 'N/A')}")
print(f" Cache read input tokens: {new_usage.get('cache_read_input_tokens', 'N/A')}")
print(f" Full usage: {json.dumps(new_usage, indent=2)}")
delta_content = data.get('delta', {})
if delta_content:
print(f" Delta content: {json.dumps(delta_content, indent=2)}")
elif event_type == 'message_stop':
# End of message
if VERBOSE_STREAMING:
print(f"\n{'='*100}")
print(f"[MESSAGE COMPLETE - FINAL SUMMARY]")
print(f" Message ID: {self.message_id}")
print(f" Model: {self.model}")
print(f" Total events processed: {self.event_count}")
print(f" Total chunks received: {self.chunk_count}")
print(f" Final text length: {len(self.text_content)} chars")
print(f" Final thinking length: {len(self.thinking_content)} chars")
print(f"\n[EVENT TYPE DISTRIBUTION]")
for evt_type, count in sorted(self.event_types_seen.items()):
print(f" {evt_type}: {count} occurrences")
print(f"\n[FINAL USAGE STATISTICS]")
print(json.dumps(self.usage_stats, indent=2))
print(f"\n[COMPLETE TEXT CONTENT - NO TRUNCATION]\n{self.text_content}")
print(f"\n[COMPLETE THINKING CONTENT - NO TRUNCATION]\n{self.thinking_content}")
print(f"{'='*100}")
elif not self.debug_mode:
print() # New line after streaming text
elif event_type == 'error':
# Error event
self.error_occurred = True
self.error_message = data.get('message', 'Unknown error')
error_type = data.get('type', 'unknown')
print(f"\n[ERROR EVENT]")
print(f" Error type: {error_type}")
print(f" Error message: {self.error_message}")
print(f" Full error data: {json.dumps(data, indent=2)}")
elif event_type == 'ping':
# Keep-alive ping
if VERBOSE_STREAMING:
print(f"[PING] Keep-alive signal received at {datetime.datetime.now().isoformat()}")
def _print_final_stream_statistics(self):
"""Print comprehensive streaming statistics after completion."""
print(f"\n{'='*120}")
print("[FINAL STREAM STATISTICS]")
print(f"{'='*120}")
# Timing statistics
print("\n[TIMING INFORMATION]")
print(f" Stream Start: {self.stream_start_time.isoformat()}")
print(f" Stream End: {self.stream_end_time.isoformat()}")
total_duration = (self.stream_end_time - self.stream_start_time).total_seconds()
print(f" Total Duration: {total_duration:.2f} seconds")
if self.first_token_time:
time_to_first = (self.first_token_time - self.stream_start_time).total_seconds()
print(f" Time to First Token: {time_to_first:.3f} seconds")
generation_time = (self.stream_end_time - self.first_token_time).total_seconds()
print(f" Generation Time: {generation_time:.2f} seconds")
# Content statistics
print("\n[CONTENT STATISTICS]")
print(f" Total Text Characters: {len(self.text_content):,}")
print(f" Total Thinking Characters: {len(self.thinking_content):,}")
print(f" Total Combined Characters: {len(self.text_content) + len(self.thinking_content):,}")
# Chunk statistics
print("\n[CHUNK STATISTICS]")
print(f" Total Chunks: {self.chunk_count}")
if self.chunk_sizes:
print(f" Average Chunk Size: {sum(self.chunk_sizes)/len(self.chunk_sizes):.1f} chars")
print(f" Min Chunk Size: {min(self.chunk_sizes)} chars")
print(f" Max Chunk Size: {max(self.chunk_sizes)} chars")
print(f" Total Chunk Data: {sum(self.chunk_sizes):,} chars")
# Throughput calculations
if total_duration > 0:
print("\n[THROUGHPUT METRICS]")
chars_per_second = (len(self.text_content) + len(self.thinking_content)) / total_duration
print(f" Characters per Second: {chars_per_second:.1f}")
if self.chunk_count > 0:
chunks_per_second = self.chunk_count / total_duration
print(f" Chunks per Second: {chunks_per_second:.1f}")
# Event distribution
print("\n[EVENT DISTRIBUTION]")
for event_type, count in sorted(self.event_types_seen.items()):
percentage = (count / self.event_count) * 100 if self.event_count > 0 else 0
print(f" {event_type}: {count} ({percentage:.1f}%)")
# Token usage summary
print("\n[TOKEN USAGE SUMMARY]")
if self.usage_stats:
print(f" Input Tokens: {self.usage_stats.get('input_tokens', 'N/A')}")
print(f" Output Tokens: {self.usage_stats.get('output_tokens', 'N/A')}")
print(f" Cache Creation Input Tokens: {self.usage_stats.get('cache_creation_input_tokens', 'N/A')}")
print(f" Cache Read Input Tokens: {self.usage_stats.get('cache_read_input_tokens', 'N/A')}")
# Calculate token rate if we have output tokens
output_tokens = self.usage_stats.get('output_tokens')
if output_tokens and total_duration > 0:
tokens_per_second = output_tokens / total_duration
print(f" Token Generation Rate: {tokens_per_second:.1f} tokens/second")
# Model and message info
print("\n[MESSAGE METADATA]")
print(f" Message ID: {self.message_id or 'N/A'}")
print(f" Model: {self.model or 'N/A'}")
# Error status
print("\n[COMPLETION STATUS]")
if self.error_occurred:
print(f" Status: ERROR")
print(f" Error Message: {self.error_message}")
else:
print(f" Status: SUCCESS")
print(f"\n{'='*120}")
def prepare_conversation_prompt():
"""Create the conversation-aware prompt that allows the LLM to request information."""
# Load the standard prompt first