-
Notifications
You must be signed in to change notification settings - Fork 16k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
text-splitters: Add JSFrameworkTextSplitter for Handling JavaScript Framework Code #28972
Draft
BenStuk
wants to merge
6
commits into
langchain-ai:master
Choose a base branch
from
BenStuk:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+265
−0
Draft
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
8a3aa9e
[feat] Add JSXTextSplitter to text splitters
BenStuk 175eb49
linting
BenStuk 87ebfdd
linting text splitter
BenStuk 0e6a5e2
linting
BenStuk 1f7be37
Refactor JSXTextSplitter to JSFrameworkTextSplitter; add support for …
BenStuk df1b83b
linting
BenStuk File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,124 @@ | ||
import re | ||
from typing import Any, List, Optional | ||
|
||
from langchain_text_splitters import RecursiveCharacterTextSplitter | ||
|
||
|
||
class JSFrameworkTextSplitter(RecursiveCharacterTextSplitter): | ||
"""Text splitter that handles React (JSX), Vue, and Svelte code. | ||
|
||
This splitter extends RecursiveCharacterTextSplitter to handle | ||
React (JSX), Vue, and Svelte code by: | ||
1. Detecting and extracting custom component tags from the text | ||
2. Using those tags as additional separators along with standard JS syntax | ||
|
||
The splitter combines: | ||
- Custom component tags as separators (e.g. <Component, <div) | ||
- JavaScript syntax elements (function, const, if, etc) | ||
- Standard text splitting on newlines | ||
|
||
This allows chunks to break at natural boundaries in | ||
React, Vue, and Svelte component code. | ||
""" | ||
|
||
def __init__( | ||
self, | ||
separators: Optional[List[str]] = None, | ||
chunk_size: int = 2000, | ||
chunk_overlap: int = 0, | ||
**kwargs: Any, | ||
) -> None: | ||
"""Initialize the JS Framework text splitter. | ||
|
||
Args: | ||
separators: Optional list of custom separator strings to use | ||
chunk_size: Maximum size of chunks to return | ||
chunk_overlap: Overlap in characters between chunks | ||
**kwargs: Additional arguments to pass to parent class | ||
""" | ||
super().__init__(chunk_size=chunk_size, chunk_overlap=chunk_overlap, **kwargs) | ||
self._separators = separators or [] | ||
|
||
def split_text(self, text: str) -> List[str]: | ||
"""Split text into chunks. | ||
|
||
This method splits the text into chunks by: | ||
- Extracting unique opening component tags using regex | ||
- Creating separators list with extracted tags and JS separators | ||
- Splitting the text using the separators by calling the parent class method | ||
- Handling chunk overlap if enabled | ||
|
||
Args: | ||
text: String containing code to split | ||
|
||
Returns: | ||
List of text chunks split on component and JS boundaries | ||
""" | ||
# Extract unique opening component tags using regex | ||
component_tags = list( | ||
set( | ||
tag.split(" ")[0].strip("<>\n") | ||
for tag in re.findall(r"<[^/\s][^>]*>", text) # Match opening tags | ||
if tag.strip() | ||
) | ||
) | ||
# Create separators list with extracted tags and default separators | ||
component_separators = [f"<{tag}" for tag in component_tags] | ||
component_separators = sorted( | ||
component_separators, | ||
key=lambda x: abs( | ||
len(component_separators) // 2 - component_separators.index(x) | ||
), | ||
) | ||
component_separators = list(set(component_separators)) | ||
|
||
js_separators = [ | ||
"\nexport ", | ||
" export ", | ||
"\nfunction ", | ||
"\nasync function ", | ||
" async function ", | ||
"\nconst ", | ||
"\nlet ", | ||
"\nvar ", | ||
"\nclass ", | ||
" class ", | ||
"\nif ", | ||
" if ", | ||
"\nfor ", | ||
" for ", | ||
"\nwhile ", | ||
" while ", | ||
"\nswitch ", | ||
" switch ", | ||
"\ncase ", | ||
" case ", | ||
"\ndefault ", | ||
" default ", | ||
] | ||
separators = ( | ||
self._separators | ||
+ js_separators | ||
+ component_separators | ||
+ ["<>", "\n\n", "&&\n", "||\n"] | ||
) | ||
self._separators = separators | ||
|
||
# Split the text using the separators | ||
chunks = super().split_text(text) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could you comment why the logic around chunk overlaps below is necessary following the call to |
||
|
||
# Handle chunk overlap | ||
if self._chunk_overlap > 0: | ||
# Create a new list to hold the final chunks with overlap | ||
final_chunks = [] | ||
for i in range(len(chunks)): | ||
if i == 0: | ||
final_chunks.append(chunks[i]) | ||
else: | ||
# Add the overlap from the previous chunk | ||
overlap_chunk = chunks[i - 1][-self._chunk_overlap :] + chunks[i] | ||
final_chunks.append(overlap_chunk) | ||
|
||
return final_chunks | ||
|
||
return chunks |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
CI is failing on
test_vue_text_splitter
, and I'm finding that this test is flaky when I run it locally (it fails around 50% of the time).I think it is due to the use of
list(set(...))
here and on line 73, since this is not deterministic. Usingsorted(set(...))
will likely fix it if that makes sense to you.