forked from MarcSkovMadsen/holoviz-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata.py
More file actions
2693 lines (2286 loc) · 100 KB
/
Copy pathdata.py
File metadata and controls
2693 lines (2286 loc) · 100 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
"""Data handling for the HoloViz Documentation MCP server."""
import asyncio
import hashlib
import json
import logging
import os
import re
import shutil
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from pathlib import PurePosixPath
from typing import Any
from typing import Literal
from typing import Optional
import chromadb
import git
from chromadb.api.collection_configuration import CreateCollectionConfiguration
from chromadb.api.shared_system_client import SharedSystemClient
from fastmcp import Context
from nbconvert import MarkdownExporter
from nbformat import read as nbread
from pydantic import HttpUrl
from holoviz_mcp.config.loader import get_config
from holoviz_mcp.config.models import FolderConfig
from holoviz_mcp.config.models import GitRepository
from holoviz_mcp.holoviz_mcp.models import Document
logger = logging.getLogger(__name__)
# Todo: Describe DocumentApp
# Todo: Avoid overflow-x in SearchApp sidebar
# Todo: Add bokeh documentation to README extra config
_CROMA_CONFIGURATION = CreateCollectionConfiguration(
hnsw={
"space": "cosine",
"ef_construction": 200,
"ef_search": 200,
}
)
async def log_info(message: str, ctx: Context | None = None):
"""Log an info message to the context or logger."""
if ctx:
await ctx.info(message)
else:
logger.info(message)
async def log_warning(message: str, ctx: Context | None = None):
"""Log a warning message to the context or logger."""
if ctx:
await ctx.warning(message)
else:
logger.warning(message)
async def log_exception(message: str, ctx: Context | None = None):
"""Log an error message to the context or logger."""
if ctx:
await ctx.error(message)
else:
logger.error(message)
raise Exception(message)
def _normalize_source_path(path: str | Path) -> str:
"""Normalize source paths to POSIX-style separators for cross-platform consistency."""
return str(path).replace("\\", "/")
def extract_tech_terms(query: str) -> list[str]:
"""Extract technical identifiers from a search query.
Identifies three categories of terms that benefit from exact substring
matching rather than pure semantic similarity:
- **Compound CamelCase** (requires internal case transition):
``SelectEditor``, ``ReactiveHTML``, ``TextInput`` — but NOT
single-word PascalCase like ``Button``, ``Panel``, ``Python``.
- **snake_case**: ``add_filter``, ``page_size``
- **Dot-separated qualified names**: ``param.watch``,
``pn.widgets.Button`` — excludes common abbreviations like
``e.g``, ``i.e`` via a blocklist and minimum length filter.
Parameters
----------
query : str
Search query string.
Returns
-------
list[str]
Deduplicated list of technical terms preserving original case
and discovery order. Empty list when no technical terms are found.
"""
terms: list[str] = []
seen: set[str] = set()
# Compound CamelCase: requires an internal lower→upper transition
# e.g. SelectEditor, ReactiveHTML, TextInput — NOT Button, Panel
for m in re.finditer(r"\b[A-Z][a-z]+[A-Z][a-zA-Z]*\b", query):
t = m.group()
if t not in seen:
terms.append(t)
seen.add(t)
# snake_case identifiers
for m in re.finditer(r"\b[a-z][a-z0-9]*_[a-z][a-z0-9_]*\b", query):
t = m.group()
if t not in seen:
terms.append(t)
seen.add(t)
# Dot-separated qualified names (param.watch, pn.widgets.Button)
dot_blocklist = {"e.g", "i.e", "vs.", "etc."}
for m in re.finditer(r"\b[a-z][a-z0-9]*(?:\.[a-zA-Z][a-zA-Z0-9_]*)+\b", query):
t = m.group()
if len(t) > 3 and t not in dot_blocklist and t not in seen:
terms.append(t)
seen.add(t)
return terms
_PASCAL_STOPWORDS: set[str] = {
# Determiners, pronouns, articles
"The",
"This",
"That",
"These",
"Those",
"Each",
"Every",
"Some",
"Any",
"All",
"Both",
"Few",
"Many",
"Much",
"Most",
"Other",
"Another",
"Such",
"My",
"Your",
"His",
"Her",
"Its",
"Our",
"Their",
"One",
"An",
"No",
# Short prepositions / conjunctions (sentence-initial)
"In",
"At",
"To",
"If",
"Or",
"So",
"As",
"By",
"Up",
"On",
# Interrogatives / relatives
"Who",
"What",
"Which",
"Where",
"When",
"Why",
"How",
"Whom",
"Whose",
# Personal pronouns
"He",
"She",
"It",
"We",
"They",
# Auxiliary / modal verbs
"Is",
"Are",
"Was",
"Were",
"Be",
"Been",
"Being",
"Has",
"Have",
"Had",
"Do",
"Does",
"Did",
"Will",
"Would",
"Could",
"Should",
"Can",
"May",
"Might",
"Must",
"Shall",
# Common verbs (sentence-initial in docs)
"Get",
"Set",
"Let",
"Make",
"Take",
"Give",
"Put",
"Run",
"See",
"Find",
"Use",
"Try",
"Add",
"Go",
"Come",
"Keep",
"Show",
"Tell",
"Say",
"Ask",
"Help",
"Start",
"Stop",
"Open",
"Close",
"Read",
"Write",
"New",
"Old",
"Create",
"Build",
"Deploy",
"Install",
"Update",
"Remove",
"Delete",
"Enable",
"Disable",
"Configure",
"Define",
"Return",
"Check",
"Pass",
"Call",
"Load",
"Save",
"Send",
"Move",
# Adjectives / adverbs
"Not",
"Also",
"Just",
"Only",
"Very",
"Too",
"More",
"Less",
"First",
"Last",
"Next",
"Best",
"Good",
"Bad",
# Python builtins
"True",
"False",
"None",
# Conjunctions / prepositions
"And",
"But",
"For",
"Nor",
"Yet",
"With",
"From",
"Into",
"About",
"After",
"Before",
"Between",
"Through",
"During",
"Without",
"Within",
"Along",
"Above",
"Below",
# Generic tech words (too broad to be component names)
"Data",
"Code",
"Style",
"Type",
"Name",
"Value",
"Event",
"Class",
"Object",
"Method",
"Function",
"Module",
"Package",
"File",
"Path",
"String",
"Number",
"Integer",
"Float",
"List",
"Dict",
"Tuple",
"Array",
"Index",
"Key",
"Error",
"Warning",
"Info",
"Debug",
"Log",
# Common sentence starters / discourse markers
"Here",
"There",
"Then",
"Now",
"However",
"Therefore",
"Furthermore",
"Moreover",
"Although",
"Because",
"Since",
"While",
"Until",
"Unless",
"Whether",
"Though",
# Documentation filler
"Note",
"Tip",
"Using",
"Like",
}
# Common English words that can appear PascalCase but are NOT component names.
def extract_pascal_terms(query: str) -> list[str]:
"""Extract single PascalCase words from a query, excluding stopwords.
Captures words like Scatter, Button, Tabulator that start with an
uppercase letter followed by at least one lowercase letter. Compound
CamelCase words (SelectEditor) are also captured — they overlap with
:func:`extract_tech_terms` and deduplication happens at the call site.
Parameters
----------
query : str
Search query string.
Returns
-------
list[str]
Deduplicated list of PascalCase terms preserving discovery order.
Empty list when no terms are found.
"""
terms: list[str] = []
seen: set[str] = set()
for m in re.finditer(r"\b[A-Z][a-z][a-zA-Z]*\b", query):
t = m.group()
if t not in seen and t not in _PASCAL_STOPWORDS:
terms.append(t)
seen.add(t)
return terms
def _build_where_document_clause(terms: list[str]) -> dict[str, Any] | None:
"""Build a ChromaDB ``where_document`` clause for keyword pre-filtering.
Parameters
----------
terms : list[str]
Technical terms extracted by :func:`extract_tech_terms`.
Returns
-------
dict[str, Any] | None
``None`` when *terms* is empty, a single ``{"$contains": term}``
dict for one term, or ``{"$or": [...]}`` for multiple terms.
"""
if not terms:
return None
if len(terms) == 1:
return {"$contains": terms[0]}
return {"$or": [{"$contains": t} for t in terms]}
def _build_stem_boost_clause(pascal_terms: list[str], project: str | None) -> dict[str, Any] | None:
"""Build a ChromaDB ``where`` clause matching ``source_path_stem`` metadata.
Used to boost results whose filename stem exactly matches a PascalCase
term from the query (e.g. ``Scatter`` → ``Scatter.ipynb``).
Parameters
----------
pascal_terms : list[str]
PascalCase terms extracted by :func:`extract_pascal_terms`.
project : str | None
Optional project filter.
Returns
-------
dict[str, Any] | None
``None`` when *pascal_terms* is empty, otherwise a ``where``
clause suitable for ``collection.query(where=...)``.
"""
if not pascal_terms:
return None
filters: list[dict[str, Any]] = []
if len(pascal_terms) == 1:
filters.append({"source_path_stem": pascal_terms[0]})
else:
filters.append({"$or": [{"source_path_stem": t} for t in pascal_terms]})
if project:
filters.append({"project": str(project)})
return filters[0] if len(filters) == 1 else {"$and": filters}
def extract_keywords(query: str) -> list[str]:
"""Extract meaningful keywords from search query.
Removes common stopwords and splits into terms.
Args:
query: Search query string
Returns
-------
List of meaningful keywords (lowercase)
"""
stopwords = {
"the",
"a",
"an",
"and",
"or",
"but",
"in",
"on",
"at",
"to",
"for",
"of",
"with",
"from",
"by",
"about",
"how",
"what",
"where",
"when",
"why",
"which",
"who",
"is",
"are",
"was",
"were",
"be",
"been",
"being",
"have",
"has",
"had",
"do",
"does",
"did",
"will",
"would",
"should",
"could",
"can",
"may",
"might",
"must",
"shall",
}
# Split and clean
keywords = query.lower().split()
# Remove stopwords, keep meaningful terms (> 2 chars)
keywords = [k for k in keywords if k not in stopwords and len(k) > 2]
return keywords
def find_keyword_matches(content: str, keywords: list[str]) -> list[tuple[int, int, str]]:
"""Find all positions where keywords appear in content.
Args:
content: Document content to search
keywords: List of keywords to find
Returns
-------
List of (start_pos, end_pos, matched_keyword) tuples, sorted by position
"""
matches = []
content_lower = content.lower()
for keyword in keywords:
start = 0
while True:
pos = content_lower.find(keyword, start)
if pos == -1:
break
matches.append((pos, pos + len(keyword), keyword))
start = pos + 1
# Sort by position
matches.sort(key=lambda x: x[0])
return matches
def build_excerpts(content: str, matches: list[tuple[int, int, str]], max_chars: int, context_chars: int) -> str:
"""Build excerpt string from matches with context windows.
Combines nearby matches, adds separators for distant sections.
Args:
content: Full document content
matches: List of (start_pos, end_pos, keyword) tuples
max_chars: Maximum total characters to return
context_chars: Characters to include before/after each match
Returns
-------
Excerpt(s) with [...] separators and truncation indicators
"""
if not matches:
# Fallback to beginning truncation
truncated = content[:max_chars]
last_space = truncated.rfind(" ")
if last_space > max_chars * 0.8:
truncated = truncated[:last_space]
return truncated + "\n\n[... content truncated, use content='full' for complete content ...]"
# Cluster nearby matches
clusters = []
current_cluster = [matches[0]]
for match in matches[1:]:
# If within 2x context window, add to current cluster
if match[0] - current_cluster[-1][1] < 2 * context_chars:
current_cluster.append(match)
else:
clusters.append(current_cluster)
current_cluster = [match]
clusters.append(current_cluster)
# Build excerpts from clusters
excerpts: list[str] = []
total_chars = 0
for cluster in clusters:
# Get range for this cluster
start_pos = max(0, cluster[0][0] - context_chars)
end_pos = min(len(content), cluster[-1][1] + context_chars)
# Extract excerpt, break at word boundaries
excerpt = content[start_pos:end_pos]
# Trim to word boundaries
if start_pos > 0:
# Find first space to start at word boundary
first_space = excerpt.find(" ")
if first_space != -1 and first_space < context_chars * 0.3:
excerpt = excerpt[first_space + 1 :]
start_pos += first_space + 1
if end_pos < len(content):
# Find last space to end at word boundary
last_space = excerpt.rfind(" ")
if last_space > len(excerpt) * 0.7:
excerpt = excerpt[:last_space]
# Check if we have room
separator = "\n\n[...]\n\n" if excerpts else ""
if total_chars + len(excerpt) + len(separator) > max_chars:
# Try to fit partial excerpt
remaining = max_chars - total_chars - len(separator)
if remaining > 200: # Only add if we have reasonable space
excerpt = excerpt[:remaining]
last_space = excerpt.rfind(" ")
if last_space > remaining * 0.7:
excerpt = excerpt[:last_space]
excerpts.append(excerpt)
break
excerpts.append(excerpt)
total_chars += len(excerpt) + len(separator)
if not excerpts:
# Fallback if nothing fits
return build_excerpts(content, [], max_chars, context_chars)
# Combine excerpts
result = "\n\n[...]\n\n".join(excerpts)
# Add indicators at start/end if content was truncated
first_match_pos = matches[0][0] if matches else 0
last_match_pos = matches[-1][1] if matches else len(content)
if first_match_pos > context_chars:
result = "[...]\n\n" + result
if last_match_pos < len(content) - context_chars:
result = result + "\n\n[...]"
return result
def extract_relevant_excerpt(content: str, query: str, max_chars: int, context_chars: int = 500) -> str:
"""Extract relevant excerpt from content based on query keywords.
Args:
content: Full document content
query: Search query string
max_chars: Maximum total characters to return
context_chars: Characters to include before/after each match (default: 500)
Returns
-------
Excerpt(s) centered around query matches, or beginning if no matches
"""
# Extract keywords from query
keywords = extract_keywords(query)
if not keywords:
# No meaningful keywords, fall back to simple truncation
return build_excerpts(content, [], max_chars, context_chars)
# Find keyword matches in content
matches = find_keyword_matches(content, keywords)
if not matches:
# No matches found, fall back to simple truncation
return build_excerpts(content, [], max_chars, context_chars)
# Build excerpts from matches
return build_excerpts(content, matches, max_chars, context_chars)
def truncate_content(content: str | None, max_chars: int | None, query: str | None = None) -> str | None:
"""Truncate content, optionally centering on query matches.
Args:
content: The content to truncate
max_chars: Maximum characters allowed. If None, no truncation is performed.
query: Optional search query for context-aware truncation
Returns
-------
The original content if under limit, truncated content with ellipsis if over limit,
or None if content is None.
"""
if content is None or max_chars is None:
return content
if len(content) <= max_chars:
return content
# If query provided, use smart excerpt extraction
if query:
# Adjust context_chars based on max_chars to ensure keywords fit
# Use at most 40% of max_chars for context on each side
context_chars = min(500, int(max_chars * 0.4))
return extract_relevant_excerpt(content, query, max_chars, context_chars)
# Otherwise, use simple truncation (existing logic)
truncated = content[:max_chars]
last_space = truncated.rfind(" ")
# Don't cut off too much - if last space is in the last 20% of max_chars, use it
if last_space > max_chars * 0.8:
truncated = truncated[:last_space]
# Add indicator
return truncated + "\n\n[... content truncated, use content='full' for complete content ...]"
def _find_markdown_header_lines(content: str) -> list[int]:
"""Find line indices of H1/H2 markdown headers that are outside code fences.
Skips headers inside fenced code blocks (``` ... ```) so that Python
comments like ``# setup code`` or decorative lines like
``# ========`` are never treated as split points.
Parameters
----------
content : str
Full markdown content.
Returns
-------
list[int]
Sorted line indices (0-based) where H1/H2 headers appear.
"""
header_lines: list[int] = []
in_code_block = False
for i, line in enumerate(content.split("\n")):
if line.strip().startswith("```"):
in_code_block = not in_code_block
continue
if not in_code_block and re.match(r"^#{1,2} ", line):
header_lines.append(i)
return header_lines
def chunk_document(doc: dict[str, Any], min_chunk_chars: int = 100) -> list[dict[str, Any]]:
r"""Split a document into chunks at H1/H2 markdown headers.
Only headers **outside** fenced code blocks are used as split points,
so Python comments (``# ...``) and decorative dividers inside code
blocks are left intact.
Each chunk stores two content fields:
- ``content``: the document title prepended to the raw section text
(``"Title\\n\\n## Section ..."``) so that ChromaDB's embedding model
associates every chunk with its parent document context.
- ``raw_content``: the original section text without the title prefix,
used by ``get_document()`` and ``search_get_reference_guide()`` to
reconstruct the full document without duplicating the title.
Parameters
----------
doc : dict[str, Any]
Document dict with at least 'id', 'title', and 'content' keys,
plus other metadata fields.
min_chunk_chars : int
Minimum character count for a chunk to be kept. Chunks below this
threshold are discarded (e.g. empty sections). Default: 100.
Returns
-------
list[dict[str, Any]]
List of chunk dicts. If no H1/H2 headers are found, returns a single
chunk with chunk_index=0.
"""
content = doc.get("content", "") or ""
parent_id = doc["id"]
title = doc.get("title", "")
# Find H1/H2 header lines that are outside code fences
lines = content.split("\n")
header_indices = _find_markdown_header_lines(content)
# Build text parts by splitting at header boundaries
if header_indices:
parts: list[str] = []
prev = 0
for idx in header_indices:
if idx > prev:
parts.append("\n".join(lines[prev:idx]))
prev = idx
# Last chunk: from last header to end
parts.append("\n".join(lines[prev:]))
else:
parts = [content]
# Filter out tiny/empty chunks
parts = [p for p in parts if len(p.strip()) >= min_chunk_chars]
# If nothing survived filtering, keep the whole content as one chunk
if not parts:
parts = [content]
# Metadata keys to copy from the parent document to each chunk
metadata_keys = ("title", "url", "project", "source_path", "source_path_stem", "source_url", "description", "is_reference")
chunks: list[dict[str, Any]] = []
for idx, part in enumerate(parts):
chunk: dict[str, Any] = {}
for key in metadata_keys:
if key in doc:
chunk[key] = doc[key]
chunk["id"] = f"{parent_id}___chunk_{idx}"
chunk["chunk_index"] = idx
chunk["parent_id"] = parent_id
# raw_content: original section text for faithful document reconstruction
chunk["raw_content"] = part
# content: context-prefixed text stored in ChromaDB for better embeddings
context_prefix = _build_context_prefix(doc.get("project", ""), doc.get("source_path", ""), doc.get("is_reference", False))
if title:
chunk["content"] = f"{context_prefix}{title}\n\n{part}"
elif context_prefix:
chunk["content"] = f"{context_prefix}{part}"
else:
chunk["content"] = part
chunks.append(chunk)
return chunks
def _strip_title_prefix(
content: str,
title: str,
project: str = "",
source_path: str = "",
is_reference: bool = False,
) -> str:
r"""Remove the title prefix that chunk_document() prepends for embedding.
Handles both the new format (with context prefix) and the old format
(title only) for backward compatibility with existing indexes.
Parameters
----------
content : str
Chunk content, possibly prefixed with context + title.
title : str
The document title to strip.
project : str
Project name (used to compute context prefix).
source_path : str
Relative source path (used to compute context prefix).
is_reference : bool
Whether the document is a reference guide.
Returns
-------
str
Content with the title prefix removed if present, otherwise unchanged.
"""
# Try new format: context_prefix + title
context_prefix = _build_context_prefix(project, source_path, is_reference)
new_prefix = f"{context_prefix}{title}\n\n"
if title and content.startswith(new_prefix):
return content[len(new_prefix) :]
# Backward compat: old format (title only, no context prefix)
old_prefix = f"{title}\n\n"
if title and content.startswith(old_prefix):
return content[len(old_prefix) :]
return content
def _extract_reference_category(source_path: str, is_reference: bool) -> str | None:
"""Extract the component category from a reference guide's source path.
Finds ``"reference"`` in the path parts and returns the next non-filename
part (i.e. the directory immediately below ``reference/``).
Parameters
----------
source_path : str
Relative source path of the document.
is_reference : bool
Whether this document is a reference guide.
Returns
-------
str | None
Category name (e.g. ``"widgets"``, ``"elements"``, ``"panes"``),
or ``None`` if not a reference doc or no category directory exists.
"""
if not is_reference:
return None
parts = source_path.split("/")
try:
ref_idx = parts.index("reference")
except ValueError:
return None
# Category is next part after "reference", if it's not a filename
if ref_idx + 1 < len(parts):
candidate = parts[ref_idx + 1]
if "." not in candidate: # skip filenames like "guide.md"
return candidate
return None
def _build_context_prefix(project: str, source_path: str, is_reference: bool) -> str:
r"""Build a context line prepended before the title in chunk content.
The prefix enriches the embedding with project and reference-category
context so that queries like "HoloViews Scatter" are closer in vector
space to the Scatter reference guide chunk.
Parameters
----------
project : str
Project name (e.g. ``"panel"``, ``"holoviews"``).
source_path : str
Relative source path of the document.
is_reference : bool
Whether this document is a reference guide.
Returns
-------
str
A context line ending with ``"\n"`` (e.g. ``"panel widgets\n"``),
or ``""`` when no context is available.
"""
parts: list[str] = []
if project:
parts.append(project)
category = _extract_reference_category(source_path, is_reference)
if category:
parts.append(category)
if parts:
return " ".join(parts) + "\n"
return ""
def get_skill(name: str) -> str:
"""Get skill for using a project with LLMs.
This function searches for skill resources in user and default directories,
with user resources taking precedence over default ones.
Args:
name (str): The name of the skill to get.
Returns
-------
str: A string containing the skill in Markdown format.
Raises
------
FileNotFoundError: If the specified skill is not found in either directory.
"""
config = get_config()
# Convert underscored names to hyphenated for file lookup
skill_filename = name.replace("_", "-") + ".md"
# Search in user directory first, then default directory
search_paths = [
config.skills_dir("user"),
config.skills_dir("default"),
]
for search_dir in search_paths:
skills_file = search_dir / skill_filename
if skills_file.exists():
return skills_file.read_text(encoding="utf-8")
# If not found, raise error with helpful message
available_files = []
for search_dir in search_paths:
if search_dir.exists():
available_files.extend([f.name for f in search_dir.glob("*.md")])
available_str = ", ".join(set(available_files)) if available_files else "None"
raise FileNotFoundError(f"Skill file {name} not found. Available skills: {available_str}. Searched in: {[str(p) for p in search_paths]}")
def list_skills() -> list[str]:
"""List all available skills.
This function discovers available skills from both user and default directories,
with user resources taking precedence over default ones.
Returns
-------
list[str]: A list of the skills available.
Names are returned in hyphenated format (e.g., "panel-material-ui").
"""
config = get_config()
# Collect available projects from both directories
available_projects = set()
search_paths = [
config.skills_dir("user"),
config.skills_dir("default"),
]
for search_dir in search_paths:
if search_dir.exists():
for md_file in search_dir.glob("*.md"):
available_projects.add(md_file.stem)
return sorted(list(available_projects))
def remove_leading_number_sep_from_path(p: Path) -> Path:
"""Remove a leading number + underscore or hyphen from the last path component."""
new_name = re.sub(r"^\d+[_-]", "", p.name)
return p.with_name(new_name)