hammad-python 0.0.11__py3-none-any.whl → 0.0.13__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hammad/__init__.py +169 -56
- hammad/_core/__init__.py +1 -0
- hammad/_core/_utils/__init__.py +4 -0
- hammad/_core/_utils/_import_utils.py +182 -0
- hammad/ai/__init__.py +59 -0
- hammad/ai/_utils.py +142 -0
- hammad/ai/completions/__init__.py +44 -0
- hammad/ai/completions/client.py +729 -0
- hammad/ai/completions/create.py +686 -0
- hammad/ai/completions/types.py +711 -0
- hammad/ai/completions/utils.py +374 -0
- hammad/ai/embeddings/__init__.py +35 -0
- hammad/ai/embeddings/client/__init__.py +1 -0
- hammad/ai/embeddings/client/base_embeddings_client.py +26 -0
- hammad/ai/embeddings/client/fastembed_text_embeddings_client.py +200 -0
- hammad/ai/embeddings/client/litellm_embeddings_client.py +288 -0
- hammad/ai/embeddings/create.py +159 -0
- hammad/ai/embeddings/types.py +69 -0
- hammad/base/__init__.py +35 -0
- hammad/{based → base}/fields.py +23 -23
- hammad/{based → base}/model.py +124 -14
- hammad/base/utils.py +280 -0
- hammad/cache/__init__.py +30 -12
- hammad/cache/base_cache.py +181 -0
- hammad/cache/cache.py +169 -0
- hammad/cache/decorators.py +261 -0
- hammad/cache/file_cache.py +80 -0
- hammad/cache/ttl_cache.py +74 -0
- hammad/cli/__init__.py +10 -2
- hammad/cli/{styles/animations.py → animations.py} +79 -23
- hammad/cli/{plugins/__init__.py → plugins.py} +85 -90
- hammad/cli/styles/__init__.py +50 -0
- hammad/cli/styles/settings.py +4 -0
- hammad/configuration/__init__.py +35 -0
- hammad/{data/types/files → configuration}/configuration.py +96 -7
- hammad/data/__init__.py +14 -26
- hammad/data/collections/__init__.py +4 -2
- hammad/data/collections/collection.py +300 -75
- hammad/data/collections/vector_collection.py +118 -12
- hammad/data/databases/__init__.py +2 -2
- hammad/data/databases/database.py +383 -32
- hammad/json/__init__.py +2 -2
- hammad/logging/__init__.py +13 -5
- hammad/logging/decorators.py +404 -2
- hammad/logging/logger.py +442 -22
- hammad/multimodal/__init__.py +24 -0
- hammad/{data/types/files → multimodal}/audio.py +21 -6
- hammad/{data/types/files → multimodal}/image.py +5 -5
- hammad/multithreading/__init__.py +304 -0
- hammad/pydantic/__init__.py +2 -2
- hammad/pydantic/converters.py +1 -1
- hammad/pydantic/models/__init__.py +2 -2
- hammad/text/__init__.py +59 -14
- hammad/text/converters.py +723 -0
- hammad/text/{utils/markdown/formatting.py → markdown.py} +25 -23
- hammad/text/text.py +12 -14
- hammad/types/__init__.py +11 -0
- hammad/{data/types/files → types}/file.py +18 -18
- hammad/typing/__init__.py +138 -84
- hammad/web/__init__.py +3 -2
- hammad/web/models.py +245 -0
- hammad/web/search/client.py +75 -23
- hammad/web/utils.py +14 -5
- hammad/yaml/__init__.py +2 -2
- hammad/yaml/converters.py +1 -1
- {hammad_python-0.0.11.dist-info → hammad_python-0.0.13.dist-info}/METADATA +4 -1
- hammad_python-0.0.13.dist-info/RECORD +85 -0
- hammad/based/__init__.py +0 -52
- hammad/based/utils.py +0 -455
- hammad/cache/_cache.py +0 -746
- hammad/data/types/__init__.py +0 -33
- hammad/data/types/files/__init__.py +0 -1
- hammad/data/types/files/document.py +0 -195
- hammad/text/utils/__init__.py +0 -1
- hammad/text/utils/converters.py +0 -229
- hammad/text/utils/markdown/__init__.py +0 -1
- hammad/text/utils/markdown/converters.py +0 -506
- hammad_python-0.0.11.dist-info/RECORD +0 -65
- {hammad_python-0.0.11.dist-info → hammad_python-0.0.13.dist-info}/WHEEL +0 -0
- {hammad_python-0.0.11.dist-info → hammad_python-0.0.13.dist-info}/licenses/LICENSE +0 -0
hammad/logging/decorators.py
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
"""hammad.logging.tracers"""
|
2
2
|
|
3
|
-
from functools import wraps
|
3
|
+
from functools import wraps
|
4
4
|
from typing import (
|
5
5
|
Any,
|
6
6
|
Callable,
|
@@ -10,9 +10,10 @@ from typing import (
|
|
10
10
|
overload,
|
11
11
|
Union,
|
12
12
|
Type,
|
13
|
-
Dict,
|
14
13
|
Optional,
|
14
|
+
Awaitable,
|
15
15
|
)
|
16
|
+
import asyncio
|
16
17
|
|
17
18
|
import logging
|
18
19
|
import time
|
@@ -31,6 +32,8 @@ __all__ = (
|
|
31
32
|
"trace_function",
|
32
33
|
"trace_cls",
|
33
34
|
"trace",
|
35
|
+
"trace_http",
|
36
|
+
"install_trace_http",
|
34
37
|
)
|
35
38
|
|
36
39
|
|
@@ -430,3 +433,402 @@ def trace(
|
|
430
433
|
else:
|
431
434
|
# Called directly: @log
|
432
435
|
return decorator(func_or_cls)
|
436
|
+
|
437
|
+
|
438
|
+
def trace_http(
|
439
|
+
fn_or_call: Union[Callable[_P, _R], Callable[_P, Awaitable[_R]], Any, None] = None,
|
440
|
+
*,
|
441
|
+
show_request: bool = True,
|
442
|
+
show_response: bool = True,
|
443
|
+
request_exclude_none: bool = True,
|
444
|
+
response_exclude_none: bool = False,
|
445
|
+
logger: Union[logging.Logger, Logger, None] = None,
|
446
|
+
level: Union[LoggerLevelName, str, int] = "debug",
|
447
|
+
rich: bool = True,
|
448
|
+
style: Union[CLIStyleType, str] = "white",
|
449
|
+
bg: Union[CLIStyleBackgroundType, str] = None, # noqa: ARG001
|
450
|
+
) -> Any:
|
451
|
+
"""Wraps any function that makes HTTP requests, and displays only the request / response
|
452
|
+
bodies in a pretty panel. Can be used as a decorator or direct function wrapper.
|
453
|
+
|
454
|
+
Usage patterns:
|
455
|
+
1. As decorator: @trace_http
|
456
|
+
2. As decorator with params: @trace_http(show_request=False)
|
457
|
+
3. Direct function call: trace_http(my_function(), show_request=True)
|
458
|
+
4. Direct async function call: await trace_http(my_async_function(), show_request=True)
|
459
|
+
|
460
|
+
Args:
|
461
|
+
fn_or_call: The function to wrap, or the result of a function call.
|
462
|
+
show_request: Whether to show the request body.
|
463
|
+
show_response: Whether to show the response body.
|
464
|
+
request_exclude_none: Whether to exclude None values from request logging.
|
465
|
+
response_exclude_none: Whether to exclude None values from response logging.
|
466
|
+
logger: The logger to use.
|
467
|
+
level: The logging level.
|
468
|
+
rich: Whether to use rich formatting.
|
469
|
+
style: The style to use for the logging.
|
470
|
+
bg: The background to use for the logging (kept for API consistency).
|
471
|
+
|
472
|
+
Returns:
|
473
|
+
The decorated function, a decorator function, or the traced result.
|
474
|
+
"""
|
475
|
+
|
476
|
+
def _get_logger(name: str) -> Logger:
|
477
|
+
"""Get or create a logger."""
|
478
|
+
if logger is None:
|
479
|
+
return create_logger(name=name, level=level, rich=rich)
|
480
|
+
elif isinstance(logger, Logger):
|
481
|
+
return logger
|
482
|
+
else:
|
483
|
+
# It's a standard logging.Logger, wrap it
|
484
|
+
_logger = create_logger(name=logger.name)
|
485
|
+
_logger._logger = logger
|
486
|
+
return _logger
|
487
|
+
|
488
|
+
def _log_request_info(
|
489
|
+
bound_args: inspect.BoundArguments,
|
490
|
+
func_name: str,
|
491
|
+
module_name: str,
|
492
|
+
_logger: Logger,
|
493
|
+
):
|
494
|
+
"""Log HTTP request information."""
|
495
|
+
if not show_request:
|
496
|
+
return
|
497
|
+
|
498
|
+
# Simply log all arguments passed to the function
|
499
|
+
args_info = []
|
500
|
+
for param_name, param_value in bound_args.arguments.items():
|
501
|
+
# Skip None values if requested
|
502
|
+
if request_exclude_none and param_value is None:
|
503
|
+
continue
|
504
|
+
args_info.append(f"{param_name}: {repr(param_value)}")
|
505
|
+
|
506
|
+
if args_info:
|
507
|
+
if rich:
|
508
|
+
request_msg = f"[{style}]🌐 HTTP Request from {module_name}.{func_name}()[/{style}]"
|
509
|
+
request_msg += f"\n " + "\n ".join(args_info)
|
510
|
+
else:
|
511
|
+
request_msg = f"🌐 HTTP Request from {module_name}.{func_name}()"
|
512
|
+
request_msg += f"\n " + "\n ".join(args_info)
|
513
|
+
|
514
|
+
_logger.log(level, request_msg)
|
515
|
+
|
516
|
+
def _log_response_info(
|
517
|
+
result: Any, exec_time: float, func_name: str, module_name: str, _logger: Logger
|
518
|
+
):
|
519
|
+
"""Log HTTP response information."""
|
520
|
+
if not show_response:
|
521
|
+
return
|
522
|
+
|
523
|
+
# Skip None responses if requested
|
524
|
+
if response_exclude_none and result is None:
|
525
|
+
return
|
526
|
+
|
527
|
+
# Simply log the response as a string representation
|
528
|
+
result_str = str(result)
|
529
|
+
truncated_result = result_str[:500] + ("..." if len(result_str) > 500 else "")
|
530
|
+
|
531
|
+
if rich:
|
532
|
+
response_msg = f"[{style}]📥 HTTP Response to {module_name}.{func_name}() [dim](took {exec_time:.3f}s)[/dim][/{style}]"
|
533
|
+
response_msg += f"\n Response: {truncated_result}"
|
534
|
+
else:
|
535
|
+
response_msg = f"📥 HTTP Response to {module_name}.{func_name}() (took {exec_time:.3f}s)"
|
536
|
+
response_msg += f"\n Response: {truncated_result}"
|
537
|
+
|
538
|
+
_logger.log(level, response_msg)
|
539
|
+
|
540
|
+
def _log_error_info(
|
541
|
+
e: Exception,
|
542
|
+
exec_time: float,
|
543
|
+
func_name: str,
|
544
|
+
module_name: str,
|
545
|
+
_logger: Logger,
|
546
|
+
):
|
547
|
+
"""Log HTTP error information."""
|
548
|
+
error_style = "bold red" if rich else None
|
549
|
+
if rich:
|
550
|
+
error_msg = f"[{error_style}]❌ HTTP Error in {module_name}.{func_name}() [dim](after {exec_time:.3f}s)[/dim][/{error_style}]"
|
551
|
+
error_msg += f"\n [red]{type(e).__name__}: {str(e)}[/red]"
|
552
|
+
else:
|
553
|
+
error_msg = (
|
554
|
+
f"❌ HTTP Error in {module_name}.{func_name}() (after {exec_time:.3f}s)"
|
555
|
+
)
|
556
|
+
error_msg += f"\n {type(e).__name__}: {str(e)}"
|
557
|
+
|
558
|
+
_logger.error(error_msg)
|
559
|
+
|
560
|
+
def decorator(
|
561
|
+
target_fn: Union[Callable[_P, _R], Callable[_P, Awaitable[_R]]],
|
562
|
+
) -> Union[Callable[_P, _R], Callable[_P, Awaitable[_R]]]:
|
563
|
+
"""Decorator that wraps sync or async functions."""
|
564
|
+
|
565
|
+
if asyncio.iscoroutinefunction(target_fn):
|
566
|
+
# Async function
|
567
|
+
@wraps(target_fn)
|
568
|
+
async def async_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:
|
569
|
+
_logger = _get_logger(
|
570
|
+
f"http.{target_fn.__module__}.{target_fn.__name__}"
|
571
|
+
)
|
572
|
+
|
573
|
+
# Get function signature for parameter inspection
|
574
|
+
sig = inspect.signature(target_fn)
|
575
|
+
bound_args = sig.bind(*args, **kwargs)
|
576
|
+
bound_args.apply_defaults()
|
577
|
+
|
578
|
+
func_name = target_fn.__name__
|
579
|
+
module_name = target_fn.__module__
|
580
|
+
|
581
|
+
# Log request info
|
582
|
+
_log_request_info(bound_args, func_name, module_name, _logger)
|
583
|
+
|
584
|
+
# Track execution time
|
585
|
+
start_time = time.time()
|
586
|
+
|
587
|
+
try:
|
588
|
+
# Execute the async function
|
589
|
+
result = await target_fn(*args, **kwargs)
|
590
|
+
|
591
|
+
# Calculate execution time
|
592
|
+
exec_time = time.time() - start_time
|
593
|
+
|
594
|
+
# Log response info
|
595
|
+
_log_response_info(
|
596
|
+
result, exec_time, func_name, module_name, _logger
|
597
|
+
)
|
598
|
+
|
599
|
+
return result
|
600
|
+
|
601
|
+
except Exception as e:
|
602
|
+
# Calculate execution time
|
603
|
+
exec_time = time.time() - start_time
|
604
|
+
|
605
|
+
# Log error info
|
606
|
+
_log_error_info(e, exec_time, func_name, module_name, _logger)
|
607
|
+
|
608
|
+
# Re-raise the exception
|
609
|
+
raise
|
610
|
+
|
611
|
+
return async_wrapper
|
612
|
+
else:
|
613
|
+
# Sync function
|
614
|
+
@wraps(target_fn)
|
615
|
+
def sync_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:
|
616
|
+
_logger = _get_logger(
|
617
|
+
f"http.{target_fn.__module__}.{target_fn.__name__}"
|
618
|
+
)
|
619
|
+
|
620
|
+
# Get function signature for parameter inspection
|
621
|
+
sig = inspect.signature(target_fn)
|
622
|
+
bound_args = sig.bind(*args, **kwargs)
|
623
|
+
bound_args.apply_defaults()
|
624
|
+
|
625
|
+
func_name = target_fn.__name__
|
626
|
+
module_name = target_fn.__module__
|
627
|
+
|
628
|
+
# Log request info
|
629
|
+
_log_request_info(bound_args, func_name, module_name, _logger)
|
630
|
+
|
631
|
+
# Track execution time
|
632
|
+
start_time = time.time()
|
633
|
+
|
634
|
+
try:
|
635
|
+
# Execute the function
|
636
|
+
result = target_fn(*args, **kwargs)
|
637
|
+
|
638
|
+
# Calculate execution time
|
639
|
+
exec_time = time.time() - start_time
|
640
|
+
|
641
|
+
# Log response info
|
642
|
+
_log_response_info(
|
643
|
+
result, exec_time, func_name, module_name, _logger
|
644
|
+
)
|
645
|
+
|
646
|
+
return result
|
647
|
+
|
648
|
+
except Exception as e:
|
649
|
+
# Calculate execution time
|
650
|
+
exec_time = time.time() - start_time
|
651
|
+
|
652
|
+
# Log error info
|
653
|
+
_log_error_info(e, exec_time, func_name, module_name, _logger)
|
654
|
+
|
655
|
+
# Re-raise the exception
|
656
|
+
raise
|
657
|
+
|
658
|
+
return sync_wrapper
|
659
|
+
|
660
|
+
# Handle different usage patterns
|
661
|
+
if fn_or_call is None:
|
662
|
+
# Called with parameters: @trace_http(show_request=False)
|
663
|
+
return decorator
|
664
|
+
elif callable(fn_or_call):
|
665
|
+
# Called directly as decorator: @trace_http
|
666
|
+
return decorator(fn_or_call)
|
667
|
+
else:
|
668
|
+
# Called with a function result: trace_http(some_function(), ...)
|
669
|
+
# In this case, we can't trace the function call since it's already executed
|
670
|
+
# But we can still log the response
|
671
|
+
_logger = _get_logger("http.direct_call")
|
672
|
+
|
673
|
+
if show_response and fn_or_call is not None:
|
674
|
+
_log_response_info(fn_or_call, 0.0, "direct_call", "trace_http", _logger)
|
675
|
+
|
676
|
+
return fn_or_call
|
677
|
+
|
678
|
+
|
679
|
+
def install_trace_http(
|
680
|
+
*,
|
681
|
+
show_request: bool = True,
|
682
|
+
show_response: bool = True,
|
683
|
+
request_exclude_none: bool = True,
|
684
|
+
response_exclude_none: bool = False,
|
685
|
+
logger: Union[logging.Logger, Logger, None] = None,
|
686
|
+
level: Union[LoggerLevelName, str, int] = "debug",
|
687
|
+
rich: bool = True,
|
688
|
+
style: Union[CLIStyleType, str] = "white",
|
689
|
+
bg: Union[CLIStyleBackgroundType, str] = None, # noqa: ARG001
|
690
|
+
patch_imports: bool = True,
|
691
|
+
) -> None:
|
692
|
+
"""Install global HTTP tracing for all HTTP-related functions.
|
693
|
+
|
694
|
+
This function patches common HTTP libraries to automatically trace all
|
695
|
+
HTTP requests and responses without needing to manually decorate functions.
|
696
|
+
|
697
|
+
Args:
|
698
|
+
show_request: Whether to show the request body.
|
699
|
+
show_response: Whether to show the response body.
|
700
|
+
request_exclude_none: Whether to exclude None values from request logging.
|
701
|
+
response_exclude_none: Whether to exclude None values from response logging.
|
702
|
+
logger: The logger to use.
|
703
|
+
level: The logging level.
|
704
|
+
rich: Whether to use rich formatting.
|
705
|
+
style: The style to use for the logging.
|
706
|
+
bg: The background to use for the logging (kept for API consistency).
|
707
|
+
patch_imports: Whether to also patch the import mechanism for future imports.
|
708
|
+
"""
|
709
|
+
import sys
|
710
|
+
|
711
|
+
# Create a tracer function with the specified settings
|
712
|
+
def create_tracer(original_func):
|
713
|
+
return trace_http(
|
714
|
+
original_func,
|
715
|
+
show_request=show_request,
|
716
|
+
show_response=show_response,
|
717
|
+
request_exclude_none=request_exclude_none,
|
718
|
+
response_exclude_none=response_exclude_none,
|
719
|
+
logger=logger,
|
720
|
+
level=level,
|
721
|
+
rich=rich,
|
722
|
+
style=style,
|
723
|
+
bg=bg,
|
724
|
+
)
|
725
|
+
|
726
|
+
# List of common HTTP libraries and their functions to patch
|
727
|
+
patches = [
|
728
|
+
# requests library
|
729
|
+
("requests", "get"),
|
730
|
+
("requests", "post"),
|
731
|
+
("requests", "put"),
|
732
|
+
("requests", "delete"),
|
733
|
+
("requests", "patch"),
|
734
|
+
("requests", "head"),
|
735
|
+
("requests", "options"),
|
736
|
+
("requests", "request"),
|
737
|
+
# httpx library
|
738
|
+
("httpx", "get"),
|
739
|
+
("httpx", "post"),
|
740
|
+
("httpx", "put"),
|
741
|
+
("httpx", "delete"),
|
742
|
+
("httpx", "patch"),
|
743
|
+
("httpx", "head"),
|
744
|
+
("httpx", "options"),
|
745
|
+
("httpx", "request"),
|
746
|
+
# urllib3
|
747
|
+
("urllib3", "request"),
|
748
|
+
# aiohttp
|
749
|
+
("aiohttp", "request"),
|
750
|
+
]
|
751
|
+
|
752
|
+
patched_functions = []
|
753
|
+
|
754
|
+
for module_name, func_name in patches:
|
755
|
+
try:
|
756
|
+
# Check if module is already imported
|
757
|
+
if module_name in sys.modules:
|
758
|
+
module = sys.modules[module_name]
|
759
|
+
|
760
|
+
# Handle nested module paths like "openai.chat.completions"
|
761
|
+
if "." in module_name:
|
762
|
+
module_parts = module_name.split(".")
|
763
|
+
for part in module_parts[1:]:
|
764
|
+
if hasattr(module, part):
|
765
|
+
module = getattr(module, part)
|
766
|
+
else:
|
767
|
+
break
|
768
|
+
else:
|
769
|
+
# Successfully navigated to nested module
|
770
|
+
if hasattr(module, func_name):
|
771
|
+
original_func = getattr(module, func_name)
|
772
|
+
traced_func = create_tracer(original_func)
|
773
|
+
setattr(module, func_name, traced_func)
|
774
|
+
patched_functions.append(f"{module_name}.{func_name}")
|
775
|
+
else:
|
776
|
+
# Simple module path
|
777
|
+
if hasattr(module, func_name):
|
778
|
+
original_func = getattr(module, func_name)
|
779
|
+
traced_func = create_tracer(original_func)
|
780
|
+
setattr(module, func_name, traced_func)
|
781
|
+
patched_functions.append(f"{module_name}.{func_name}")
|
782
|
+
|
783
|
+
# Special handling for litellm - also patch litellm.main if available
|
784
|
+
if module_name == "litellm" and "litellm.main" in sys.modules:
|
785
|
+
main_module = sys.modules["litellm.main"]
|
786
|
+
if hasattr(main_module, func_name):
|
787
|
+
setattr(main_module, func_name, traced_func)
|
788
|
+
|
789
|
+
# Also check if the nested module exists in sys.modules for litellm.main case
|
790
|
+
elif "." in module_name and module_name in sys.modules:
|
791
|
+
module = sys.modules[module_name]
|
792
|
+
if hasattr(module, func_name):
|
793
|
+
original_func = getattr(module, func_name)
|
794
|
+
traced_func = create_tracer(original_func)
|
795
|
+
setattr(module, func_name, traced_func)
|
796
|
+
patched_functions.append(f"{module_name}.{func_name}")
|
797
|
+
|
798
|
+
# If this is litellm.main, also patch the main litellm module
|
799
|
+
if module_name == "litellm.main" and "litellm" in sys.modules:
|
800
|
+
main_litellm = sys.modules["litellm"]
|
801
|
+
if hasattr(main_litellm, func_name):
|
802
|
+
setattr(main_litellm, func_name, traced_func)
|
803
|
+
|
804
|
+
except (ImportError, AttributeError):
|
805
|
+
# Module not available or function doesn't exist
|
806
|
+
continue
|
807
|
+
|
808
|
+
# Log what was patched
|
809
|
+
if patched_functions:
|
810
|
+
_logger = (
|
811
|
+
logger
|
812
|
+
if isinstance(logger, Logger)
|
813
|
+
else create_logger(name="http.install_trace", level=level, rich=rich)
|
814
|
+
)
|
815
|
+
|
816
|
+
if rich:
|
817
|
+
install_msg = f"[{style}]✨ Installed HTTP tracing on {len(patched_functions)} functions[/{style}]"
|
818
|
+
install_msg += f"\n " + "\n ".join(patched_functions)
|
819
|
+
else:
|
820
|
+
install_msg = (
|
821
|
+
f"✨ Installed HTTP tracing on {len(patched_functions)} functions"
|
822
|
+
)
|
823
|
+
install_msg += f"\n " + "\n ".join(patched_functions)
|
824
|
+
|
825
|
+
_logger.info(install_msg)
|
826
|
+
else:
|
827
|
+
_logger = (
|
828
|
+
logger
|
829
|
+
if isinstance(logger, Logger)
|
830
|
+
else create_logger(name="http.install_trace", level=level, rich=rich)
|
831
|
+
)
|
832
|
+
_logger.warning(
|
833
|
+
"No HTTP functions found to patch. Import HTTP libraries first."
|
834
|
+
)
|