hammad-python 0.0.14__py3-none-any.whl → 0.0.16__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.
Files changed (122) hide show
  1. hammad/__init__.py +177 -0
  2. hammad/{performance/imports.py → _internal.py} +7 -1
  3. hammad/cache/__init__.py +1 -1
  4. hammad/cli/__init__.py +3 -1
  5. hammad/cli/_runner.py +265 -0
  6. hammad/cli/animations.py +1 -1
  7. hammad/cli/plugins.py +133 -78
  8. hammad/cli/styles/__init__.py +1 -1
  9. hammad/cli/styles/utils.py +149 -3
  10. hammad/data/__init__.py +56 -29
  11. hammad/data/collections/__init__.py +27 -17
  12. hammad/data/collections/collection.py +205 -383
  13. hammad/data/collections/indexes/__init__.py +37 -0
  14. hammad/data/collections/indexes/qdrant/__init__.py +1 -0
  15. hammad/data/collections/indexes/qdrant/index.py +735 -0
  16. hammad/data/collections/indexes/qdrant/settings.py +94 -0
  17. hammad/data/collections/indexes/qdrant/utils.py +220 -0
  18. hammad/data/collections/indexes/tantivy/__init__.py +1 -0
  19. hammad/data/collections/indexes/tantivy/index.py +428 -0
  20. hammad/data/collections/indexes/tantivy/settings.py +51 -0
  21. hammad/data/collections/indexes/tantivy/utils.py +200 -0
  22. hammad/data/configurations/__init__.py +2 -2
  23. hammad/data/configurations/configuration.py +2 -2
  24. hammad/data/models/__init__.py +20 -9
  25. hammad/data/models/extensions/__init__.py +4 -0
  26. hammad/data/models/{pydantic → extensions/pydantic}/__init__.py +6 -19
  27. hammad/data/models/{pydantic → extensions/pydantic}/converters.py +143 -16
  28. hammad/data/models/{base/fields.py → fields.py} +1 -1
  29. hammad/data/models/{base/model.py → model.py} +1 -1
  30. hammad/data/models/{base/utils.py → utils.py} +1 -1
  31. hammad/data/sql/__init__.py +23 -0
  32. hammad/data/sql/database.py +578 -0
  33. hammad/data/sql/types.py +141 -0
  34. hammad/data/types/__init__.py +1 -3
  35. hammad/data/types/file.py +3 -3
  36. hammad/data/types/multimodal/__init__.py +2 -2
  37. hammad/data/types/multimodal/audio.py +2 -2
  38. hammad/data/types/multimodal/image.py +2 -2
  39. hammad/formatting/__init__.py +9 -27
  40. hammad/formatting/json/__init__.py +8 -2
  41. hammad/formatting/json/converters.py +7 -1
  42. hammad/formatting/text/__init__.py +1 -1
  43. hammad/formatting/yaml/__init__.py +1 -1
  44. hammad/genai/__init__.py +78 -0
  45. hammad/genai/agents/__init__.py +1 -0
  46. hammad/genai/agents/types/__init__.py +35 -0
  47. hammad/genai/agents/types/history.py +277 -0
  48. hammad/genai/agents/types/tool.py +490 -0
  49. hammad/genai/embedding_models/__init__.py +41 -0
  50. hammad/{ai/embeddings/client/litellm_embeddings_client.py → genai/embedding_models/embedding_model.py} +47 -142
  51. hammad/genai/embedding_models/embedding_model_name.py +77 -0
  52. hammad/genai/embedding_models/embedding_model_request.py +65 -0
  53. hammad/{ai/embeddings/types.py → genai/embedding_models/embedding_model_response.py} +3 -3
  54. hammad/genai/embedding_models/run.py +161 -0
  55. hammad/genai/language_models/__init__.py +35 -0
  56. hammad/genai/language_models/_streaming.py +622 -0
  57. hammad/genai/language_models/_types.py +276 -0
  58. hammad/genai/language_models/_utils/__init__.py +31 -0
  59. hammad/genai/language_models/_utils/_completions.py +131 -0
  60. hammad/genai/language_models/_utils/_messages.py +89 -0
  61. hammad/genai/language_models/_utils/_requests.py +202 -0
  62. hammad/genai/language_models/_utils/_structured_outputs.py +124 -0
  63. hammad/genai/language_models/language_model.py +734 -0
  64. hammad/genai/language_models/language_model_request.py +135 -0
  65. hammad/genai/language_models/language_model_response.py +219 -0
  66. hammad/genai/language_models/language_model_response_chunk.py +53 -0
  67. hammad/genai/language_models/run.py +530 -0
  68. hammad/genai/multimodal_models.py +48 -0
  69. hammad/genai/rerank_models.py +26 -0
  70. hammad/logging/__init__.py +1 -1
  71. hammad/logging/decorators.py +1 -1
  72. hammad/logging/logger.py +2 -2
  73. hammad/mcp/__init__.py +1 -1
  74. hammad/mcp/client/__init__.py +35 -0
  75. hammad/mcp/client/client.py +105 -4
  76. hammad/mcp/client/client_service.py +10 -3
  77. hammad/mcp/servers/__init__.py +24 -0
  78. hammad/{performance/runtime → runtime}/__init__.py +2 -2
  79. hammad/{performance/runtime → runtime}/decorators.py +1 -1
  80. hammad/{performance/runtime → runtime}/run.py +1 -1
  81. hammad/service/__init__.py +1 -1
  82. hammad/service/create.py +3 -8
  83. hammad/service/decorators.py +8 -8
  84. hammad/typing/__init__.py +28 -0
  85. hammad/web/__init__.py +3 -3
  86. hammad/web/http/client.py +1 -1
  87. hammad/web/models.py +53 -21
  88. hammad/web/search/client.py +99 -52
  89. hammad/web/utils.py +13 -13
  90. hammad_python-0.0.16.dist-info/METADATA +191 -0
  91. hammad_python-0.0.16.dist-info/RECORD +110 -0
  92. hammad/ai/__init__.py +0 -1
  93. hammad/ai/_utils.py +0 -142
  94. hammad/ai/completions/__init__.py +0 -45
  95. hammad/ai/completions/client.py +0 -684
  96. hammad/ai/completions/create.py +0 -710
  97. hammad/ai/completions/settings.py +0 -100
  98. hammad/ai/completions/types.py +0 -792
  99. hammad/ai/completions/utils.py +0 -486
  100. hammad/ai/embeddings/__init__.py +0 -35
  101. hammad/ai/embeddings/client/__init__.py +0 -1
  102. hammad/ai/embeddings/client/base_embeddings_client.py +0 -26
  103. hammad/ai/embeddings/client/fastembed_text_embeddings_client.py +0 -200
  104. hammad/ai/embeddings/create.py +0 -159
  105. hammad/data/collections/base_collection.py +0 -58
  106. hammad/data/collections/searchable_collection.py +0 -556
  107. hammad/data/collections/vector_collection.py +0 -596
  108. hammad/data/databases/__init__.py +0 -21
  109. hammad/data/databases/database.py +0 -902
  110. hammad/data/models/base/__init__.py +0 -35
  111. hammad/data/models/pydantic/models/__init__.py +0 -28
  112. hammad/data/models/pydantic/models/arbitrary_model.py +0 -46
  113. hammad/data/models/pydantic/models/cacheable_model.py +0 -79
  114. hammad/data/models/pydantic/models/fast_model.py +0 -318
  115. hammad/data/models/pydantic/models/function_model.py +0 -176
  116. hammad/data/models/pydantic/models/subscriptable_model.py +0 -63
  117. hammad/performance/__init__.py +0 -36
  118. hammad/py.typed +0 -0
  119. hammad_python-0.0.14.dist-info/METADATA +0 -70
  120. hammad_python-0.0.14.dist-info/RECORD +0 -99
  121. {hammad_python-0.0.14.dist-info → hammad_python-0.0.16.dist-info}/WHEEL +0 -0
  122. {hammad_python-0.0.14.dist-info → hammad_python-0.0.16.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,94 @@
1
+ """hammad.data.collections.indexes.qdrant.settings"""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import (
5
+ Any,
6
+ Dict,
7
+ Optional,
8
+ Literal,
9
+ )
10
+
11
+ __all__ = (
12
+ "QdrantCollectionIndexSettings",
13
+ "QdrantCollectionIndexQuerySettings",
14
+ "DistanceMetric",
15
+ )
16
+
17
+
18
+ DistanceMetric = Literal[
19
+ "cosine",
20
+ "dot",
21
+ "euclidean",
22
+ "manhattan",
23
+ ]
24
+
25
+
26
+ @dataclass
27
+ class QdrantCollectionIndexSettings:
28
+ """Object representation of user configurable settings
29
+ that can be used to configure a `QdrantCollectionIndex`."""
30
+
31
+ vector_size: int = 768
32
+ """The size/dimension of the vectors to store."""
33
+
34
+ distance_metric: DistanceMetric = "dot"
35
+ """Distance metric for similarity search."""
36
+
37
+ path: Optional[str] = None
38
+ """Path for local Qdrant storage (None = in-memory)."""
39
+
40
+ host: Optional[str] = None
41
+ """Qdrant server host (if using remote server)."""
42
+
43
+ port: int = 6333
44
+ """Qdrant server port."""
45
+
46
+ grpc_port: int = 6334
47
+ """Qdrant gRPC port."""
48
+
49
+ prefer_grpc: bool = False
50
+ """Whether to prefer gRPC over HTTP."""
51
+
52
+ api_key: Optional[str] = None
53
+ """API key for Qdrant authentication."""
54
+
55
+ timeout: Optional[float] = None
56
+ """Request timeout for Qdrant operations."""
57
+
58
+ def get_qdrant_config(self) -> Dict[str, Any]:
59
+ """Returns a configuration dictionary used
60
+ to configure the qdrant client internally."""
61
+ config = {}
62
+
63
+ if self.path is not None:
64
+ config["path"] = self.path
65
+ elif self.host is not None:
66
+ config["host"] = self.host
67
+ config["port"] = self.port
68
+ config["grpc_port"] = self.grpc_port
69
+ config["prefer_grpc"] = self.prefer_grpc
70
+ if self.api_key:
71
+ config["api_key"] = self.api_key
72
+ if self.timeout:
73
+ config["timeout"] = self.timeout
74
+ else:
75
+ # In-memory database
76
+ config["location"] = ":memory:"
77
+
78
+ return config
79
+
80
+
81
+ @dataclass
82
+ class QdrantCollectionIndexQuerySettings:
83
+ """Object representation of user configurable settings
84
+ that can be used to configure the query engine for a
85
+ `QdrantCollectionIndex`."""
86
+
87
+ limit: int = 10
88
+ """The maximum number of results to return."""
89
+
90
+ score_threshold: Optional[float] = None
91
+ """Minimum similarity score threshold for results."""
92
+
93
+ exact: bool = False
94
+ """Whether to use exact search (slower but more accurate)."""
@@ -0,0 +1,220 @@
1
+ """hammad.data.collections.indexes.qdrant.utils"""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import (
5
+ Any,
6
+ Dict,
7
+ List,
8
+ Optional,
9
+ Union,
10
+ final
11
+ )
12
+ import uuid
13
+
14
+ from .....cache import cached
15
+ from .settings import (
16
+ QdrantCollectionIndexSettings,
17
+ QdrantCollectionIndexQuerySettings,
18
+ DistanceMetric,
19
+ )
20
+
21
+ # Lazy imports to avoid errors when qdrant is not installed
22
+ try:
23
+ import numpy as np
24
+ NUMPY_AVAILABLE = True
25
+ except ImportError:
26
+ NUMPY_AVAILABLE = False
27
+
28
+ __all__ = (
29
+ "QdrantCollectionIndexError",
30
+ "QdrantClientWrapper",
31
+ "create_qdrant_client",
32
+ "prepare_vector",
33
+ "convert_distance_metric",
34
+ "serialize",
35
+ )
36
+
37
+
38
+ class QdrantCollectionIndexError(Exception):
39
+ """Exception raised when an error occurs in the `QdrantCollectionIndex`."""
40
+
41
+
42
+ @dataclass
43
+ class QdrantClientWrapper:
44
+ """Wrapper over the qdrant client and collection setup."""
45
+
46
+ client: Any
47
+ """The qdrant client object."""
48
+
49
+ collection_name: str
50
+ """The name of the qdrant collection."""
51
+
52
+
53
+ @cached
54
+ def convert_distance_metric(metric: DistanceMetric) -> Any:
55
+ """Convert string distance metric to qdrant Distance enum."""
56
+ try:
57
+ from qdrant_client.models import Distance
58
+
59
+ mapping = {
60
+ "cosine": Distance.COSINE,
61
+ "dot": Distance.DOT,
62
+ "euclidean": Distance.EUCLID,
63
+ "manhattan": Distance.MANHATTAN,
64
+ }
65
+
66
+ return mapping.get(metric, Distance.DOT)
67
+ except ImportError:
68
+ raise QdrantCollectionIndexError(
69
+ "qdrant-client is required for QdrantCollectionIndex. "
70
+ "Install with: pip install qdrant-client"
71
+ )
72
+
73
+
74
+ @cached
75
+ def create_qdrant_client(settings: QdrantCollectionIndexSettings) -> Any:
76
+ """Create a qdrant client from settings."""
77
+ try:
78
+ from qdrant_client import QdrantClient
79
+ except ImportError:
80
+ raise QdrantCollectionIndexError(
81
+ "qdrant-client is required for QdrantCollectionIndex. "
82
+ "Install with: pip install qdrant-client"
83
+ )
84
+
85
+ config = settings.get_qdrant_config()
86
+
87
+ if "path" in config:
88
+ # Local persistent storage
89
+ return QdrantClient(path=config["path"])
90
+ elif "host" in config:
91
+ # Remote server
92
+ client_kwargs = {
93
+ "host": config["host"],
94
+ "port": config.get("port", 6333),
95
+ "grpc_port": config.get("grpc_port", 6334),
96
+ "prefer_grpc": config.get("prefer_grpc", False),
97
+ }
98
+
99
+ if config.get("api_key"):
100
+ client_kwargs["api_key"] = config["api_key"]
101
+ if config.get("timeout"):
102
+ client_kwargs["timeout"] = config["timeout"]
103
+
104
+ return QdrantClient(**client_kwargs)
105
+ else:
106
+ # In-memory database
107
+ return QdrantClient(":memory:")
108
+
109
+
110
+ def prepare_vector(
111
+ vector: Union[List[float], Any],
112
+ expected_size: int,
113
+ ) -> List[float]:
114
+ """Prepare and validate a vector for qdrant storage."""
115
+ if NUMPY_AVAILABLE and hasattr(vector, 'tolist'):
116
+ # Handle numpy arrays
117
+ vector = vector.tolist()
118
+ elif not isinstance(vector, list):
119
+ raise QdrantCollectionIndexError(
120
+ f"Vector must be a list or numpy array, got {type(vector)}"
121
+ )
122
+
123
+ if len(vector) != expected_size:
124
+ raise QdrantCollectionIndexError(
125
+ f"Vector size {len(vector)} doesn't match expected size {expected_size}"
126
+ )
127
+
128
+ # Ensure all elements are floats
129
+ try:
130
+ return [float(x) for x in vector]
131
+ except (TypeError, ValueError) as e:
132
+ raise QdrantCollectionIndexError(
133
+ f"Vector contains non-numeric values: {e}"
134
+ )
135
+
136
+
137
+ def build_qdrant_filter(filters: Optional[Dict[str, Any]]) -> Optional[Any]:
138
+ """Build qdrant filter from filters dict."""
139
+ if not filters:
140
+ return None
141
+
142
+ try:
143
+ from qdrant_client.models import Filter, FieldCondition, MatchValue
144
+
145
+ conditions = []
146
+ for key, value in filters.items():
147
+ conditions.append(
148
+ FieldCondition(key=key, match=MatchValue(value=value))
149
+ )
150
+
151
+ if len(conditions) == 1:
152
+ return Filter(must=[conditions[0]])
153
+ else:
154
+ return Filter(must=conditions)
155
+
156
+ except ImportError:
157
+ raise QdrantCollectionIndexError(
158
+ "qdrant-client is required for QdrantCollectionIndex. "
159
+ "Install with: pip install qdrant-client"
160
+ )
161
+
162
+
163
+ def create_collection_if_not_exists(
164
+ client: Any,
165
+ collection_name: str,
166
+ settings: QdrantCollectionIndexSettings,
167
+ ) -> None:
168
+ """Create qdrant collection if it doesn't exist."""
169
+ try:
170
+ from qdrant_client.models import VectorParams
171
+
172
+ # Check if collection exists
173
+ try:
174
+ collections = client.get_collections()
175
+ collection_names = [col.name for col in collections.collections]
176
+
177
+ if collection_name not in collection_names:
178
+ # Create collection
179
+ distance_metric = convert_distance_metric(settings.distance_metric)
180
+
181
+ client.create_collection(
182
+ collection_name=collection_name,
183
+ vectors_config=VectorParams(
184
+ size=settings.vector_size,
185
+ distance=distance_metric
186
+ ),
187
+ )
188
+ except Exception:
189
+ # Collection might already exist or other issue
190
+ pass
191
+
192
+ except ImportError:
193
+ raise QdrantCollectionIndexError(
194
+ "qdrant-client is required for QdrantCollectionIndex. "
195
+ "Install with: pip install qdrant-client"
196
+ )
197
+
198
+
199
+ @cached
200
+ def serialize(obj: Any) -> Any:
201
+ """Serialize an object to JSON-compatible format."""
202
+ try:
203
+ from msgspec import json
204
+ return json.decode(json.encode(obj))
205
+ except Exception:
206
+ # Fallback to manual serialization if msgspec fails
207
+ from dataclasses import is_dataclass, asdict
208
+
209
+ if isinstance(obj, (str, int, float, bool, type(None))):
210
+ return obj
211
+ elif isinstance(obj, (list, tuple)):
212
+ return [serialize(item) for item in obj]
213
+ elif isinstance(obj, dict):
214
+ return {k: serialize(v) for k, v in obj.items()}
215
+ elif is_dataclass(obj):
216
+ return serialize(asdict(obj))
217
+ elif hasattr(obj, "__dict__"):
218
+ return serialize(obj.__dict__)
219
+ else:
220
+ return str(obj)
@@ -0,0 +1 @@
1
+ """hammad.data.collections.indexes.tantivy"""