weaviate-agents 0.1.0__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.
@@ -0,0 +1,191 @@
1
+ import httpx
2
+ import pytest
3
+ from pydantic import ValidationError
4
+
5
+ from weaviate_agents.classes.query import CollectionDescription, QueryAgentResponse
6
+ from weaviate_agents.errors import QueryAgentError
7
+ from weaviate_agents.query import QueryAgent
8
+
9
+
10
+ class DummyClient:
11
+ """A dummy client to simulate the Weaviate client for testing purposes."""
12
+
13
+ def __init__(self):
14
+ self._connection = self # Simulate connection
15
+ self.url = "http://test-url:443" # Add url attribute
16
+ self.additional_headers = {"Authorization": "test-token"}
17
+
18
+ def get_current_bearer_token(self) -> str:
19
+ """Simulate bearer token retrieval from connection.
20
+
21
+ Returns:
22
+ str: The test bearer token prefixed with 'Bearer '.
23
+ """
24
+ return "Bearer test-token"
25
+
26
+
27
+ class FakeResponse:
28
+ """A fake HTTP response for testing purposes.
29
+
30
+ Attributes:
31
+ status_code (int): The HTTP status code.
32
+ _json (dict): The JSON data to return.
33
+ """
34
+
35
+ def __init__(self, status_code: int, json_data: dict):
36
+ self.status_code = status_code
37
+ self._json = json_data
38
+
39
+ def json(self) -> dict:
40
+ """Return the JSON data of the fake response.
41
+
42
+ Returns:
43
+ dict: The JSON data.
44
+ """
45
+ return self._json
46
+
47
+
48
+ def fake_post_success(*args, **kwargs) -> FakeResponse:
49
+ """Simulate a successful HTTP POST response.
50
+
51
+ Returns:
52
+ FakeResponse: A fake HTTP response with status code 200.
53
+ """
54
+ json_data = {
55
+ "original_query": "test query",
56
+ "collection_names": ["test_collection"],
57
+ "searches": [],
58
+ "aggregations": [],
59
+ "usage": {
60
+ "requests": 1,
61
+ "request_tokens": 10,
62
+ "response_tokens": 20,
63
+ "total_tokens": 30,
64
+ "details": {},
65
+ },
66
+ "total_time": 0.1,
67
+ "search_answer": None,
68
+ "aggregation_answer": None,
69
+ "has_aggregation_answer": False,
70
+ "has_search_answer": False,
71
+ "is_partial_answer": False,
72
+ "missing_information": [],
73
+ "final_answer": "final answer",
74
+ }
75
+ return FakeResponse(200, json_data)
76
+
77
+
78
+ def fake_post_failure(*args, **kwargs) -> FakeResponse:
79
+ """Simulate a failed HTTP POST response.
80
+
81
+ Returns:
82
+ FakeResponse: A fake HTTP response with a non-200 status code.
83
+ """
84
+ json_data = {
85
+ "error": {
86
+ "message": "Test error message",
87
+ "code": "test_error_code",
88
+ "details": {"info": "test detail"},
89
+ }
90
+ }
91
+ return FakeResponse(400, json_data)
92
+
93
+
94
+ def test_run_success(monkeypatch):
95
+ """Test that QueryAgent.run returns a valid QueryAgentResponse when the HTTP call is successful.
96
+
97
+ Returns:
98
+ None.
99
+ """
100
+ monkeypatch.setattr(httpx, "post", fake_post_success)
101
+ dummy_client = DummyClient()
102
+ agent = QueryAgent(
103
+ dummy_client, ["test_collection"], agents_host="http://dummy-agent"
104
+ )
105
+ agent._connection = dummy_client
106
+ agent._headers = dummy_client.additional_headers
107
+
108
+ result = agent.run("test query")
109
+ assert isinstance(result, QueryAgentResponse)
110
+ assert result.original_query == "test query"
111
+ assert result.collection_names == ["test_collection"]
112
+ assert result.total_time == 0.1
113
+ assert result.final_answer == "final answer"
114
+
115
+
116
+ def test_run_failure(monkeypatch):
117
+ """Test that QueryAgent.run raises a QueryAgentError when the HTTP response indicates an error.
118
+
119
+ Returns:
120
+ None.
121
+ """
122
+ monkeypatch.setattr(httpx, "post", fake_post_failure)
123
+ dummy_client = DummyClient()
124
+ agent = QueryAgent(
125
+ dummy_client, ["test_collection"], agents_host="http://dummy-agent"
126
+ )
127
+ agent._connection = dummy_client
128
+ agent._headers = dummy_client.additional_headers
129
+
130
+ with pytest.raises(QueryAgentError) as exc_info:
131
+ agent.run("failure query")
132
+ error = exc_info.value
133
+ assert error.message == "Test error message"
134
+ assert error.code == "test_error_code"
135
+ assert error.details == {"info": "test detail"}
136
+ assert error.status_code == 400
137
+
138
+
139
+ def test_add_and_remove_collection():
140
+ """Test the add_collection and remove_collection methods of the QueryAgent.
141
+
142
+ Returns:
143
+ None.
144
+ """
145
+ dummy_client = DummyClient()
146
+ initial_collections = [
147
+ "col1",
148
+ CollectionDescription(name="col2", description="desc2"),
149
+ ]
150
+ agent = QueryAgent(
151
+ dummy_client, initial_collections, agents_host="http://dummy-agent"
152
+ )
153
+ agent._connection = dummy_client
154
+ agent._headers = dummy_client.additional_headers
155
+
156
+ # Test add_collection: adding a duplicate should not increase the number of collections.
157
+ agent.add_collection("col1")
158
+ assert len(agent._collections) == 2
159
+
160
+ # Add a new collection as a string.
161
+ agent.add_collection("col3")
162
+ assert len(agent._collections) == 3
163
+
164
+ # Add a collection as a CollectionDescription with a duplicate name.
165
+ agent.add_collection(
166
+ CollectionDescription(name="col2", description="different desc")
167
+ )
168
+ assert len(agent._collections) == 3
169
+
170
+ # Remove collection by string.
171
+ agent.remove_collection("col1")
172
+ assert len(agent._collections) == 2
173
+
174
+ # Remove collection using CollectionDescription (by name).
175
+ agent.remove_collection(CollectionDescription(name="col2", description="any desc"))
176
+ assert len(agent._collections) == 1
177
+
178
+ # Removing a non-existing collection should not raise an error.
179
+ agent.remove_collection("non_existing")
180
+ assert len(agent._collections) == 1
181
+
182
+
183
+ def test_query_agent_response_model_validation():
184
+ """Test that the QueryAgentResponse model raises a ValidationError when required fields are missing.
185
+
186
+ Returns:
187
+ None.
188
+ """
189
+ incomplete_data = {"original_query": "incomplete query"}
190
+ with pytest.raises(ValidationError):
191
+ QueryAgentResponse(**incomplete_data)
File without changes
@@ -0,0 +1,33 @@
1
+ from typing import Union
2
+
3
+ from weaviate.client import WeaviateAsyncClient, WeaviateClient
4
+
5
+
6
+ class _BaseAgent:
7
+ """
8
+ Base class for all agents.
9
+ """
10
+
11
+ def __init__(
12
+ self,
13
+ client: Union[WeaviateClient, WeaviateAsyncClient],
14
+ agents_host: Union[str, None] = None,
15
+ ):
16
+ """
17
+ Initialize the base agent.
18
+
19
+ Args:
20
+ client: A Weaviate client instance, either sync or async.
21
+ agents_host: Optional host URL for the agents service. If not provided,
22
+ will use the default agents host.
23
+ """
24
+ self._client = client
25
+ self._connection = client._connection
26
+ self._agents_host = agents_host or "https://api.agents.weaviate.io"
27
+
28
+ self._headers = {
29
+ "Authorization": self._connection.get_current_bearer_token().replace(
30
+ "Bearer ", ""
31
+ ),
32
+ "X-Weaviate-Cluster-Url": self._client._connection.url.replace(":443", ""),
33
+ }
@@ -0,0 +1,3 @@
1
+ from . import query, transformation
2
+
3
+ __all__ = ["transformation", "query"]
@@ -0,0 +1,3 @@
1
+ from weaviate_agents.query.classes import CollectionDescription, QueryAgentResponse
2
+
3
+ __all__ = ["CollectionDescription", "QueryAgentResponse"]
File without changes
@@ -0,0 +1,16 @@
1
+ class QueryAgentError(Exception):
2
+ """Exception raised for errors returned by the Query Agent API.
3
+
4
+ Attributes:
5
+ message: Human-readable error message from the API response.
6
+ code: Machine-readable error code identifying the error type.
7
+ details: Additional error context or details (may be empty).
8
+ status_code: HTTP status code returned by the API.
9
+ """
10
+
11
+ def __init__(self, message: str, code: str, details: dict, status_code: int):
12
+ super().__init__(message)
13
+ self.message = message
14
+ self.code = code
15
+ self.details = details
16
+ self.status_code = status_code
File without changes
@@ -0,0 +1,3 @@
1
+ from .query_agent import QueryAgent
2
+
3
+ __all__ = ["QueryAgent"]
@@ -0,0 +1,3 @@
1
+ from .response import CollectionDescription, QueryAgentResponse
2
+
3
+ __all__ = ["CollectionDescription", "QueryAgentResponse"]
@@ -0,0 +1,150 @@
1
+ from enum import Enum
2
+ from typing import Dict, Literal, Optional, Union
3
+
4
+ from pydantic import BaseModel
5
+
6
+
7
+ class CollectionDescription(BaseModel):
8
+ name: str
9
+ description: str
10
+
11
+
12
+ class ComparisonOperator(str, Enum):
13
+ EQUALS = "="
14
+ LESS_THAN = "<"
15
+ GREATER_THAN = ">"
16
+ LESS_EQUAL = "<="
17
+ GREATER_EQUAL = ">="
18
+ NOT_EQUALS = "!="
19
+ LIKE = "LIKE"
20
+
21
+
22
+ class IntegerPropertyFilter(BaseModel):
23
+ """Filter numeric properties using comparison operators."""
24
+
25
+ property_name: str
26
+ operator: ComparisonOperator
27
+ value: float
28
+
29
+
30
+ class TextPropertyFilter(BaseModel):
31
+ """Filter text properties using equality or LIKE operators"""
32
+
33
+ property_name: str
34
+ operator: ComparisonOperator
35
+ value: str
36
+
37
+
38
+ class BooleanPropertyFilter(BaseModel):
39
+ """Filter boolean properties using equality operators"""
40
+
41
+ property_name: str
42
+ operator: ComparisonOperator
43
+ value: bool
44
+
45
+
46
+ class QueryResult(BaseModel):
47
+ queries: list[str]
48
+ filters: list[
49
+ list[Union[BooleanPropertyFilter, IntegerPropertyFilter, TextPropertyFilter]]
50
+ ] = []
51
+ filter_operators: Literal["AND", "OR"]
52
+
53
+
54
+ class NumericMetrics(str, Enum):
55
+ COUNT = "COUNT"
56
+ MAX = "MAXIMUM"
57
+ MEAN = "MEAN"
58
+ MEDIAN = "MEDIAN"
59
+ MIN = "MINIMUM"
60
+ MODE = "MODE"
61
+ SUM = "SUM"
62
+ TYPE = "TYPE"
63
+
64
+
65
+ class TextMetrics(str, Enum):
66
+ COUNT = "COUNT"
67
+ TYPE = "TYPE"
68
+ TOP_OCCURRENCES = "TOP_OCCURRENCES"
69
+
70
+
71
+ class BooleanMetrics(str, Enum):
72
+ COUNT = "COUNT"
73
+ TYPE = "TYPE"
74
+ TOTAL_TRUE = "TOTAL_TRUE"
75
+ TOTAL_FALSE = "TOTAL_FALSE"
76
+ PERCENTAGE_TRUE = "PERCENTAGE_TRUE"
77
+ PERCENTAGE_FALSE = "PERCENTAGE_FALSE"
78
+
79
+
80
+ class IntegerPropertyAggregation(BaseModel):
81
+ """Aggregate numeric properties using statistical functions"""
82
+
83
+ property_name: str
84
+ metrics: NumericMetrics
85
+
86
+
87
+ class TextPropertyAggregation(BaseModel):
88
+ """Aggregate text properties using frequency analysis"""
89
+
90
+ property_name: str
91
+ metrics: TextMetrics
92
+ top_occurrences_limit: Optional[int] = None
93
+
94
+
95
+ class BooleanPropertyAggregation(BaseModel):
96
+ """Aggregate boolean properties using statistical functions"""
97
+
98
+ property_name: str
99
+ metrics: BooleanMetrics
100
+
101
+
102
+ class AggregationResult(BaseModel):
103
+ """
104
+ The aggregations to be performed on a collection in a vector database.
105
+
106
+ They should be based on the original user query and can include multiple
107
+ aggregations across different properties and metrics.
108
+ """
109
+
110
+ search_query: Optional[str] = None
111
+ groupby_property: Optional[str] = None
112
+ aggregations: list[
113
+ Union[
114
+ IntegerPropertyAggregation,
115
+ TextPropertyAggregation,
116
+ BooleanPropertyAggregation,
117
+ ]
118
+ ]
119
+
120
+
121
+ class Usage(BaseModel):
122
+ requests: Union[int, str] = 0
123
+ request_tokens: Union[int, str, None] = None
124
+ response_tokens: Union[int, str, None] = None
125
+ total_tokens: Union[int, str, None] = None
126
+ details: Union[Dict[str, int], Dict[str, str], None] = None
127
+
128
+
129
+ class AggregationResultWithCollection(AggregationResult):
130
+ collection: str
131
+
132
+
133
+ class QueryResultWithCollection(QueryResult):
134
+ collection: str
135
+
136
+
137
+ class QueryAgentResponse(BaseModel):
138
+ original_query: str
139
+ collection_names: list[str]
140
+ searches: list[list[QueryResultWithCollection]]
141
+ aggregations: list[list[AggregationResultWithCollection]]
142
+ usage: Usage
143
+ total_time: float
144
+ search_answer: Optional[str] = None
145
+ aggregation_answer: Optional[str] = None
146
+ has_aggregation_answer: bool
147
+ has_search_answer: bool
148
+ is_partial_answer: bool
149
+ missing_information: list[str]
150
+ final_answer: str
@@ -0,0 +1,129 @@
1
+ from typing import List, Optional, Union
2
+
3
+ import httpx
4
+ from weaviate.client import WeaviateAsyncClient, WeaviateClient
5
+
6
+ from weaviate_agents.base import _BaseAgent
7
+ from weaviate_agents.errors import QueryAgentError
8
+ from weaviate_agents.query.classes import CollectionDescription, QueryAgentResponse
9
+
10
+
11
+ class QueryAgent(_BaseAgent):
12
+ """An agent for executing agentic queries against Weaviate.
13
+
14
+ Warning:
15
+ Weaviate Agents - Query Agent is an early stage alpha product. The API is subject to
16
+ breaking changes. Please ensure you are using the latest version.
17
+
18
+ For more information, see the [Weaviate Agents - Query Agent](TODO: add docs link)
19
+ """
20
+
21
+ def __init__(
22
+ self,
23
+ client: Union[WeaviateClient, WeaviateAsyncClient],
24
+ collections: List[Union[str, CollectionDescription]],
25
+ agents_host: Union[str, None] = None,
26
+ system_prompt: Union[str, None] = None,
27
+ timeout: Union[int, None] = None,
28
+ ):
29
+ """Initialize the QueryAgent.
30
+
31
+ Args:
32
+ client: The Weaviate client connected to a Weaviate Cloud cluster.
33
+ collections: The collections to query.
34
+ agents_host: Optional host of the agents service.
35
+ system_prompt: Optional system prompt for the agent.
36
+ timeout: The timeout for the request. Defaults to 60 seconds.
37
+ """
38
+ super().__init__(client, agents_host)
39
+
40
+ self._collections = collections
41
+ self._system_prompt = system_prompt
42
+
43
+ self._timeout = 60 if timeout is None else timeout
44
+
45
+ self.q_host = f"{self._agents_host}/agent/query"
46
+
47
+ def run(
48
+ self,
49
+ query: str,
50
+ view_properties: Optional[List[str]] = None,
51
+ context: Optional[QueryAgentResponse] = None,
52
+ ) -> QueryAgentResponse:
53
+ """Run the query agent.
54
+
55
+ Args:
56
+ query: The natural language query string for the agent.
57
+ view_properties: Optional list of of property names the agent has the ability to view
58
+ across all collections.
59
+ context: Optional previous response from the agent.
60
+ """
61
+ request_body = {
62
+ "query": query,
63
+ "collection_names": [
64
+ c.name if isinstance(c, CollectionDescription) else c
65
+ for c in self._collections
66
+ ],
67
+ "headers": self._connection.additional_headers,
68
+ "collection_view_properties": view_properties,
69
+ "limit": 20,
70
+ "tenant": None,
71
+ "previous_response": context.model_dump() if context else None,
72
+ "system_prompt": self._system_prompt,
73
+ }
74
+
75
+ response = httpx.post(
76
+ self.q_host,
77
+ headers=self._headers,
78
+ json=request_body,
79
+ timeout=self._timeout,
80
+ )
81
+
82
+ if response.status_code != 200:
83
+ error_data = response.json().get("error", {})
84
+ raise QueryAgentError(
85
+ message=error_data.get("message", "Unknown error"),
86
+ code=error_data.get("code", "unknown"),
87
+ details=error_data.get("details", {}),
88
+ status_code=response.status_code,
89
+ )
90
+
91
+ return QueryAgentResponse(**response.json())
92
+
93
+ def add_collection(self, collection: Union[str, CollectionDescription]):
94
+ """Add a collection to the query agent.
95
+
96
+ Args:
97
+ collection: The collection to add.
98
+ """
99
+ new_collection_name = (
100
+ collection.name
101
+ if isinstance(collection, CollectionDescription)
102
+ else collection
103
+ )
104
+ for c in self._collections:
105
+ if isinstance(c, CollectionDescription):
106
+ if c.name == new_collection_name:
107
+ return
108
+ elif c == new_collection_name:
109
+ return
110
+ self._collections.append(collection)
111
+
112
+ def remove_collection(self, collection: Union[str, CollectionDescription]):
113
+ """Remove a collection from the query agent if it exists.
114
+
115
+ Args:
116
+ collection: The collection to remove. Can be either a string name or CollectionDescription.
117
+ """
118
+ target_name = (
119
+ collection.name
120
+ if isinstance(collection, CollectionDescription)
121
+ else collection
122
+ )
123
+
124
+ self._collections = [
125
+ c
126
+ for c in self._collections
127
+ if (isinstance(c, CollectionDescription) and c.name != target_name)
128
+ or (isinstance(c, str) and c != target_name)
129
+ ]
File without changes
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 2.2
2
+ Name: weaviate-agents
3
+ Version: 0.1.0
4
+ Summary: Add your description here
5
+ Requires-Python: >=3.9
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: weaviate-client>=4.11.0
8
+
9
+ # Weaviate Agents Python Client
10
+
11
+ Official Python client for Weaviate Agents.
@@ -0,0 +1,17 @@
1
+ test/query_agent/test_query_model.py,sha256=b3crowxPtHNVg8X0CO7G9i_rWXBrbNzS4uw4-2zW4Is,5867
2
+ weaviate_agents/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ weaviate_agents/base.py,sha256=FXSeUzgh1TMJVgy6wGvzFH7y9GbOEsu_2wEtDfpVgJ8,985
4
+ weaviate_agents/errors.py,sha256=FGHl_OAPy4id1-pmV7J1jpE3mdUBbZcqzku3p4W4YO4,637
5
+ weaviate_agents/classes/__init__.py,sha256=BDpbeVPlzRG1YufHFa2Ac1YdB11VmGEJo4jgY0Ce5YM,75
6
+ weaviate_agents/classes/query.py,sha256=QdzlZAUS17YLi0oSusKMuTdRifzBllmsgEQvClECwHg,143
7
+ weaviate_agents/classes/transformation.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ weaviate_agents/query/.gitkeep,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ weaviate_agents/query/__init__.py,sha256=6ob70QVRiiFHHm_tGmEP_2snj1B3JiKvTTtIpJIcdrA,62
10
+ weaviate_agents/query/query_agent.py,sha256=fxGsbht7Awn8kPckD8ufSJ1gR6VCr07h3LhTVpM8Egg,4550
11
+ weaviate_agents/query/classes/__init__.py,sha256=oZwcLHHs5Go89k_noUidejH1NjUIEcU2fZf3ySDphTk,123
12
+ weaviate_agents/query/classes/response.py,sha256=hZHD-6VA8Ei1h9nPPHjiRjKOz9cMEwm6AKqdYbDz_pI,3579
13
+ weaviate_agents/transformation/.gitkeep,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ weaviate_agents-0.1.0.dist-info/METADATA,sha256=fVkL4RkoQBnXNCbT0Xq9QCD2U8GLDVNeu4MkAPhxmBo,274
15
+ weaviate_agents-0.1.0.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
16
+ weaviate_agents-0.1.0.dist-info/top_level.txt,sha256=9FVUFn9cpWQ2wd2cunM3MP6A9RE0J0iiH_HXrrpZaac,21
17
+ weaviate_agents-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.8.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ test
2
+ weaviate_agents