-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnodes.py
More file actions
1456 lines (1272 loc) · 58.6 KB
/
nodes.py
File metadata and controls
1456 lines (1272 loc) · 58.6 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 re
import yaml
from concurrent.futures import ThreadPoolExecutor, as_completed
from pocketflow import Node, BatchNode
from utils.crawl_github_files import crawl_github_files
from utils.call_llm import call_llm
from utils.crawl_local_files import crawl_local_files
from utils.semantic_chunks import (
build_chunk_catalog,
build_compact_chunk_catalog,
build_chunk_inventory,
deterministic_plan_batches,
extract_file_indices,
format_chunks_for_prompt,
pack_chunks_for_prompt,
select_chunks_by_ids,
sort_files_items,
)
LLM_PLANNER_MAX_CHUNKS = 250
LLM_PLANNER_MAX_CATALOG_CHARS = 60000
MAX_LLM_EXTRACTION_BATCHES = 40
DEFAULT_LLM_EXTRACTION_CONCURRENCY = 1
DEFAULT_TUTORIAL_LANGUAGE = "Chinese"
def _positive_int(value, default):
try:
parsed = int(value)
except (TypeError, ValueError):
return default
return parsed if parsed > 0 else default
def _env_positive_int(name, default):
return _positive_int(os.getenv(name), default)
def _extraction_metadata(
project_name,
batch,
batch_index,
batch_total,
chunk_group_index,
chunk_group_total,
chunk_count,
):
return {
"project_name": project_name,
"batch_index": batch_index,
"batch_total": batch_total,
"batch_name": batch.get("name", "Code Chunk Batch"),
"chunk_group_index": chunk_group_index,
"chunk_group_total": chunk_group_total,
"chunk_count": chunk_count,
}
# Helper to get content for specific file indices
def get_content_for_indices(files_data, indices):
content_map = {}
for i in indices:
if 0 <= i < len(files_data):
path, content = files_data[i]
content_map[f"{i} # {path}"] = (
content # Use index + path as key for context
)
return content_map
class FetchRepo(Node):
def prep(self, shared):
repo_url = shared.get("repo_url")
local_dir = shared.get("local_dir")
project_name = shared.get("project_name")
if not project_name:
# Basic name derivation from URL or directory
if repo_url:
project_name = repo_url.split("/")[-1].replace(".git", "")
else:
project_name = os.path.basename(os.path.abspath(local_dir))
shared["project_name"] = project_name
# Get file patterns directly from shared
include_patterns = shared["include_patterns"]
exclude_patterns = shared["exclude_patterns"]
max_file_size = shared["max_file_size"]
return {
"repo_url": repo_url,
"local_dir": local_dir,
"token": shared.get("github_token"),
"include_patterns": include_patterns,
"exclude_patterns": exclude_patterns,
"max_file_size": max_file_size,
"use_relative_paths": True,
}
def exec(self, prep_res):
if prep_res["repo_url"]:
print(f"Crawling repository: {prep_res['repo_url']}...")
result = crawl_github_files(
repo_url=prep_res["repo_url"],
token=prep_res["token"],
include_patterns=prep_res["include_patterns"],
exclude_patterns=prep_res["exclude_patterns"],
max_file_size=prep_res["max_file_size"],
use_relative_paths=prep_res["use_relative_paths"],
)
else:
print(f"Crawling directory: {prep_res['local_dir']}...")
result = crawl_local_files(
directory=prep_res["local_dir"],
include_patterns=prep_res["include_patterns"],
exclude_patterns=prep_res["exclude_patterns"],
max_file_size=prep_res["max_file_size"],
use_relative_paths=prep_res["use_relative_paths"]
)
# Convert dict to stable list of tuples: [(path, content), ...]
files_list = sort_files_items(result.get("files", {}).items())
if len(files_list) == 0:
raise (ValueError("Failed to fetch files"))
print(f"Fetched {len(files_list)} files.")
return files_list
def post(self, shared, prep_res, exec_res):
shared["files"] = exec_res # List of (path, content) tuples
class IdentifyAbstractions(Node):
def prep(self, shared):
files_data = shared["files"]
project_name = shared["project_name"] # Get project name
language = shared.get("language", DEFAULT_TUTORIAL_LANGUAGE) # Get language
use_cache = shared.get("use_cache", True) # Get use_cache flag, default to True
max_abstraction_num = shared.get("max_abstraction_num", 10) # Get max_abstraction_num, default to 10
max_extraction_batches = _positive_int(
shared.get("max_extraction_batches"),
_env_positive_int("LLM_MAX_EXTRACTION_BATCHES", MAX_LLM_EXTRACTION_BATCHES),
)
llm_extraction_concurrency = _positive_int(
shared.get("llm_extraction_concurrency"),
_env_positive_int("LLM_EXTRACTION_CONCURRENCY", DEFAULT_LLM_EXTRACTION_CONCURRENCY),
)
chunk_inventory = build_chunk_inventory(files_data)
if not chunk_inventory:
raise ValueError("No semantic chunks were produced from fetched files")
return {
"chunk_inventory": chunk_inventory,
"file_count": len(files_data),
"project_name": project_name,
"language": language,
"use_cache": use_cache,
"max_abstraction_num": max_abstraction_num,
"max_extraction_batches": max_extraction_batches,
"llm_extraction_concurrency": llm_extraction_concurrency,
}
def exec(self, prep_res):
chunk_inventory = prep_res["chunk_inventory"]
file_count = prep_res["file_count"]
project_name = prep_res["project_name"]
language = prep_res["language"]
use_cache = prep_res["use_cache"]
max_abstraction_num = prep_res["max_abstraction_num"]
max_extraction_batches = prep_res.get(
"max_extraction_batches", MAX_LLM_EXTRACTION_BATCHES
)
llm_extraction_concurrency = prep_res.get(
"llm_extraction_concurrency", DEFAULT_LLM_EXTRACTION_CONCURRENCY
)
print(f"Identifying abstractions using LLM...")
try:
candidates = self._identify_with_compact_catalog(
project_name,
chunk_inventory,
language,
use_cache,
max_abstraction_num,
)
except (ValueError, yaml.YAMLError) as exc:
print(f"Compact catalog identification failed; using batch fallback: {exc}")
candidates = self._identify_with_batch_fallback(
project_name,
chunk_inventory,
language,
use_cache,
max_extraction_batches,
llm_extraction_concurrency,
)
validated_abstractions = self._validate_and_merge(
candidates,
chunk_inventory,
file_count,
max_abstraction_num,
)
print(f"Identified {len(validated_abstractions)} abstractions.")
return validated_abstractions
def post(self, shared, prep_res, exec_res):
shared["abstractions"] = (
exec_res # List of {"name": str, "description": str, "files": [int]}
)
def _identify_with_compact_catalog(
self,
project_name,
chunk_inventory,
language,
use_cache,
max_abstraction_num,
):
plan = self._plan_compact_abstractions(
project_name,
chunk_inventory,
language,
use_cache,
max_abstraction_num,
)
selected_chunks = select_chunks_by_ids(
chunk_inventory,
_planned_supporting_ids(plan, chunk_inventory),
)
if not selected_chunks:
raise ValueError("Compact planner selected no valid evidence chunks")
return self._refine_compact_abstractions(
project_name,
plan,
selected_chunks,
language,
use_cache,
max_abstraction_num,
)
def _identify_with_batch_fallback(
self,
project_name,
chunk_inventory,
language,
use_cache,
max_extraction_batches,
llm_extraction_concurrency,
):
batches = self._plan_batches(
project_name,
chunk_inventory,
use_cache,
max_extraction_batches,
)
jobs = self._build_extraction_jobs(project_name, chunk_inventory, batches)
return self._extract_batch_jobs(
jobs,
project_name,
language,
use_cache,
llm_extraction_concurrency,
)
def _plan_compact_abstractions(
self,
project_name,
chunk_inventory,
language,
use_cache,
max_abstraction_num,
):
language_instruction = ""
if language.lower() != "english":
language_instruction = (
f"Generate candidate `name` values in {language.capitalize()}.\n\n"
)
prompt = f"""
For the project `{project_name}`, choose a small set of tutorial-worthy code abstractions from this compact semantic chunk catalog.
Compact catalog:
{build_compact_chunk_catalog(chunk_inventory)}
{language_instruction}Select at most {max_abstraction_num} middle-level concepts that are useful for onboarding.
Prefer entrypoints, model/workflow orchestration, public APIs, configuration, providers, data models, schedulers, stores, or core adapters.
Use only chunk_id values from the catalog. Do not choose test-only, demo-only, or trivial utility chunks unless they explain core wiring.
Format the output as YAML:
```yaml
abstractions:
- name: |
Routing Layer
reason: |
Explains how request routes connect to handlers.
supporting_chunk_ids:
- "00003:src/router.ts:entity:0"
- "00003:src/router.ts:misc:0"
```
"""
response = call_llm(
prompt,
use_cache=(use_cache and self.cur_retry == 0),
stage="identify.compact_plan",
metadata={
"project_name": project_name,
"chunk_count": len(chunk_inventory),
"max_abstraction_num": max_abstraction_num,
},
)
data = _load_yaml_block(response)
candidates = data.get("abstractions") if isinstance(data, dict) else data
return _validate_compact_plan(candidates, chunk_inventory, max_abstraction_num)
def _refine_compact_abstractions(
self,
project_name,
plan,
selected_chunks,
language,
use_cache,
max_abstraction_num,
):
prompt = _compact_refinement_prompt(
project_name,
plan,
selected_chunks,
language,
max_abstraction_num,
)
response = call_llm(
prompt,
use_cache=(use_cache and self.cur_retry == 0),
stage="identify.refine",
metadata={
"project_name": project_name,
"planned_abstractions": len(plan),
"selected_chunk_count": len(selected_chunks),
"max_abstraction_num": max_abstraction_num,
},
)
data = _load_yaml_block(response)
abstractions = data.get("abstractions") if isinstance(data, dict) else data
if not isinstance(abstractions, list):
raise ValueError("Refined abstraction output is not a list")
return abstractions
def _build_extraction_jobs(self, project_name, chunk_inventory, batches):
jobs = []
for batch_index, batch in enumerate(batches):
packed_batches = pack_chunks_for_prompt(chunk_inventory, batch["chunk_ids"])
for chunk_group_index, chunk_group in enumerate(packed_batches):
jobs.append(
{
"ordinal": len(jobs),
"batch": batch,
"chunks": chunk_group,
"metadata": _extraction_metadata(
project_name,
batch,
batch_index,
len(batches),
chunk_group_index,
len(packed_batches),
len(chunk_group),
),
}
)
return jobs
def _plan_batches(
self,
project_name,
chunk_inventory,
use_cache,
max_extraction_batches=None,
):
max_batches = _positive_int(max_extraction_batches, MAX_LLM_EXTRACTION_BATCHES)
if len(chunk_inventory) > LLM_PLANNER_MAX_CHUNKS:
print(
"Chunk inventory is large "
f"({len(chunk_inventory)} chunks); using deterministic bounded planning."
)
return deterministic_plan_batches(
chunk_inventory,
max_batches=max_batches,
)
chunk_catalog = build_chunk_catalog(chunk_inventory)
if len(chunk_catalog) > LLM_PLANNER_MAX_CATALOG_CHARS:
print(
"Chunk catalog is large "
f"({len(chunk_catalog)} chars); using deterministic bounded planning."
)
return deterministic_plan_batches(
chunk_inventory,
max_batches=max_batches,
)
chunk_ids = {chunk["chunk_id"] for chunk in chunk_inventory}
prompt = f"""
For the project `{project_name}`, plan semantic code chunk batches for abstraction discovery.
Chunk catalog:
{chunk_catalog}
Group related chunks into prompt-safe batches. Prefer middle-level code concepts that
map to symbols, scopes, routing, registration, configuration, orchestration, or data flow.
Include misc chunks when they explain wiring, imports, module-level constants, config,
registration, or dependency injection. Use only chunk_id values listed above.
Format the output as YAML:
```yaml
batches:
- name: |
Request Routing Layer
reason: |
Groups route registration and handler dispatch symbols.
chunk_ids:
- "00003:src/router.ts:entity:0"
- "00003:src/router.ts:misc:0"
```
"""
response = call_llm(
prompt,
use_cache=(use_cache and self.cur_retry == 0),
stage="identify.plan",
metadata={
"project_name": project_name,
"chunk_count": len(chunk_inventory),
"max_extraction_batches": max_batches,
},
)
try:
data = _load_yaml_block(response)
batches = data.get("batches") if isinstance(data, dict) else None
return _validate_batches(batches, chunk_ids)
except (ValueError, yaml.YAMLError) as exc:
print(f"Chunk planning failed; using deterministic fallback: {exc}")
return deterministic_plan_batches(chunk_inventory, max_batches=max_batches)
def _extract_batch_jobs(
self,
jobs,
project_name,
language,
use_cache,
llm_extraction_concurrency,
):
if not jobs:
return []
max_workers = min(_positive_int(llm_extraction_concurrency, 1), len(jobs))
if max_workers <= 1:
ordered_results = self._run_extraction_jobs_sequential(
jobs, project_name, language, use_cache
)
else:
ordered_results = self._run_extraction_jobs_parallel(
jobs, project_name, language, use_cache, max_workers
)
candidates = []
for _, result in sorted(ordered_results, key=lambda item: item[0]):
candidates.extend(result)
return candidates
def _run_extraction_jobs_sequential(self, jobs, project_name, language, use_cache):
return [
(
job["ordinal"],
self._extract_batch_abstractions(
project_name,
job["batch"],
job["chunks"],
language,
use_cache,
metadata=job["metadata"],
),
)
for job in jobs
]
def _run_extraction_jobs_parallel(
self, jobs, project_name, language, use_cache, max_workers
):
print(f"Extracting abstractions with {max_workers} concurrent LLM workers...")
ordered_results = []
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {
executor.submit(
self._extract_batch_abstractions,
project_name,
job["batch"],
job["chunks"],
language,
use_cache,
job["metadata"],
): job["ordinal"]
for job in jobs
}
for future in as_completed(futures):
ordered_results.append((futures[future], future.result()))
return ordered_results
def _extract_batch_abstractions(
self,
project_name,
batch,
chunks,
language,
use_cache,
metadata=None,
):
language_instruction = ""
name_lang_hint = ""
desc_lang_hint = ""
if language.lower() != "english":
language_instruction = f"IMPORTANT: Generate `name` and `description` in **{language.capitalize()}**. Do NOT use English for these fields.\n\n"
name_lang_hint = f" (value in {language.capitalize()})"
desc_lang_hint = f" (value in {language.capitalize()})"
prompt = f"""
For the project `{project_name}`, extract middle-level code abstractions from this planned chunk batch.
Batch name: {batch.get("name", "Code Chunk Batch")}
Batch reason: {batch.get("reason", "")}
Chunk context:
{format_chunks_for_prompt(chunks)}
{language_instruction}Identify abstractions that are useful for onboarding.
Prefer concepts that map to code symbols, scopes, module wiring, config, routing,
providers, schedulers, data models, or orchestration. Do not produce a raw function
list, and do not produce product-level slogans that cannot be mapped to code.
Misc chunks may be core evidence for routing, registration, configuration, or glue code.
For each abstraction, provide:
1. A concise `name`{name_lang_hint}.
2. A beginner-friendly `description` explaining the code concept{desc_lang_hint}.
3. `file_indices` using valid file indices shown in chunk headers.
4. `supporting_chunk_ids` using only chunk ids shown in this batch.
Format the output as YAML:
```yaml
abstractions:
- name: |
Route Registration{name_lang_hint}
description: |
Explains how route definitions are collected and connected to handlers.{desc_lang_hint}
file_indices:
- 3 # src/router.ts
supporting_chunk_ids:
- "00003:src/router.ts:entity:0"
- "00003:src/router.ts:misc:0"
```
"""
response = call_llm(
prompt,
use_cache=(use_cache and self.cur_retry == 0),
stage="identify.extract",
metadata=metadata,
)
data = _load_yaml_block(response)
if isinstance(data, dict):
abstractions = data.get("abstractions", [])
else:
abstractions = data
if not isinstance(abstractions, list):
raise ValueError("Batch abstraction output is not a list")
return abstractions
def _validate_and_merge(self, candidates, chunks, file_count, max_abstraction_num):
chunk_ids = {chunk["chunk_id"] for chunk in chunks}
merged = []
seen_names = set()
for item in candidates:
if not isinstance(item, dict):
continue
name = item.get("name")
description = item.get("description")
if not isinstance(name, str) or not isinstance(description, str):
continue
supporting_ids = _valid_supporting_ids(item, chunk_ids)
file_indices = _parse_file_indices(item.get("file_indices", []), file_count)
if not file_indices and supporting_ids:
file_indices = extract_file_indices(chunks, supporting_ids)
if not file_indices:
continue
dedupe_key = name.strip().lower()
if dedupe_key in seen_names:
continue
seen_names.add(dedupe_key)
merged.append(
{
"name": name.strip(),
"description": description.strip(),
"files": file_indices,
}
)
if len(merged) >= max_abstraction_num:
break
if not merged:
raise ValueError("No valid abstractions were extracted from chunk batches")
return merged
def _load_yaml_block(response):
text = response.strip()
if "```yaml" in text:
text = text.split("```yaml", 1)[1].split("```", 1)[0].strip()
elif "```" in text:
text = text.split("```", 1)[1].split("```", 1)[0].strip()
data = yaml.safe_load(text)
if data is None:
raise ValueError("LLM returned empty YAML")
return data
def _validate_batches(batches, valid_chunk_ids):
if not isinstance(batches, list):
raise ValueError("Planning output missing batches list")
validated = []
for batch in batches:
if not isinstance(batch, dict):
continue
chunk_ids = batch.get("chunk_ids")
if not isinstance(chunk_ids, list):
continue
clean_ids = []
for chunk_id in chunk_ids:
if chunk_id not in valid_chunk_ids:
raise ValueError(f"Invalid chunk id in planning output: {chunk_id}")
clean_ids.append(chunk_id)
if clean_ids:
validated.append(
{
"name": str(batch.get("name") or "Code Chunk Batch").strip(),
"reason": str(batch.get("reason") or "").strip(),
"chunk_ids": clean_ids,
}
)
if not validated:
raise ValueError("Planning output did not contain valid chunk batches")
return validated
def _validate_compact_plan(candidates, chunks, max_abstraction_num):
if not isinstance(candidates, list):
raise ValueError("Compact planning output missing abstractions list")
valid_chunk_ids = {chunk["chunk_id"] for chunk in chunks}
validated = []
seen_names = set()
for item in candidates:
if not isinstance(item, dict):
continue
name = item.get("name")
if not isinstance(name, str) or not name.strip():
continue
supporting_ids = _valid_supporting_ids(item, valid_chunk_ids)
if not supporting_ids:
continue
dedupe_key = name.strip().lower()
if dedupe_key in seen_names:
continue
seen_names.add(dedupe_key)
validated.append(
{
"name": name.strip(),
"reason": str(item.get("reason") or "").strip(),
"supporting_chunk_ids": supporting_ids,
}
)
if len(validated) >= max_abstraction_num:
break
if not validated:
raise ValueError("Compact planning output did not select valid chunks")
return validated
def _planned_supporting_ids(plan, chunks):
valid_chunk_ids = {chunk["chunk_id"] for chunk in chunks}
ids = []
seen = set()
for item in plan:
for chunk_id in item.get("supporting_chunk_ids", []):
if chunk_id in valid_chunk_ids and chunk_id not in seen:
ids.append(chunk_id)
seen.add(chunk_id)
return ids
def _format_compact_plan_for_prompt(plan):
blocks = []
for index, item in enumerate(plan):
supporting = "\n".join(f" - {chunk_id}" for chunk_id in item["supporting_chunk_ids"])
blocks.append(
"\n".join(
[
f" - index: {index}",
f" name: {item['name']}",
f" reason: {item.get('reason', '')}",
" supporting_chunk_ids:",
supporting,
]
)
)
return "abstractions:\n" + "\n".join(blocks)
def _compact_refinement_prompt(
project_name,
plan,
selected_chunks,
language,
max_abstraction_num,
):
language_instruction = ""
if language.lower() != "english":
language_instruction = f"Generate `name` and `description` in {language.capitalize()}.\n\n"
return f"""
For the project `{project_name}`, refine these planned tutorial abstractions using only the selected evidence chunks.
Planned abstractions:
{_format_compact_plan_for_prompt(plan)}
Selected evidence chunks:
{format_chunks_for_prompt(selected_chunks)}
{language_instruction}Produce final onboarding abstractions. Merge overlapping candidates, discard weak candidates, and keep at most {max_abstraction_num}.
For each abstraction, provide:
1. A concise `name`.
2. A beginner-friendly `description`.
3. `file_indices` using valid file indices shown in chunk headers.
4. `supporting_chunk_ids` using only selected chunk ids shown above.
Format the output as YAML:
```yaml
abstractions:
- name: |
Routing Layer
description: |
Explains how routes connect incoming requests to handlers.
file_indices:
- 3 # src/router.ts
supporting_chunk_ids:
- "00003:src/router.ts:entity:0"
```
"""
def _valid_supporting_ids(item, valid_chunk_ids):
supporting_ids = item.get("supporting_chunk_ids", [])
if not isinstance(supporting_ids, list):
return []
return [chunk_id for chunk_id in supporting_ids if chunk_id in valid_chunk_ids]
def _parse_file_indices(raw_indices, file_count):
if not isinstance(raw_indices, list):
return []
parsed = []
for idx_entry in raw_indices:
try:
if isinstance(idx_entry, int):
idx = idx_entry
elif isinstance(idx_entry, str) and "#" in idx_entry:
idx = int(idx_entry.split("#")[0].strip())
else:
idx = int(str(idx_entry).strip())
except (ValueError, TypeError):
continue
if 0 <= idx < file_count:
parsed.append(idx)
return sorted(set(parsed))
class AnalyzeRelationships(Node):
def prep(self, shared):
abstractions = shared[
"abstractions"
] # Now contains 'files' list of indices, name/description potentially translated
files_data = shared["files"]
project_name = shared["project_name"] # Get project name
language = shared.get("language", DEFAULT_TUTORIAL_LANGUAGE) # Get language
use_cache = shared.get("use_cache", True) # Get use_cache flag, default to True
# Get the actual number of abstractions directly
num_abstractions = len(abstractions)
# Create context with abstraction names, indices, descriptions, and relevant file snippets
context = "Identified Abstractions:\\n"
all_relevant_indices = set()
abstraction_info_for_prompt = []
for i, abstr in enumerate(abstractions):
# Use 'files' which contains indices directly
file_indices_str = ", ".join(map(str, abstr["files"]))
# Abstraction name and description might be translated already
info_line = f"- Index {i}: {abstr['name']} (Relevant file indices: [{file_indices_str}])\\n Description: {abstr['description']}"
context += info_line + "\\n"
abstraction_info_for_prompt.append(
f"{i} # {abstr['name']}"
) # Use potentially translated name here too
all_relevant_indices.update(abstr["files"])
context += "\\nRelevant File Snippets (Referenced by Index and Path):\\n"
# Get content for relevant files using helper
relevant_files_content_map = get_content_for_indices(
files_data, sorted(list(all_relevant_indices))
)
# Format file content for context
file_context_str = "\\n\\n".join(
f"--- File: {idx_path} ---\\n{content}"
for idx_path, content in relevant_files_content_map.items()
)
context += file_context_str
return (
context,
"\n".join(abstraction_info_for_prompt),
num_abstractions, # Pass the actual count
project_name,
language,
use_cache,
) # Return use_cache
def exec(self, prep_res):
(
context,
abstraction_listing,
num_abstractions, # Receive the actual count
project_name,
language,
use_cache,
) = prep_res # Unpack use_cache
print(f"Analyzing relationships using LLM...")
# Add language instruction and hints only if not English
language_instruction = ""
lang_hint = ""
list_lang_note = ""
if language.lower() != "english":
language_instruction = f"IMPORTANT: Generate the `summary` and relationship `label` fields in **{language.capitalize()}** language. Do NOT use English for these fields.\n\n"
lang_hint = f" (in {language.capitalize()})"
list_lang_note = f" (Names might be in {language.capitalize()})" # Note for the input list
prompt = f"""
Based on the following abstractions and relevant code snippets from the project `{project_name}`:
List of Abstraction Indices and Names{list_lang_note}:
{abstraction_listing}
Context (Abstractions, Descriptions, Code):
{context}
{language_instruction}Please provide:
1. A high-level `summary` of the project's main purpose and functionality in a few beginner-friendly sentences{lang_hint}. Use markdown formatting with **bold** and *italic* text to highlight important concepts.
2. A list (`relationships`) describing the key interactions between these abstractions. For each relationship, specify:
- `from_abstraction`: Index of the source abstraction (e.g., `0 # AbstractionName1`)
- `to_abstraction`: Index of the target abstraction (e.g., `1 # AbstractionName2`)
- `label`: A brief label for the interaction **in just a few words**{lang_hint} (e.g., "Manages", "Inherits", "Uses").
Ideally the relationship should be backed by one abstraction calling or passing parameters to another.
Simplify the relationship and exclude those non-important ones.
IMPORTANT: Make sure EVERY abstraction is involved in at least ONE relationship (either as source or target). Each abstraction index must appear at least once across all relationships.
Format the output as YAML:
```yaml
summary: |
A brief, simple explanation of the project{lang_hint}.
Can span multiple lines with **bold** and *italic* for emphasis.
relationships:
- from_abstraction: 0 # AbstractionName1
to_abstraction: 1 # AbstractionName2
label: "Manages"{lang_hint}
- from_abstraction: 2 # AbstractionName3
to_abstraction: 0 # AbstractionName1
label: "Provides config"{lang_hint}
# ... other relationships
```
Now, provide the YAML output:
"""
response = call_llm(
prompt,
use_cache=(use_cache and self.cur_retry == 0),
stage="analyze.relationships",
metadata={
"project_name": project_name,
"num_abstractions": num_abstractions,
},
) # Use cache only if enabled and not retrying
# --- Validation ---
yaml_str = response.strip().split("```yaml")[1].split("```")[0].strip()
relationships_data = yaml.safe_load(yaml_str)
if not isinstance(relationships_data, dict) or not all(
k in relationships_data for k in ["summary", "relationships"]
):
raise ValueError(
"LLM output is not a dict or missing keys ('summary', 'relationships')"
)
if not isinstance(relationships_data["summary"], str):
raise ValueError("summary is not a string")
if not isinstance(relationships_data["relationships"], list):
raise ValueError("relationships is not a list")
# Validate relationships structure
validated_relationships = []
for rel in relationships_data["relationships"]:
# Check for 'label' key
if not isinstance(rel, dict) or not all(
k in rel for k in ["from_abstraction", "to_abstraction", "label"]
):
raise ValueError(
f"Missing keys (expected from_abstraction, to_abstraction, label) in relationship item: {rel}"
)
# Validate 'label' is a string
if not isinstance(rel["label"], str):
raise ValueError(f"Relationship label is not a string: {rel}")
# Validate indices
try:
from_idx = int(str(rel["from_abstraction"]).split("#")[0].strip())
to_idx = int(str(rel["to_abstraction"]).split("#")[0].strip())
if not (
0 <= from_idx < num_abstractions and 0 <= to_idx < num_abstractions
):
raise ValueError(
f"Invalid index in relationship: from={from_idx}, to={to_idx}. Max index is {num_abstractions-1}."
)
validated_relationships.append(
{
"from": from_idx,
"to": to_idx,
"label": rel["label"], # Potentially translated label
}
)
except (ValueError, TypeError):
raise ValueError(f"Could not parse indices from relationship: {rel}")
print("Generated project summary and relationship details.")
return {
"summary": relationships_data["summary"], # Potentially translated summary
"details": validated_relationships, # Store validated, index-based relationships with potentially translated labels
}
def post(self, shared, prep_res, exec_res):
# Structure is now {"summary": str, "details": [{"from": int, "to": int, "label": str}]}
# Summary and label might be translated
shared["relationships"] = exec_res
class OrderChapters(Node):
def prep(self, shared):
abstractions = shared["abstractions"] # Name/description might be translated
relationships = shared["relationships"] # Summary/label might be translated
project_name = shared["project_name"] # Get project name
language = shared.get("language", DEFAULT_TUTORIAL_LANGUAGE) # Get language
use_cache = shared.get("use_cache", True) # Get use_cache flag, default to True
# Prepare context for the LLM
abstraction_info_for_prompt = []
for i, a in enumerate(abstractions):
abstraction_info_for_prompt.append(
f"- {i} # {a['name']}"
) # Use potentially translated name
abstraction_listing = "\n".join(abstraction_info_for_prompt)
# Use potentially translated summary and labels
summary_note = ""
if language.lower() != "english":
summary_note = (
f" (Note: Project Summary might be in {language.capitalize()})"
)
context = f"Project Summary{summary_note}:\n{relationships['summary']}\n\n"
context += "Relationships (Indices refer to abstractions above):\n"
for rel in relationships["details"]:
from_name = abstractions[rel["from"]]["name"]
to_name = abstractions[rel["to"]]["name"]
# Use potentially translated 'label'
context += f"- From {rel['from']} ({from_name}) to {rel['to']} ({to_name}): {rel['label']}\n" # Label might be translated
list_lang_note = ""
if language.lower() != "english":