wisent 0.1.1__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.

Potentially problematic release.


This version of wisent might be problematic. Click here for more details.

wisent/utils/http.py ADDED
@@ -0,0 +1,228 @@
1
+ """
2
+ HTTP request utilities for the Wisent API.
3
+ """
4
+
5
+ import json
6
+ from typing import Any, Dict, Optional, Union
7
+
8
+ import aiohttp
9
+ import requests
10
+ from requests.exceptions import RequestException
11
+
12
+
13
+ class APIError(Exception):
14
+ """Exception raised for API errors."""
15
+
16
+ def __init__(self, message: str, status_code: Optional[int] = None, response: Optional[Dict[str, Any]] = None):
17
+ self.message = message
18
+ self.status_code = status_code
19
+ self.response = response
20
+ super().__init__(self.message)
21
+
22
+
23
+ class HTTPClient:
24
+ """
25
+ HTTP client for making requests to the Wisent API.
26
+
27
+ Args:
28
+ base_url: The base URL for the API
29
+ headers: Headers to include in all requests
30
+ timeout: Request timeout in seconds
31
+ """
32
+
33
+ def __init__(self, base_url: str, headers: Dict[str, str], timeout: int = 60):
34
+ self.base_url = base_url.rstrip("/")
35
+ self.headers = headers
36
+ self.timeout = timeout
37
+
38
+ def _build_url(self, endpoint: str) -> str:
39
+ """Build the full URL for an API endpoint."""
40
+ endpoint = endpoint.lstrip("/")
41
+ return f"{self.base_url}/{endpoint}"
42
+
43
+ def get(self, endpoint: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
44
+ """
45
+ Make a GET request to the API.
46
+
47
+ Args:
48
+ endpoint: API endpoint
49
+ params: Query parameters
50
+
51
+ Returns:
52
+ Response data as a dictionary
53
+
54
+ Raises:
55
+ APIError: If the request fails
56
+ """
57
+ url = self._build_url(endpoint)
58
+ try:
59
+ response = requests.get(
60
+ url,
61
+ headers=self.headers,
62
+ params=params,
63
+ timeout=self.timeout
64
+ )
65
+ response.raise_for_status()
66
+ return response.json()
67
+ except RequestException as e:
68
+ status_code = getattr(e.response, "status_code", None) if hasattr(e, "response") else None
69
+ response_data = None
70
+
71
+ if hasattr(e, "response") and e.response is not None:
72
+ try:
73
+ response_data = e.response.json()
74
+ except (ValueError, AttributeError):
75
+ response_data = {"error": str(e)}
76
+
77
+ raise APIError(
78
+ f"GET request to {url} failed: {str(e)}",
79
+ status_code=status_code,
80
+ response=response_data
81
+ ) from e
82
+
83
+ def post(self, endpoint: str, data: Optional[Dict[str, Any]] = None, json_data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
84
+ """
85
+ Make a POST request to the API.
86
+
87
+ Args:
88
+ endpoint: API endpoint
89
+ data: Form data
90
+ json_data: JSON data
91
+
92
+ Returns:
93
+ Response data as a dictionary
94
+
95
+ Raises:
96
+ APIError: If the request fails
97
+ """
98
+ url = self._build_url(endpoint)
99
+ try:
100
+ response = requests.post(
101
+ url,
102
+ headers=self.headers,
103
+ data=data,
104
+ json=json_data,
105
+ timeout=self.timeout
106
+ )
107
+ response.raise_for_status()
108
+ return response.json()
109
+ except RequestException as e:
110
+ status_code = getattr(e.response, "status_code", None) if hasattr(e, "response") else None
111
+ response_data = None
112
+
113
+ if hasattr(e, "response") and e.response is not None:
114
+ try:
115
+ response_data = e.response.json()
116
+ except (ValueError, AttributeError):
117
+ response_data = {"error": str(e)}
118
+
119
+ raise APIError(
120
+ f"POST request to {url} failed: {str(e)}",
121
+ status_code=status_code,
122
+ response=response_data
123
+ ) from e
124
+
125
+
126
+ class AsyncHTTPClient:
127
+ """
128
+ Asynchronous HTTP client for making requests to the Wisent API.
129
+
130
+ Args:
131
+ base_url: The base URL for the API
132
+ headers: Headers to include in all requests
133
+ timeout: Request timeout in seconds
134
+ """
135
+
136
+ def __init__(self, base_url: str, headers: Dict[str, str], timeout: int = 60):
137
+ self.base_url = base_url.rstrip("/")
138
+ self.headers = headers
139
+ self.timeout = timeout
140
+
141
+ def _build_url(self, endpoint: str) -> str:
142
+ """Build the full URL for an API endpoint."""
143
+ endpoint = endpoint.lstrip("/")
144
+ return f"{self.base_url}/{endpoint}"
145
+
146
+ async def get(self, endpoint: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
147
+ """
148
+ Make an asynchronous GET request to the API.
149
+
150
+ Args:
151
+ endpoint: API endpoint
152
+ params: Query parameters
153
+
154
+ Returns:
155
+ Response data as a dictionary
156
+
157
+ Raises:
158
+ APIError: If the request fails
159
+ """
160
+ url = self._build_url(endpoint)
161
+ try:
162
+ async with aiohttp.ClientSession() as session:
163
+ async with session.get(
164
+ url,
165
+ headers=self.headers,
166
+ params=params,
167
+ timeout=self.timeout
168
+ ) as response:
169
+ response.raise_for_status()
170
+ return await response.json()
171
+ except aiohttp.ClientError as e:
172
+ status_code = getattr(response, "status", None) if 'response' in locals() else None
173
+ response_data = None
174
+
175
+ if 'response' in locals():
176
+ try:
177
+ response_data = await response.json()
178
+ except (ValueError, AttributeError):
179
+ response_data = {"error": str(e)}
180
+
181
+ raise APIError(
182
+ f"Async GET request to {url} failed: {str(e)}",
183
+ status_code=status_code,
184
+ response=response_data
185
+ ) from e
186
+
187
+ async def post(self, endpoint: str, data: Optional[Dict[str, Any]] = None, json_data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
188
+ """
189
+ Make an asynchronous POST request to the API.
190
+
191
+ Args:
192
+ endpoint: API endpoint
193
+ data: Form data
194
+ json_data: JSON data
195
+
196
+ Returns:
197
+ Response data as a dictionary
198
+
199
+ Raises:
200
+ APIError: If the request fails
201
+ """
202
+ url = self._build_url(endpoint)
203
+ try:
204
+ async with aiohttp.ClientSession() as session:
205
+ async with session.post(
206
+ url,
207
+ headers=self.headers,
208
+ data=data,
209
+ json=json_data,
210
+ timeout=self.timeout
211
+ ) as response:
212
+ response.raise_for_status()
213
+ return await response.json()
214
+ except aiohttp.ClientError as e:
215
+ status_code = getattr(response, "status", None) if 'response' in locals() else None
216
+ response_data = None
217
+
218
+ if 'response' in locals():
219
+ try:
220
+ response_data = await response.json()
221
+ except (ValueError, AttributeError):
222
+ response_data = {"error": str(e)}
223
+
224
+ raise APIError(
225
+ f"Async POST request to {url} failed: {str(e)}",
226
+ status_code=status_code,
227
+ response=response_data
228
+ ) from e
wisent/version.py ADDED
@@ -0,0 +1,3 @@
1
+ """Version information."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Wisent Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,142 @@
1
+ Metadata-Version: 2.2
2
+ Name: wisent
3
+ Version: 0.1.1
4
+ Summary: Client library for interacting with the Wisent backend services
5
+ Home-page: https://github.com/wisent-ai/wisent
6
+ Author: Wisent Team
7
+ Author-email: info@wisent.ai
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: requests>=2.25.0
15
+ Requires-Dist: pydantic>=2.0.0
16
+ Requires-Dist: aiohttp>=3.8.0
17
+ Requires-Dist: torch>=2.0.0
18
+ Requires-Dist: numpy>=1.20.0
19
+ Requires-Dist: tqdm>=4.60.0
20
+ Requires-Dist: transformers>=4.30.0
21
+ Dynamic: author
22
+ Dynamic: author-email
23
+ Dynamic: classifier
24
+ Dynamic: description
25
+ Dynamic: description-content-type
26
+ Dynamic: home-page
27
+ Dynamic: requires-dist
28
+ Dynamic: requires-python
29
+ Dynamic: summary
30
+
31
+ # Wisent
32
+
33
+ A Python client library for interacting with the Wisent backend services.
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install wisent
39
+ ```
40
+
41
+ ## Features
42
+
43
+ - **Activations**: Extract and send model activations to the Wisent backend
44
+ - **Control Vectors**: Retrieve and apply control vectors for model inference
45
+ - **Inference**: Utilities for applying control vectors during inference
46
+ - **Utilities**: Helper functions for common tasks
47
+
48
+ ## Quick Start
49
+
50
+ ```python
51
+ from wisent import WisentClient
52
+
53
+ # Initialize the client
54
+ client = WisentClient(api_key="your_api_key", base_url="https://api.wisent.ai")
55
+
56
+ # Extract activations from a model and send to backend
57
+ activations = client.activations.extract(
58
+ model_name="mistralai/Mistral-7B-Instruct-v0.1",
59
+ prompt="Tell me about quantum computing",
60
+ layers=[0, 12, 24]
61
+ )
62
+
63
+ # Get a control vector from the backend
64
+ control_vector = client.control_vector.get(
65
+ name="helpful",
66
+ model="mistralai/Mistral-7B-Instruct-v0.1"
67
+ )
68
+
69
+ # Apply a control vector during inference
70
+ response = client.inference.generate_with_control(
71
+ model_name="mistralai/Mistral-7B-Instruct-v0.1",
72
+ prompt="Tell me about quantum computing",
73
+ control_vectors={"helpful": 0.8, "concise": 0.5}
74
+ )
75
+
76
+ # Print the response
77
+ print(response.text)
78
+ ```
79
+
80
+ ## Advanced Usage
81
+
82
+ ### Extracting Activations
83
+
84
+ ```python
85
+ from wisent.activations import ActivationExtractor
86
+
87
+ # Create an extractor
88
+ extractor = ActivationExtractor(
89
+ model_name="mistralai/Mistral-7B-Instruct-v0.1",
90
+ device="cuda"
91
+ )
92
+
93
+ # Extract activations for a specific prompt
94
+ activations = extractor.extract(
95
+ prompt="Tell me about quantum computing",
96
+ layers=[0, 12, 24],
97
+ tokens_to_extract=[-10, -1] # Extract last 10 tokens and final token
98
+ )
99
+
100
+ # Send activations to the Wisent backend
101
+ from wisent import WisentClient
102
+ client = WisentClient(api_key="your_api_key")
103
+ client.activations.upload(activations)
104
+ ```
105
+
106
+ ### Working with Control Vectors
107
+
108
+ ```python
109
+ from wisent.control_vector import ControlVectorManager
110
+
111
+ # Initialize the manager
112
+ manager = ControlVectorManager(api_key="your_api_key")
113
+
114
+ # Get a control vector
115
+ helpful_vector = manager.get("helpful", model="mistralai/Mistral-7B-Instruct-v0.1")
116
+
117
+ # Combine multiple vectors
118
+ combined_vector = manager.combine(
119
+ vectors={
120
+ "helpful": 0.8,
121
+ "concise": 0.5
122
+ },
123
+ model="mistralai/Mistral-7B-Instruct-v0.1"
124
+ )
125
+
126
+ # Apply during inference
127
+ from wisent.inference import Inferencer
128
+ inferencer = Inferencer(model_name="mistralai/Mistral-7B-Instruct-v0.1")
129
+ response = inferencer.generate(
130
+ prompt="Tell me about quantum computing",
131
+ control_vector=combined_vector,
132
+ method="caa" # Context-Aware Addition
133
+ )
134
+ ```
135
+
136
+ ## Documentation
137
+
138
+ For full documentation, visit [docs.wisent.ai](https://docs.wisent.ai).
139
+
140
+ ## License
141
+
142
+ MIT
@@ -0,0 +1,23 @@
1
+ wisent/__init__.py,sha256=oenGFUKmnJh5VuHLbNvK4W87jY6OX2bad5bdZg3JDkg,204
2
+ wisent/client.py,sha256=Yiz-xeVo5EPxKdNxrg05diy17kYa7wv1Q0iTgg0cpv0,1408
3
+ wisent/version.py,sha256=HOmU5sgXU14tXjdvSe0iIIyluugGL0Y7R8eo1JaeyxE,50
4
+ wisent/activations/__init__.py,sha256=IXhsn6OGw9N-tsRDar-YIxHevpqDhSI0zMCbwF8GUOo,342
5
+ wisent/activations/client.py,sha256=ibDcIXF_W53F2BBOIWRzZZMXLj6ZtINAxY_cTaRaiyU,3035
6
+ wisent/activations/extractor.py,sha256=FWVqF3IcF0oyo8A0nrt4qYTnevi7xN2_CIXPVAINuqM,9094
7
+ wisent/activations/models.py,sha256=MyNrKBS33Tln84FhV7iQknkPW08Eg69M6roSdYIa5ks,2678
8
+ wisent/control_vector/__init__.py,sha256=HG4PDNhWvTyWnNICsj7srWwK8h9fVglEUGBNfO0ti-I,356
9
+ wisent/control_vector/client.py,sha256=kZydPLAKzPpoaI3A2muZk-hOyKeKVeKALG7yENKNMMY,2382
10
+ wisent/control_vector/manager.py,sha256=VNB5BBrm0NWcuHTwT-mG5xMrV4dQW6bIuqzgvkwhl30,4998
11
+ wisent/control_vector/models.py,sha256=oe71uq71m2uOvFdxcwLUyKiTzkFmUpJZTp_J1RLHMGA,1990
12
+ wisent/inference/__init__.py,sha256=BRbNaUptOA5RzyBzjbUkYL9uj6tgNU0hzDsF8X0_eOY,324
13
+ wisent/inference/client.py,sha256=37CAvXkvASPWe4vY7AxrZnbmW90I8m7qrS_nb8lhZTg,3198
14
+ wisent/inference/inferencer.py,sha256=DAcKnAd4qIEweB190VVB0OVivhOg6CJwGDOk_d0e2wg,8807
15
+ wisent/inference/models.py,sha256=1PAAN_XdR5SK1i3UgZAEG8KvYjgr1pZFNzhx3i49iWA,1743
16
+ wisent/utils/__init__.py,sha256=vBkMxUrO9zzLFgKjdRP2zlige1n_83HVwWtzyMA-pEA,62
17
+ wisent/utils/auth.py,sha256=5HBN8LTzqg69tuzCk1r52HeIcPULQFhZgAipnqT_kvU,676
18
+ wisent/utils/http.py,sha256=iJ6YM1XyBdaO5MTyDLt-59ik2CjOtcKel8AWqcV-7yI,7654
19
+ wisent-0.1.1.dist-info/LICENSE,sha256=3T6y8B1fz8ZX0hclhj19tMPywIvQdNCU5gfreL7lr3M,1068
20
+ wisent-0.1.1.dist-info/METADATA,sha256=I5WZ2AtGfQWTMmKt5L7lRKLQcyxuJe5JGAXVtfRdySM,3626
21
+ wisent-0.1.1.dist-info/WHEEL,sha256=jB7zZ3N9hIM9adW7qlTAyycLYW9npaWKLRzaoVcLKcM,91
22
+ wisent-0.1.1.dist-info/top_level.txt,sha256=2Ts9Iyldnb3auIN2HBBaHPknRy7nSRDm2f6RGzYgr8A,7
23
+ wisent-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.8.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ wisent