-
Notifications
You must be signed in to change notification settings - Fork 16
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: statistical chunker improvements
- Loading branch information
Showing
3 changed files
with
268 additions
and
1,437 deletions.
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
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 |
---|---|---|
@@ -1,7 +1,55 @@ | ||
import asyncio | ||
from functools import wraps | ||
import tiktoken | ||
import time | ||
from semantic_chunkers.utils.logger import logger | ||
|
||
|
||
def tiktoken_length(text: str) -> int: | ||
tokenizer = tiktoken.get_encoding("cl100k_base") | ||
tokens = tokenizer.encode(text, disallowed_special=()) | ||
return len(tokens) | ||
|
||
|
||
def time_it(func): | ||
async def async_wrapper(*args, **kwargs): | ||
start_time = time.time() | ||
result = await func(*args, **kwargs) # Await the async function | ||
end_time = time.time() | ||
logger.debug(f"{func.__name__} duration: {end_time - start_time:.2f} seconds") | ||
return result | ||
|
||
def sync_wrapper(*args, **kwargs): | ||
start_time = time.time() | ||
result = func(*args, **kwargs) # Call the sync function directly | ||
end_time = time.time() | ||
logger.debug(f"{func.__name__} duration: {end_time - start_time:.2f} seconds") | ||
return result | ||
|
||
if asyncio.iscoroutinefunction(func): | ||
return async_wrapper | ||
else: | ||
return sync_wrapper | ||
|
||
|
||
def async_retry_with_timeout(retries=3, timeout=10): | ||
def decorator(func): | ||
@wraps(func) | ||
async def wrapper(*args, **kwargs): | ||
for attempt in range(retries): | ||
try: | ||
return await asyncio.wait_for(func(*args, **kwargs), timeout) | ||
except asyncio.TimeoutError: | ||
logger.warning( | ||
f"Timeout on attempt {attempt+1} for {func.__name__}" | ||
) | ||
except Exception as e: | ||
logger.error( | ||
f"Exception on attempt {attempt+1} for {func.__name__}: {e}" | ||
) | ||
if attempt == retries - 1: | ||
raise | ||
else: | ||
await asyncio.sleep(2**attempt) # Exponential backoff | ||
return wrapper | ||
return decorator |