oagi 0.5.0__py3-none-any.whl → 0.6.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.

Potentially problematic release.


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

oagi/async_client.py DELETED
@@ -1,247 +0,0 @@
1
- # -----------------------------------------------------------------------------
2
- # Copyright (c) OpenAGI Foundation
3
- # All rights reserved.
4
- #
5
- # This file is part of the official API project.
6
- # Licensed under the MIT License.
7
- # -----------------------------------------------------------------------------
8
-
9
- import os
10
- from functools import wraps
11
-
12
- import httpx
13
-
14
- from .exceptions import (
15
- APIError,
16
- AuthenticationError,
17
- ConfigurationError,
18
- NetworkError,
19
- NotFoundError,
20
- RateLimitError,
21
- RequestTimeoutError,
22
- ServerError,
23
- ValidationError,
24
- )
25
- from .logging import get_logger
26
- from .sync_client import ErrorResponse, LLMResponse
27
-
28
- logger = get_logger("async_client")
29
-
30
-
31
- def async_log_trace_on_failure(func):
32
- """Async decorator that logs trace ID when a method fails."""
33
-
34
- @wraps(func)
35
- async def wrapper(*args, **kwargs):
36
- try:
37
- return await func(*args, **kwargs)
38
- except Exception as e:
39
- # Try to get response from the exception if it has one
40
- if (response := getattr(e, "response", None)) is not None:
41
- logger.error(f"Request Id: {response.headers.get('x-request-id', '')}")
42
- logger.error(f"Trace Id: {response.headers.get('x-trace-id', '')}")
43
- raise
44
-
45
- return wrapper
46
-
47
-
48
- class AsyncClient:
49
- """Async HTTP client for the OAGI API."""
50
-
51
- def __init__(self, base_url: str | None = None, api_key: str | None = None):
52
- # Get from environment if not provided
53
- self.base_url = base_url or os.getenv("OAGI_BASE_URL")
54
- self.api_key = api_key or os.getenv("OAGI_API_KEY")
55
-
56
- # Validate required configuration
57
- if not self.base_url:
58
- raise ConfigurationError(
59
- "OAGI base URL must be provided either as 'base_url' parameter or "
60
- "OAGI_BASE_URL environment variable"
61
- )
62
-
63
- if not self.api_key:
64
- raise ConfigurationError(
65
- "OAGI API key must be provided either as 'api_key' parameter or "
66
- "OAGI_API_KEY environment variable"
67
- )
68
-
69
- self.base_url = self.base_url.rstrip("/")
70
- self.client = httpx.AsyncClient(base_url=self.base_url)
71
- self.timeout = 60
72
-
73
- logger.info(f"AsyncClient initialized with base_url: {self.base_url}")
74
-
75
- async def __aenter__(self):
76
- return self
77
-
78
- async def __aexit__(self, exc_type, exc_val, exc_tb):
79
- await self.client.aclose()
80
-
81
- async def close(self):
82
- """Close the underlying httpx async client"""
83
- await self.client.aclose()
84
-
85
- @async_log_trace_on_failure
86
- async def create_message(
87
- self,
88
- model: str,
89
- screenshot: str, # base64 encoded
90
- task_description: str | None = None,
91
- task_id: str | None = None,
92
- instruction: str | None = None,
93
- max_actions: int | None = 5,
94
- last_task_id: str | None = None,
95
- history_steps: int | None = None,
96
- api_version: str | None = None,
97
- ) -> LLMResponse:
98
- """
99
- Call the /v1/message endpoint to analyze task and screenshot
100
-
101
- Args:
102
- model: The model to use for task analysis
103
- screenshot: Base64-encoded screenshot image
104
- task_description: Description of the task (required for new sessions)
105
- task_id: Task ID for continuing existing task
106
- instruction: Additional instruction when continuing a session (only works with task_id)
107
- max_actions: Maximum number of actions to return (1-20)
108
- last_task_id: Previous task ID to retrieve history from (only works with task_id)
109
- history_steps: Number of historical steps to include from last_task_id (default: 1, max: 10)
110
- api_version: API version header
111
-
112
- Returns:
113
- LLMResponse: The response from the API
114
-
115
- Raises:
116
- httpx.HTTPStatusError: For HTTP error responses
117
- """
118
- headers = {}
119
- if api_version:
120
- headers["x-api-version"] = api_version
121
- if self.api_key:
122
- headers["x-api-key"] = self.api_key
123
-
124
- payload = {"model": model, "screenshot": screenshot}
125
-
126
- if task_description is not None:
127
- payload["task_description"] = task_description
128
- if task_id is not None:
129
- payload["task_id"] = task_id
130
- if instruction is not None:
131
- payload["instruction"] = instruction
132
- if max_actions is not None:
133
- payload["max_actions"] = max_actions
134
- if last_task_id is not None:
135
- payload["last_task_id"] = last_task_id
136
- if history_steps is not None:
137
- payload["history_steps"] = history_steps
138
-
139
- logger.info(f"Making async API request to /v1/message with model: {model}")
140
- logger.debug(
141
- f"Request includes task_description: {task_description is not None}, task_id: {task_id is not None}"
142
- )
143
-
144
- try:
145
- response = await self.client.post(
146
- "/v1/message", json=payload, headers=headers, timeout=self.timeout
147
- )
148
- except httpx.TimeoutException as e:
149
- logger.error(f"Request timed out after {self.timeout} seconds")
150
- raise RequestTimeoutError(
151
- f"Request timed out after {self.timeout} seconds", e
152
- )
153
- except httpx.NetworkError as e:
154
- logger.error(f"Network error: {e}")
155
- raise NetworkError(f"Network error: {e}", e)
156
-
157
- try:
158
- response_data = response.json()
159
- except ValueError:
160
- # If response is not JSON, raise API error
161
- logger.error(f"Non-JSON API response: {response.status_code}")
162
- raise APIError(
163
- f"Invalid response format (status {response.status_code})",
164
- status_code=response.status_code,
165
- response=response,
166
- )
167
-
168
- # Check if it's an error response (non-200 status or has error field)
169
- if response.status_code != 200:
170
- error_resp = ErrorResponse(**response_data)
171
- if error_resp.error:
172
- error_code = error_resp.error.code
173
- error_msg = error_resp.error.message
174
- logger.error(f"API Error [{error_code}]: {error_msg}")
175
-
176
- # Map to specific exception types based on status code
177
- exception_class = self._get_exception_class(response.status_code)
178
- raise exception_class(
179
- error_msg,
180
- code=error_code,
181
- status_code=response.status_code,
182
- response=response,
183
- )
184
- else:
185
- # Error response without error details
186
- logger.error(
187
- f"API error response without details: {response.status_code}"
188
- )
189
- exception_class = self._get_exception_class(response.status_code)
190
- raise exception_class(
191
- f"API error (status {response.status_code})",
192
- status_code=response.status_code,
193
- response=response,
194
- )
195
-
196
- # Parse successful response
197
- result = LLMResponse(**response_data)
198
-
199
- # Check if the response contains an error (even with 200 status)
200
- if result.error:
201
- logger.error(
202
- f"API Error in response: [{result.error.code}]: {result.error.message}"
203
- )
204
- raise APIError(
205
- result.error.message,
206
- code=result.error.code,
207
- status_code=200,
208
- response=response,
209
- )
210
-
211
- logger.info(
212
- f"Async API request successful - task_id: {result.task_id}, step: {result.current_step}, complete: {result.is_complete}"
213
- )
214
- logger.debug(f"Response included {len(result.actions)} actions")
215
- return result
216
-
217
- def _get_exception_class(self, status_code: int) -> type[APIError]:
218
- """Get the appropriate exception class based on status code."""
219
- status_map = {
220
- 401: AuthenticationError,
221
- 404: NotFoundError,
222
- 422: ValidationError,
223
- 429: RateLimitError,
224
- }
225
-
226
- if status_code >= 500:
227
- return ServerError
228
-
229
- return status_map.get(status_code, APIError)
230
-
231
- async def health_check(self) -> dict:
232
- """
233
- Call the /health endpoint for health check
234
-
235
- Returns:
236
- dict: Health check response
237
- """
238
- logger.debug("Making async health check request")
239
- try:
240
- response = await self.client.get("/health")
241
- response.raise_for_status()
242
- result = response.json()
243
- logger.debug("Async health check successful")
244
- return result
245
- except httpx.HTTPStatusError as e:
246
- logger.warning(f"Async health check failed: {e}")
247
- raise
oagi/sync_client.py DELETED
@@ -1,297 +0,0 @@
1
- # -----------------------------------------------------------------------------
2
- # Copyright (c) OpenAGI Foundation
3
- # All rights reserved.
4
- #
5
- # This file is part of the official API project.
6
- # Licensed under the MIT License.
7
- # -----------------------------------------------------------------------------
8
-
9
- import base64
10
- import os
11
- from functools import wraps
12
-
13
- import httpx
14
- from httpx import Response
15
- from pydantic import BaseModel
16
-
17
- from .exceptions import (
18
- APIError,
19
- AuthenticationError,
20
- ConfigurationError,
21
- NetworkError,
22
- NotFoundError,
23
- RateLimitError,
24
- RequestTimeoutError,
25
- ServerError,
26
- ValidationError,
27
- )
28
- from .logging import get_logger
29
- from .types import Action
30
-
31
- logger = get_logger("sync_client")
32
-
33
-
34
- class Usage(BaseModel):
35
- prompt_tokens: int
36
- completion_tokens: int
37
- total_tokens: int
38
-
39
-
40
- class ErrorDetail(BaseModel):
41
- """Detailed error information."""
42
-
43
- code: str
44
- message: str
45
-
46
-
47
- class ErrorResponse(BaseModel):
48
- """Standard error response format."""
49
-
50
- error: ErrorDetail | None
51
-
52
-
53
- class LLMResponse(BaseModel):
54
- id: str
55
- task_id: str
56
- object: str = "task.completion"
57
- created: int
58
- model: str
59
- task_description: str
60
- current_step: int
61
- is_complete: bool
62
- actions: list[Action]
63
- reason: str | None = None
64
- usage: Usage
65
- error: ErrorDetail | None = None
66
-
67
-
68
- def _log_trace_id(response: Response):
69
- logger.error(f"Request Id: {response.headers.get('x-request-id', '')}")
70
- logger.error(f"Trace Id: {response.headers.get('x-trace-id', '')}")
71
-
72
-
73
- def log_trace_on_failure(func):
74
- """Decorator that logs trace ID when a method fails."""
75
-
76
- @wraps(func)
77
- def wrapper(*args, **kwargs):
78
- try:
79
- return func(*args, **kwargs)
80
- except Exception as e:
81
- # Try to get response from the exception if it has one
82
- if (response := getattr(e, "response", None)) is not None:
83
- _log_trace_id(response)
84
- raise
85
-
86
- return wrapper
87
-
88
-
89
- class SyncClient:
90
- def __init__(self, base_url: str | None = None, api_key: str | None = None):
91
- # Get from environment if not provided
92
- self.base_url = base_url or os.getenv("OAGI_BASE_URL")
93
- self.api_key = api_key or os.getenv("OAGI_API_KEY")
94
-
95
- # Validate required configuration
96
- if not self.base_url:
97
- raise ConfigurationError(
98
- "OAGI base URL must be provided either as 'base_url' parameter or "
99
- "OAGI_BASE_URL environment variable"
100
- )
101
-
102
- if not self.api_key:
103
- raise ConfigurationError(
104
- "OAGI API key must be provided either as 'api_key' parameter or "
105
- "OAGI_API_KEY environment variable"
106
- )
107
-
108
- self.base_url = self.base_url.rstrip("/")
109
- self.client = httpx.Client(base_url=self.base_url)
110
- self.timeout = 60
111
-
112
- logger.info(f"SyncClient initialized with base_url: {self.base_url}")
113
-
114
- def __enter__(self):
115
- return self
116
-
117
- def __exit__(self, exc_type, exc_val, exc_tb):
118
- self.client.close()
119
-
120
- def close(self):
121
- """Close the underlying httpx client"""
122
- self.client.close()
123
-
124
- @log_trace_on_failure
125
- def create_message(
126
- self,
127
- model: str,
128
- screenshot: str, # base64 encoded
129
- task_description: str | None = None,
130
- task_id: str | None = None,
131
- instruction: str | None = None,
132
- max_actions: int | None = 5,
133
- last_task_id: str | None = None,
134
- history_steps: int | None = None,
135
- api_version: str | None = None,
136
- ) -> LLMResponse:
137
- """
138
- Call the /v1/message endpoint to analyze task and screenshot
139
-
140
- Args:
141
- model: The model to use for task analysis
142
- screenshot: Base64-encoded screenshot image
143
- task_description: Description of the task (required for new sessions)
144
- task_id: Task ID for continuing existing task
145
- instruction: Additional instruction when continuing a session (only works with task_id)
146
- max_actions: Maximum number of actions to return (1-20)
147
- last_task_id: Previous task ID to retrieve history from (only works with task_id)
148
- history_steps: Number of historical steps to include from last_task_id (default: 1, max: 10)
149
- api_version: API version header
150
-
151
- Returns:
152
- LLMResponse: The response from the API
153
-
154
- Raises:
155
- httpx.HTTPStatusError: For HTTP error responses
156
- """
157
- headers = {}
158
- if api_version:
159
- headers["x-api-version"] = api_version
160
- if self.api_key:
161
- headers["x-api-key"] = self.api_key
162
-
163
- payload = {"model": model, "screenshot": screenshot}
164
-
165
- if task_description is not None:
166
- payload["task_description"] = task_description
167
- if task_id is not None:
168
- payload["task_id"] = task_id
169
- if instruction is not None:
170
- payload["instruction"] = instruction
171
- if max_actions is not None:
172
- payload["max_actions"] = max_actions
173
- if last_task_id is not None:
174
- payload["last_task_id"] = last_task_id
175
- if history_steps is not None:
176
- payload["history_steps"] = history_steps
177
-
178
- logger.info(f"Making API request to /v1/message with model: {model}")
179
- logger.debug(
180
- f"Request includes task_description: {task_description is not None}, task_id: {task_id is not None}"
181
- )
182
-
183
- try:
184
- response = self.client.post(
185
- "/v1/message", json=payload, headers=headers, timeout=self.timeout
186
- )
187
- except httpx.TimeoutException as e:
188
- logger.error(f"Request timed out after {self.timeout} seconds")
189
- raise RequestTimeoutError(
190
- f"Request timed out after {self.timeout} seconds", e
191
- )
192
- except httpx.NetworkError as e:
193
- logger.error(f"Network error: {e}")
194
- raise NetworkError(f"Network error: {e}", e)
195
-
196
- try:
197
- response_data = response.json()
198
- except ValueError:
199
- # If response is not JSON, raise API error
200
- logger.error(f"Non-JSON API response: {response.status_code}")
201
- raise APIError(
202
- f"Invalid response format (status {response.status_code})",
203
- status_code=response.status_code,
204
- response=response,
205
- )
206
-
207
- # Check if it's an error response (non-200 status or has error field)
208
- if response.status_code != 200:
209
- error_resp = ErrorResponse(**response_data)
210
- if error_resp.error:
211
- error_code = error_resp.error.code
212
- error_msg = error_resp.error.message
213
- logger.error(f"API Error [{error_code}]: {error_msg}")
214
-
215
- # Map to specific exception types based on status code
216
- exception_class = self._get_exception_class(response.status_code)
217
- raise exception_class(
218
- error_msg,
219
- code=error_code,
220
- status_code=response.status_code,
221
- response=response,
222
- )
223
- else:
224
- # Error response without error details
225
- logger.error(
226
- f"API error response without details: {response.status_code}"
227
- )
228
- exception_class = self._get_exception_class(response.status_code)
229
- raise exception_class(
230
- f"API error (status {response.status_code})",
231
- status_code=response.status_code,
232
- response=response,
233
- )
234
-
235
- # Parse successful response
236
- result = LLMResponse(**response_data)
237
-
238
- # Check if the response contains an error (even with 200 status)
239
- if result.error:
240
- logger.error(
241
- f"API Error in response: [{result.error.code}]: {result.error.message}"
242
- )
243
- raise APIError(
244
- result.error.message,
245
- code=result.error.code,
246
- status_code=200,
247
- response=response,
248
- )
249
-
250
- logger.info(
251
- f"API request successful - task_id: {result.task_id}, step: {result.current_step}, complete: {result.is_complete}"
252
- )
253
- logger.debug(f"Response included {len(result.actions)} actions")
254
- return result
255
-
256
- def _get_exception_class(self, status_code: int) -> type[APIError]:
257
- """Get the appropriate exception class based on status code."""
258
- status_map = {
259
- 401: AuthenticationError,
260
- 404: NotFoundError,
261
- 422: ValidationError,
262
- 429: RateLimitError,
263
- }
264
-
265
- if status_code >= 500:
266
- return ServerError
267
-
268
- return status_map.get(status_code, APIError)
269
-
270
- def health_check(self) -> dict:
271
- """
272
- Call the /health endpoint for health check
273
-
274
- Returns:
275
- dict: Health check response
276
- """
277
- logger.debug("Making health check request")
278
- try:
279
- response = self.client.get("/health")
280
- response.raise_for_status()
281
- result = response.json()
282
- logger.debug("Health check successful")
283
- return result
284
- except httpx.HTTPStatusError as e:
285
- logger.warning(f"Health check failed: {e}")
286
- raise
287
-
288
-
289
- def encode_screenshot_from_bytes(image_bytes: bytes) -> str:
290
- """Helper function to encode image bytes to base64 string"""
291
- return base64.b64encode(image_bytes).decode("utf-8")
292
-
293
-
294
- def encode_screenshot_from_file(image_path: str) -> str:
295
- """Helper function to encode image file to base64 string"""
296
- with open(image_path, "rb") as f:
297
- return encode_screenshot_from_bytes(f.read())
@@ -1,30 +0,0 @@
1
- oagi/__init__.py,sha256=m-Z121YCIwQOPXpTC8kd_UIJizcX8QuHyrSSguQ0KE0,2187
2
- oagi/async_client.py,sha256=JN2PAhM5pRTzjKxScQm-Fb_mfsEUwyXgFDJ_5w5kQv8,8916
3
- oagi/async_pyautogui_action_handler.py,sha256=F-lKyePCONWI03WnSxpX_QwxONbvnfdQu51wTod6mdw,1614
4
- oagi/async_screenshot_maker.py,sha256=pI-dbLcYOzcO1ffgTmozAdbYJQNBPKA7hmqj1RxEmIY,1688
5
- oagi/async_short_task.py,sha256=7WM89H4V7xaPjuQQlzjA5Q7JOoJLhZw-DotJPNm8uAA,2517
6
- oagi/async_single_step.py,sha256=QawXO4GyfMz6O9jV8QBC1vKxFuS9vjKQxxJ1nwgHBzI,2838
7
- oagi/async_task.py,sha256=z6q1OUjvbnXB5mTimAkM5kTFmixJA6zmWLPujx8vMHc,5013
8
- oagi/exceptions.py,sha256=VMwVS8ouE9nHhBpN3AZMYt5_U2kGcihWaTnBhoQLquo,1662
9
- oagi/logging.py,sha256=CWe89mA5MKTipIvfrqSYkv2CAFNBSwHMDQMDkG_g64g,1350
10
- oagi/pil_image.py,sha256=Zp7YNwyE_AT25ZEFsWKbzMxbO8JOQsJ1Espph5ye8k8,3804
11
- oagi/pyautogui_action_handler.py,sha256=8IFbU4p907L4b3TV3Eeh0-c-pYL2lYw-_qf1r8TtPTw,9811
12
- oagi/screenshot_maker.py,sha256=sVuW7jn-K4FmLhmYI-akdNI-UVcTeBzh9P1_qJhoq1s,1282
13
- oagi/short_task.py,sha256=prrtUExDbiwabFqm6lOvKfFhLjQwANyWe2z7-xT995w,2323
14
- oagi/single_step.py,sha256=djhGOHzA5Y3-9_ity9QiJr_ObZZ04blSmNZsLXXXfkg,2939
15
- oagi/sync_client.py,sha256=rgLjsZ2TnFidq5UcZddN83WNQ0HpfBlVihzG1j3XY28,9856
16
- oagi/task.py,sha256=yHM8QpevP8RitnFXGgyJttGRXB8mtFPSDB33E0MSIrg,4869
17
- oagi/types/__init__.py,sha256=YXxL-30f92qAf9U6LZuVCtKFG-Pi3xahKedaNxyrxFE,766
18
- oagi/types/action_handler.py,sha256=NH8E-m5qpGqWcXzTSWfF7W0Xdp8SkzJsbhCmQ0B96cg,1075
19
- oagi/types/async_action_handler.py,sha256=k1AaqSkFcXlxwW8sn-w0WFHGsIqHFLbcOPrkknmSVug,1116
20
- oagi/types/async_image_provider.py,sha256=wnhRyPtTmuALt45Qore74-RCkP5yxU9sZGjvOzFqzOk,1170
21
- oagi/types/image.py,sha256=KgPCCTJ6D5vHIaGZdbTE7eQEa1WlT6G9tf59ZuUCV2U,537
22
- oagi/types/image_provider.py,sha256=oYFdOYznrK_VOR9egzOjw5wFM5w8EY2sY01pH0ANAgU,1112
23
- oagi/types/models/__init__.py,sha256=bVzzGxb6lVxAQyJpy0Z1QknSe-xC3g4OIDr7t-p_3Ys,467
24
- oagi/types/models/action.py,sha256=hh6mRRSSWgrW4jpZo71zGMCOcZpV5_COu4148uG6G48,967
25
- oagi/types/models/image_config.py,sha256=tl6abVg_-IAPLwpaWprgknXu7wRWriMg-AEVyUX73v0,1567
26
- oagi/types/models/step.py,sha256=RSI4H_2rrUBq_xyCoWKaq7JHdJWNobtQppaKC1l0aWU,471
27
- oagi-0.5.0.dist-info/METADATA,sha256=MQHpJB8UgoliDCNk55ce0klXvkQHVpiw9AmCylAY_jQ,4799
28
- oagi-0.5.0.dist-info/WHEEL,sha256=C2FUgwZgiLbznR-k0b_5k3Ai_1aASOXDss3lzCUsUug,87
29
- oagi-0.5.0.dist-info/licenses/LICENSE,sha256=sy5DLA2M29jFT4UfWsuBF9BAr3FnRkYtnAu6oDZiIf8,1075
30
- oagi-0.5.0.dist-info/RECORD,,
File without changes