oagi 0.0.0__py3-none-any.whl → 0.2.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/__init__.py CHANGED
@@ -1 +1,53 @@
1
- from .core import hello
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
+ from oagi.exceptions import (
10
+ APIError,
11
+ AuthenticationError,
12
+ ConfigurationError,
13
+ NetworkError,
14
+ NotFoundError,
15
+ OAGIError,
16
+ RateLimitError,
17
+ RequestTimeoutError,
18
+ ServerError,
19
+ ValidationError,
20
+ )
21
+ from oagi.pyautogui_action_handler import PyautoguiActionHandler
22
+ from oagi.screenshot_maker import ScreenshotMaker
23
+ from oagi.short_task import ShortTask
24
+ from oagi.single_step import single_step
25
+ from oagi.sync_client import ErrorDetail, ErrorResponse, LLMResponse, SyncClient
26
+ from oagi.task import Task
27
+
28
+ __all__ = [
29
+ # Core classes
30
+ "Task",
31
+ "ShortTask",
32
+ "SyncClient",
33
+ # Functions
34
+ "single_step",
35
+ # Handler classes
36
+ "PyautoguiActionHandler",
37
+ "ScreenshotMaker",
38
+ # Response models
39
+ "LLMResponse",
40
+ "ErrorResponse",
41
+ "ErrorDetail",
42
+ # Exceptions
43
+ "OAGIError",
44
+ "APIError",
45
+ "AuthenticationError",
46
+ "ConfigurationError",
47
+ "NetworkError",
48
+ "NotFoundError",
49
+ "RateLimitError",
50
+ "ServerError",
51
+ "RequestTimeoutError",
52
+ "ValidationError",
53
+ ]
oagi/exceptions.py ADDED
@@ -0,0 +1,75 @@
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 httpx
10
+
11
+
12
+ class OAGIError(Exception):
13
+ pass
14
+
15
+
16
+ class APIError(OAGIError):
17
+ def __init__(
18
+ self,
19
+ message: str,
20
+ code: str | None = None,
21
+ status_code: int | None = None,
22
+ response: httpx.Response | None = None,
23
+ ):
24
+ """Initialize APIError.
25
+
26
+ Args:
27
+ message: Human-readable error message
28
+ code: API error code for programmatic handling
29
+ status_code: HTTP status code
30
+ response: Original HTTP response object
31
+ """
32
+ super().__init__(message)
33
+ self.message = message
34
+ self.code = code
35
+ self.status_code = status_code
36
+ self.response = response
37
+
38
+ def __str__(self) -> str:
39
+ if self.code:
40
+ return f"API Error [{self.code}]: {self.message}"
41
+ return f"API Error: {self.message}"
42
+
43
+
44
+ class AuthenticationError(APIError):
45
+ pass
46
+
47
+
48
+ class RateLimitError(APIError):
49
+ pass
50
+
51
+
52
+ class ValidationError(APIError):
53
+ pass
54
+
55
+
56
+ class NotFoundError(APIError):
57
+ pass
58
+
59
+
60
+ class ServerError(APIError):
61
+ pass
62
+
63
+
64
+ class NetworkError(OAGIError):
65
+ def __init__(self, message: str, original_error: Exception | None = None):
66
+ super().__init__(message)
67
+ self.original_error = original_error
68
+
69
+
70
+ class RequestTimeoutError(NetworkError):
71
+ pass
72
+
73
+
74
+ class ConfigurationError(OAGIError):
75
+ pass
oagi/logging.py ADDED
@@ -0,0 +1,45 @@
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 logging
10
+ import os
11
+
12
+
13
+ def get_logger(name: str) -> logging.Logger:
14
+ """
15
+ Get a logger with the specified name under the 'oagi' namespace.
16
+
17
+ Log level is controlled by OAGI_LOG environment variable.
18
+ Valid values: DEBUG, INFO, WARNING, ERROR, CRITICAL
19
+ Default: INFO
20
+ """
21
+ logger = logging.getLogger(f"oagi.{name}")
22
+ oagi_root = logging.getLogger("oagi")
23
+
24
+ # Get log level from environment
25
+ log_level = os.getenv("OAGI_LOG", "INFO").upper()
26
+
27
+ # Convert string to logging level
28
+ try:
29
+ level = getattr(logging, log_level)
30
+ except AttributeError:
31
+ level = logging.INFO
32
+
33
+ # Configure root oagi logger once
34
+ if not oagi_root.handlers:
35
+ handler = logging.StreamHandler()
36
+ formatter = logging.Formatter(
37
+ "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
38
+ )
39
+ handler.setFormatter(formatter)
40
+ oagi_root.addHandler(handler)
41
+
42
+ # Always update level in case environment variable changed
43
+ oagi_root.setLevel(level)
44
+
45
+ return logger
@@ -0,0 +1,146 @@
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 re
10
+ import time
11
+
12
+ import pyautogui
13
+
14
+ from .types import Action, ActionType
15
+
16
+
17
+ class PyautoguiActionHandler:
18
+ """
19
+ Handles actions to be executed using PyAutoGUI.
20
+
21
+ This class provides functionality for handling and executing a sequence of
22
+ actions using the PyAutoGUI library. It processes a list of actions and executes
23
+ them as per the implementation.
24
+
25
+ Methods:
26
+ __call__: Executes the provided list of actions.
27
+
28
+ Args:
29
+ actions (list[Action]): List of actions to be processed and executed.
30
+ """
31
+
32
+ def __init__(self):
33
+ # Get screen dimensions for coordinate denormalization
34
+ self.screen_width, self.screen_height = pyautogui.size()
35
+ # Set default delay between actions
36
+ pyautogui.PAUSE = 0.1
37
+
38
+ def _denormalize_coords(self, x: float, y: float) -> tuple[int, int]:
39
+ """Convert coordinates from 0-1000 range to actual screen coordinates."""
40
+ screen_x = int(x * self.screen_width / 1000)
41
+ screen_y = int(y * self.screen_height / 1000)
42
+ return screen_x, screen_y
43
+
44
+ def _parse_coords(self, args_str: str) -> tuple[int, int]:
45
+ """Extract x, y coordinates from argument string."""
46
+ match = re.match(r"(\d+),\s*(\d+)", args_str)
47
+ if not match:
48
+ raise ValueError(f"Invalid coordinates format: {args_str}")
49
+ x, y = int(match.group(1)), int(match.group(2))
50
+ return self._denormalize_coords(x, y)
51
+
52
+ def _parse_drag_coords(self, args_str: str) -> tuple[int, int, int, int]:
53
+ """Extract x1, y1, x2, y2 coordinates from drag argument string."""
54
+ match = re.match(r"(\d+),\s*(\d+),\s*(\d+),\s*(\d+)", args_str)
55
+ if not match:
56
+ raise ValueError(f"Invalid drag coordinates format: {args_str}")
57
+ x1, y1, x2, y2 = (
58
+ int(match.group(1)),
59
+ int(match.group(2)),
60
+ int(match.group(3)),
61
+ int(match.group(4)),
62
+ )
63
+ x1, y1 = self._denormalize_coords(x1, y1)
64
+ x2, y2 = self._denormalize_coords(x2, y2)
65
+ return x1, y1, x2, y2
66
+
67
+ def _parse_scroll(self, args_str: str) -> tuple[int, int, str]:
68
+ """Extract x, y, direction from scroll argument string."""
69
+ match = re.match(r"(\d+),\s*(\d+),\s*(\w+)", args_str)
70
+ if not match:
71
+ raise ValueError(f"Invalid scroll format: {args_str}")
72
+ x, y = int(match.group(1)), int(match.group(2))
73
+ x, y = self._denormalize_coords(x, y)
74
+ direction = match.group(3).lower()
75
+ return x, y, direction
76
+
77
+ def _parse_hotkey(self, args_str: str) -> list[str]:
78
+ """Parse hotkey string into list of keys."""
79
+ # Remove parentheses if present
80
+ args_str = args_str.strip("()")
81
+ # Split by '+' to get individual keys
82
+ keys = [key.strip() for key in args_str.split("+")]
83
+ return keys
84
+
85
+ def _execute_action(self, action: Action) -> None:
86
+ """Execute a single action."""
87
+ count = action.count or 1
88
+ arg = action.argument.strip("()") # Remove outer parentheses if present
89
+
90
+ for _ in range(count):
91
+ match action.type:
92
+ case ActionType.CLICK:
93
+ x, y = self._parse_coords(arg)
94
+ pyautogui.click(x, y)
95
+
96
+ case ActionType.LEFT_DOUBLE:
97
+ x, y = self._parse_coords(arg)
98
+ pyautogui.doubleClick(x, y)
99
+
100
+ case ActionType.RIGHT_SINGLE:
101
+ x, y = self._parse_coords(arg)
102
+ pyautogui.rightClick(x, y)
103
+
104
+ case ActionType.DRAG:
105
+ x1, y1, x2, y2 = self._parse_drag_coords(arg)
106
+ pyautogui.moveTo(x1, y1)
107
+ pyautogui.dragTo(x2, y2, duration=0.5, button="left")
108
+
109
+ case ActionType.HOTKEY:
110
+ keys = self._parse_hotkey(arg)
111
+ pyautogui.hotkey(*keys)
112
+
113
+ case ActionType.TYPE:
114
+ # Remove quotes if present
115
+ text = arg.strip("\"'")
116
+ pyautogui.typewrite(text)
117
+
118
+ case ActionType.SCROLL:
119
+ x, y, direction = self._parse_scroll(arg)
120
+ pyautogui.moveTo(x, y)
121
+ scroll_amount = 5 if direction == "up" else -5
122
+ pyautogui.scroll(scroll_amount)
123
+
124
+ case ActionType.FINISH:
125
+ # Task completion - no action needed
126
+ pass
127
+
128
+ case ActionType.WAIT:
129
+ # Wait for a short period
130
+ time.sleep(1)
131
+
132
+ case ActionType.CALL_USER:
133
+ # Call user - implementation depends on requirements
134
+ print("User intervention requested")
135
+
136
+ case _:
137
+ print(f"Unknown action type: {action.type}")
138
+
139
+ def __call__(self, actions: list[Action]) -> None:
140
+ """Execute the provided list of actions."""
141
+ for action in actions:
142
+ try:
143
+ self._execute_action(action)
144
+ except Exception as e:
145
+ print(f"Error executing action {action.type}: {e}")
146
+ raise
@@ -0,0 +1,73 @@
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 io
10
+ from typing import Optional
11
+
12
+ import pyautogui
13
+
14
+ from .types import Image
15
+
16
+
17
+ class FileImage:
18
+ def __init__(self, path: str):
19
+ self.path = path
20
+ with open(path, "rb") as f:
21
+ self.data = f.read()
22
+
23
+ def read(self) -> bytes:
24
+ return self.data
25
+
26
+
27
+ class MockImage:
28
+ def read(self) -> bytes:
29
+ return b"mock screenshot data"
30
+
31
+
32
+ class ScreenshotImage:
33
+ """Image class that wraps a pyautogui screenshot."""
34
+
35
+ def __init__(self, screenshot):
36
+ """Initialize with a PIL Image from pyautogui."""
37
+ self.screenshot = screenshot
38
+ self._cached_bytes: Optional[bytes] = None
39
+
40
+ def read(self) -> bytes:
41
+ """Convert the screenshot to bytes (PNG format)."""
42
+ if self._cached_bytes is None:
43
+ # Convert PIL Image to bytes
44
+ buffer = io.BytesIO()
45
+ self.screenshot.save(buffer, format="PNG")
46
+ self._cached_bytes = buffer.getvalue()
47
+ return self._cached_bytes
48
+
49
+
50
+ class ScreenshotMaker:
51
+ """Takes screenshots using pyautogui."""
52
+
53
+ def __init__(self):
54
+ self._last_screenshot: Optional[ScreenshotImage] = None
55
+
56
+ def __call__(self) -> Image:
57
+ """Take a screenshot and return it as an Image."""
58
+ # Take a screenshot using pyautogui
59
+ screenshot = pyautogui.screenshot()
60
+
61
+ # Wrap it in our ScreenshotImage class
62
+ screenshot_image = ScreenshotImage(screenshot)
63
+
64
+ # Store as the last screenshot
65
+ self._last_screenshot = screenshot_image
66
+
67
+ return screenshot_image
68
+
69
+ def last_image(self) -> Image:
70
+ """Return the last screenshot taken, or take a new one if none exists."""
71
+ if self._last_screenshot is None:
72
+ return self()
73
+ return self._last_screenshot
oagi/short_task.py ADDED
@@ -0,0 +1,44 @@
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
+ from .logging import get_logger
10
+ from .task import Task
11
+ from .types import ActionHandler, ImageProvider
12
+
13
+ logger = get_logger("short_task")
14
+
15
+
16
+ class ShortTask(Task):
17
+ """Task implementation with automatic mode for short-duration tasks."""
18
+
19
+ def auto_mode(
20
+ self,
21
+ task_desc: str,
22
+ max_steps: int = 5,
23
+ executor: ActionHandler = None,
24
+ image_provider: ImageProvider = None,
25
+ ) -> bool:
26
+ """Run the task in automatic mode with the provided executor and image provider."""
27
+ logger.info(
28
+ f"Starting auto mode for task: '{task_desc}' (max_steps: {max_steps})"
29
+ )
30
+ self.init_task(task_desc, max_steps=max_steps)
31
+
32
+ for i in range(max_steps):
33
+ logger.debug(f"Auto mode step {i + 1}/{max_steps}")
34
+ image = image_provider()
35
+ step = self.step(image)
36
+ if step.stop:
37
+ logger.info(f"Auto mode completed successfully after {i + 1} steps")
38
+ return True
39
+ if executor:
40
+ logger.debug(f"Executing {len(step.actions)} actions")
41
+ executor(step.actions)
42
+
43
+ logger.warning(f"Auto mode reached max steps ({max_steps}) without completion")
44
+ return False
oagi/single_step.py ADDED
@@ -0,0 +1,82 @@
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
+ from pathlib import Path
10
+
11
+ from .task import Task
12
+ from .types import Image, Step
13
+
14
+
15
+ def single_step(
16
+ task_description: str,
17
+ screenshot: str | bytes | Path | Image,
18
+ instruction: str | None = None,
19
+ api_key: str | None = None,
20
+ base_url: str | None = None,
21
+ ) -> Step:
22
+ """
23
+ Perform a single-step inference without maintaining task state.
24
+
25
+ This is useful for one-off analyses where you don't need to maintain
26
+ a conversation or task context across multiple steps.
27
+
28
+ Args:
29
+ task_description: Description of the task to perform
30
+ screenshot: Screenshot as Image, bytes, or file path
31
+ instruction: Optional additional instruction for the task
32
+ api_key: OAGI API key (uses environment variable if not provided)
33
+ base_url: OAGI base URL (uses environment variable if not provided)
34
+
35
+ Returns:
36
+ Step: Object containing reasoning, actions, and completion status
37
+
38
+ Example:
39
+ >>> # Using with bytes
40
+ >>> with open("screenshot.png", "rb") as f:
41
+ ... image_bytes = f.read()
42
+ >>> step = single_step(
43
+ ... task_description="Click the submit button",
44
+ ... screenshot=image_bytes
45
+ ... )
46
+
47
+ >>> # Using with file path
48
+ >>> step = single_step(
49
+ ... task_description="Fill in the form",
50
+ ... screenshot=Path("screenshot.png"),
51
+ ... instruction="Use test@example.com for email"
52
+ ... )
53
+
54
+ >>> # Using with Image object
55
+ >>> from oagi.types import Image
56
+ >>> image = Image(...)
57
+ >>> step = single_step(
58
+ ... task_description="Navigate to settings",
59
+ ... screenshot=image
60
+ ... )
61
+ """
62
+ # Convert file paths to bytes
63
+ if isinstance(screenshot, (str, Path)):
64
+ path = Path(screenshot) if isinstance(screenshot, str) else screenshot
65
+ if path.exists():
66
+ with open(path, "rb") as f:
67
+ screenshot_bytes = f.read()
68
+ else:
69
+ raise FileNotFoundError(f"Screenshot file not found: {path}")
70
+ elif isinstance(screenshot, bytes):
71
+ screenshot_bytes = screenshot
72
+ elif isinstance(screenshot, Image):
73
+ screenshot_bytes = screenshot.read()
74
+ else:
75
+ raise ValueError(
76
+ f"screenshot must be Image, bytes, str, or Path, got {type(screenshot)}"
77
+ )
78
+
79
+ # Use Task to perform single step
80
+ with Task(api_key=api_key, base_url=base_url) as task:
81
+ task.init_task(task_description)
82
+ return task.step(screenshot_bytes, instruction=instruction)
oagi/sync_client.py ADDED
@@ -0,0 +1,265 @@
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
+
12
+ import httpx
13
+ from pydantic import BaseModel
14
+
15
+ from .exceptions import (
16
+ APIError,
17
+ AuthenticationError,
18
+ ConfigurationError,
19
+ NetworkError,
20
+ NotFoundError,
21
+ RateLimitError,
22
+ RequestTimeoutError,
23
+ ServerError,
24
+ ValidationError,
25
+ )
26
+ from .logging import get_logger
27
+ from .types import Action
28
+
29
+ logger = get_logger("sync_client")
30
+
31
+
32
+ class Usage(BaseModel):
33
+ prompt_tokens: int
34
+ completion_tokens: int
35
+ total_tokens: int
36
+
37
+
38
+ class ErrorDetail(BaseModel):
39
+ """Detailed error information."""
40
+
41
+ code: str
42
+ message: str
43
+
44
+
45
+ class ErrorResponse(BaseModel):
46
+ """Standard error response format."""
47
+
48
+ error: ErrorDetail | None
49
+
50
+
51
+ class LLMResponse(BaseModel):
52
+ id: str
53
+ task_id: str
54
+ object: str = "task.completion"
55
+ created: int
56
+ model: str
57
+ task_description: str
58
+ current_step: int
59
+ is_complete: bool
60
+ actions: list[Action]
61
+ reason: str | None = None
62
+ usage: Usage
63
+ error: ErrorDetail | None = None
64
+
65
+
66
+ class SyncClient:
67
+ def __init__(self, base_url: str | None = None, api_key: str | None = None):
68
+ # Get from environment if not provided
69
+ self.base_url = base_url or os.getenv("OAGI_BASE_URL")
70
+ self.api_key = api_key or os.getenv("OAGI_API_KEY")
71
+
72
+ # Validate required configuration
73
+ if not self.base_url:
74
+ raise ConfigurationError(
75
+ "OAGI base URL must be provided either as 'base_url' parameter or "
76
+ "OAGI_BASE_URL environment variable"
77
+ )
78
+
79
+ if not self.api_key:
80
+ raise ConfigurationError(
81
+ "OAGI API key must be provided either as 'api_key' parameter or "
82
+ "OAGI_API_KEY environment variable"
83
+ )
84
+
85
+ self.base_url = self.base_url.rstrip("/")
86
+ self.client = httpx.Client(base_url=self.base_url)
87
+ self.timeout = 60
88
+
89
+ logger.info(f"SyncClient initialized with base_url: {self.base_url}")
90
+
91
+ def __enter__(self):
92
+ return self
93
+
94
+ def __exit__(self, exc_type, exc_val, exc_tb):
95
+ self.client.close()
96
+
97
+ def close(self):
98
+ """Close the underlying httpx client"""
99
+ self.client.close()
100
+
101
+ def create_message(
102
+ self,
103
+ model: str,
104
+ screenshot: str, # base64 encoded
105
+ task_description: str | None = None,
106
+ task_id: str | None = None,
107
+ instruction: str | None = None,
108
+ max_actions: int | None = 5,
109
+ api_version: str | None = None,
110
+ ) -> LLMResponse:
111
+ """
112
+ Call the /v1/message endpoint to analyze task and screenshot
113
+
114
+ Args:
115
+ model: The model to use for task analysis
116
+ screenshot: Base64-encoded screenshot image
117
+ task_description: Description of the task (required for new sessions)
118
+ task_id: Task ID for continuing existing task
119
+ instruction: Additional instruction when continuing a session (only works with task_id)
120
+ max_actions: Maximum number of actions to return (1-20)
121
+ api_version: API version header
122
+
123
+ Returns:
124
+ LLMResponse: The response from the API
125
+
126
+ Raises:
127
+ httpx.HTTPStatusError: For HTTP error responses
128
+ """
129
+ headers = {}
130
+ if api_version:
131
+ headers["x-api-version"] = api_version
132
+ if self.api_key:
133
+ headers["x-api-key"] = self.api_key
134
+
135
+ payload = {"model": model, "screenshot": screenshot}
136
+
137
+ if task_description is not None:
138
+ payload["task_description"] = task_description
139
+ if task_id is not None:
140
+ payload["task_id"] = task_id
141
+ if instruction is not None:
142
+ payload["instruction"] = instruction
143
+ if max_actions is not None:
144
+ payload["max_actions"] = max_actions
145
+
146
+ logger.info(f"Making API request to /v1/message with model: {model}")
147
+ logger.debug(
148
+ f"Request includes task_description: {task_description is not None}, task_id: {task_id is not None}"
149
+ )
150
+
151
+ try:
152
+ response = self.client.post(
153
+ "/v1/message", json=payload, headers=headers, timeout=self.timeout
154
+ )
155
+ except httpx.TimeoutException as e:
156
+ logger.error(f"Request timed out after {self.timeout} seconds")
157
+ raise RequestTimeoutError(
158
+ f"Request timed out after {self.timeout} seconds", e
159
+ )
160
+ except httpx.NetworkError as e:
161
+ logger.error(f"Network error: {e}")
162
+ raise NetworkError(f"Network error: {e}", e)
163
+
164
+ try:
165
+ response_data = response.json()
166
+ except ValueError:
167
+ # If response is not JSON, raise API error
168
+ logger.error(f"Non-JSON API response: {response.status_code}")
169
+ raise APIError(
170
+ f"Invalid response format (status {response.status_code})",
171
+ status_code=response.status_code,
172
+ response=response,
173
+ )
174
+
175
+ # Check if it's an error response (non-200 status or has error field)
176
+ if response.status_code != 200:
177
+ error_resp = ErrorResponse(**response_data)
178
+ if error_resp.error:
179
+ error_code = error_resp.error.code
180
+ error_msg = error_resp.error.message
181
+ logger.error(f"API Error [{error_code}]: {error_msg}")
182
+
183
+ # Map to specific exception types based on status code
184
+ exception_class = self._get_exception_class(response.status_code)
185
+ raise exception_class(
186
+ error_msg,
187
+ code=error_code,
188
+ status_code=response.status_code,
189
+ response=response,
190
+ )
191
+ else:
192
+ # Error response without error details
193
+ logger.error(
194
+ f"API error response without details: {response.status_code}"
195
+ )
196
+ exception_class = self._get_exception_class(response.status_code)
197
+ raise exception_class(
198
+ f"API error (status {response.status_code})",
199
+ status_code=response.status_code,
200
+ response=response,
201
+ )
202
+
203
+ # Parse successful response
204
+ result = LLMResponse(**response_data)
205
+
206
+ # Check if the response contains an error (even with 200 status)
207
+ if result.error:
208
+ logger.error(
209
+ f"API Error in response: [{result.error.code}]: {result.error.message}"
210
+ )
211
+ raise APIError(
212
+ result.error.message,
213
+ code=result.error.code,
214
+ status_code=200,
215
+ response=response,
216
+ )
217
+
218
+ logger.info(
219
+ f"API request successful - task_id: {result.task_id}, step: {result.current_step}, complete: {result.is_complete}"
220
+ )
221
+ logger.debug(f"Response included {len(result.actions)} actions")
222
+ return result
223
+
224
+ def _get_exception_class(self, status_code: int) -> type[APIError]:
225
+ """Get the appropriate exception class based on status code."""
226
+ status_map = {
227
+ 401: AuthenticationError,
228
+ 404: NotFoundError,
229
+ 422: ValidationError,
230
+ 429: RateLimitError,
231
+ }
232
+
233
+ if status_code >= 500:
234
+ return ServerError
235
+
236
+ return status_map.get(status_code, APIError)
237
+
238
+ def health_check(self) -> dict:
239
+ """
240
+ Call the /health endpoint for health check
241
+
242
+ Returns:
243
+ dict: Health check response
244
+ """
245
+ logger.debug("Making health check request")
246
+ try:
247
+ response = self.client.get("/health")
248
+ response.raise_for_status()
249
+ result = response.json()
250
+ logger.debug("Health check successful")
251
+ return result
252
+ except httpx.HTTPStatusError as e:
253
+ logger.warning(f"Health check failed: {e}")
254
+ raise
255
+
256
+
257
+ def encode_screenshot_from_bytes(image_bytes: bytes) -> str:
258
+ """Helper function to encode image bytes to base64 string"""
259
+ return base64.b64encode(image_bytes).decode("utf-8")
260
+
261
+
262
+ def encode_screenshot_from_file(image_path: str) -> str:
263
+ """Helper function to encode image file to base64 string"""
264
+ with open(image_path, "rb") as f:
265
+ return encode_screenshot_from_bytes(f.read())
oagi/task.py ADDED
@@ -0,0 +1,109 @@
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
+ from .logging import get_logger
10
+ from .sync_client import SyncClient, encode_screenshot_from_bytes
11
+ from .types import Image, Step
12
+
13
+ logger = get_logger("task")
14
+
15
+
16
+ class Task:
17
+ """Base class for task automation with the OAGI API."""
18
+
19
+ def __init__(self, api_key: str | None = None, base_url: str | None = None):
20
+ self.client = SyncClient(base_url=base_url, api_key=api_key)
21
+ self.api_key = self.client.api_key
22
+ self.base_url = self.client.base_url
23
+ self.task_id: str | None = None
24
+ self.task_description: str | None = None
25
+ self.model = "vision-model-v1" # default model
26
+
27
+ def init_task(self, task_desc: str, max_steps: int = 5):
28
+ """Initialize a new task with the given description."""
29
+ self.task_description = task_desc
30
+ response = self.client.create_message(
31
+ model=self.model,
32
+ screenshot="",
33
+ task_description=self.task_description,
34
+ task_id=None,
35
+ )
36
+ self.task_id = response.task_id # Reset task_id for new task
37
+ logger.info(f"Task initialized: '{task_desc}' (max_steps: {max_steps})")
38
+
39
+ def step(self, screenshot: Image | bytes, instruction: str | None = None) -> Step:
40
+ """Send screenshot to the server and get the next actions.
41
+
42
+ Args:
43
+ screenshot: Screenshot as Image object or raw bytes
44
+ instruction: Optional additional instruction for this step (only works with existing task_id)
45
+
46
+ Returns:
47
+ Step: The actions and reasoning for this step
48
+ """
49
+ if not self.task_description:
50
+ raise ValueError("Task description must be set. Call init_task() first.")
51
+
52
+ logger.debug(f"Executing step for task: '{self.task_description}'")
53
+
54
+ try:
55
+ # Convert Image to bytes using the protocol
56
+ if isinstance(screenshot, Image):
57
+ screenshot_bytes = screenshot.read()
58
+ else:
59
+ screenshot_bytes = screenshot
60
+ screenshot_b64 = encode_screenshot_from_bytes(screenshot_bytes)
61
+
62
+ # Call API
63
+ response = self.client.create_message(
64
+ model=self.model,
65
+ screenshot=screenshot_b64,
66
+ task_description=self.task_description,
67
+ task_id=self.task_id,
68
+ instruction=instruction,
69
+ )
70
+
71
+ # Update task_id from response
72
+ if self.task_id != response.task_id:
73
+ if self.task_id is None:
74
+ logger.debug(f"Task ID assigned: {response.task_id}")
75
+ else:
76
+ logger.debug(
77
+ f"Task ID changed: {self.task_id} -> {response.task_id}"
78
+ )
79
+ self.task_id = response.task_id
80
+
81
+ # Convert API response to Step
82
+ result = Step(
83
+ reason=response.reason,
84
+ actions=response.actions,
85
+ stop=response.is_complete,
86
+ )
87
+
88
+ if response.is_complete:
89
+ logger.info(f"Task completed after {response.current_step} steps")
90
+ else:
91
+ logger.debug(
92
+ f"Step {response.current_step} completed with {len(response.actions)} actions"
93
+ )
94
+
95
+ return result
96
+
97
+ except Exception as e:
98
+ logger.error(f"Error during step execution: {e}")
99
+ raise
100
+
101
+ def close(self):
102
+ """Close the underlying HTTP client to free resources."""
103
+ self.client.close()
104
+
105
+ def __enter__(self):
106
+ return self
107
+
108
+ def __exit__(self, exc_type, exc_val, exc_tb):
109
+ self.close()
oagi/types/__init__.py ADDED
@@ -0,0 +1,14 @@
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
+ from .action_handler import ActionHandler
10
+ from .image import Image
11
+ from .image_provider import ImageProvider
12
+ from .models import Action, ActionType, Step
13
+
14
+ __all__ = ["Action", "ActionType", "Image", "Step", "ActionHandler", "ImageProvider"]
@@ -0,0 +1,30 @@
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
+ from typing import Protocol
10
+
11
+ from .models import Action
12
+
13
+
14
+ class ActionHandler(Protocol):
15
+ def __call__(self, actions: list[Action]) -> None:
16
+ """
17
+ Executes a list of actions.
18
+
19
+ This method takes a list of `Action` objects and executes them. It is used
20
+ to perform operations represented by the `Action` instances. This method
21
+ does not return any value and modifies the system based on the input actions.
22
+
23
+ Parameters:
24
+ actions (list[Action]): A list of `Action` objects to be executed. Each
25
+ `Action` must encapsulate the logic that is intended to be applied
26
+ during the call.
27
+
28
+ Raises:
29
+ RuntimeError: If an error occurs during the execution of the actions.
30
+ """
oagi/types/image.py ADDED
@@ -0,0 +1,17 @@
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
+ from typing import Protocol, runtime_checkable
10
+
11
+
12
+ @runtime_checkable
13
+ class Image(Protocol):
14
+ """Protocol for image objects that can be read as bytes."""
15
+
16
+ def read(self) -> bytes:
17
+ """Read the image data as bytes."""
@@ -0,0 +1,34 @@
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
+ from typing import Protocol
10
+
11
+ from .image import Image
12
+
13
+
14
+ class ImageProvider(Protocol):
15
+ def __call__(self) -> Image:
16
+ """
17
+ Represents the functionality to invoke the callable object and produce an Image
18
+ result. Typically used to process or generate images using the defined logic
19
+ within the __call__ method.
20
+
21
+ Returns:
22
+ Image: The resulting image output from the callable logic.
23
+ """
24
+
25
+ def last_image(self) -> Image:
26
+ """
27
+ Returns the last captured image.
28
+
29
+ This method retrieves the most recent image that was captured and stored
30
+ in memory. If there are no images available, the method may return None.
31
+
32
+ Returns:
33
+ Image: The last captured image, or None if no images are available.
34
+ """
@@ -0,0 +1,12 @@
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
+ from .action import Action, ActionType
10
+ from .step import Step
11
+
12
+ __all__ = ["Action", "ActionType", "Step"]
@@ -0,0 +1,32 @@
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
+ from enum import Enum
10
+
11
+ from pydantic import BaseModel, Field
12
+
13
+
14
+ class ActionType(str, Enum):
15
+ CLICK = "click"
16
+ LEFT_DOUBLE = "left_double"
17
+ RIGHT_SINGLE = "right_single"
18
+ DRAG = "drag"
19
+ HOTKEY = "hotkey"
20
+ TYPE = "type"
21
+ SCROLL = "scroll"
22
+ FINISH = "finish"
23
+ WAIT = "wait"
24
+ CALL_USER = "call_user"
25
+
26
+
27
+ class Action(BaseModel):
28
+ type: ActionType = Field(..., description="Type of action to perform")
29
+ argument: str = Field(..., description="Action argument in the specified format")
30
+ count: int | None = Field(
31
+ default=1, ge=1, description="Number of times to repeat the action"
32
+ )
@@ -0,0 +1,17 @@
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
+ from pydantic import BaseModel
10
+
11
+ from .action import Action
12
+
13
+
14
+ class Step(BaseModel):
15
+ reason: str | None = None
16
+ actions: list[Action]
17
+ stop: bool = False
@@ -1,31 +1,55 @@
1
- Metadata-Version: 2.4
2
- Name: oagi
3
- Version: 0.0.0
4
- Summary: Official API of OpenAGI Foundation
5
- Author-email: OpenAGI Foundation <contact@agiopen.org>
6
- License: MIT License
7
-
8
- Copyright (c) 2025 OpenAGI Foundation
9
-
10
- Permission is hereby granted, free of charge, to any person obtaining a copy
11
- of this software and associated documentation files (the "Software"), to deal
12
- in the Software without restriction, including without limitation the rights
13
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
- copies of the Software, and to permit persons to whom the Software is
15
- furnished to do so, subject to the following conditions:
16
-
17
- The above copyright notice and this permission notice shall be included in all
18
- copies or substantial portions of the Software.
19
-
20
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
- SOFTWARE.
27
-
28
- Project-URL: Homepage, https://github.com/agiopen-org/oagi
29
- Description-Content-Type: text/markdown
30
- License-File: LICENSE
31
- Dynamic: license-file
1
+ Metadata-Version: 2.3
2
+ Name: oagi
3
+ Version: 0.2.0
4
+ Summary: Official API of OpenAGI Foundation
5
+ Project-URL: Homepage, https://github.com/agiopen-org/oagi
6
+ Author-email: OpenAGI Foundation <contact@agiopen.org>
7
+ License: MIT License
8
+
9
+ Copyright (c) 2025 OpenAGI Foundation
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
28
+ Requires-Python: >=3.10
29
+ Requires-Dist: httpx>=0.28.0
30
+ Requires-Dist: pillow>=11.3.0
31
+ Requires-Dist: pyautogui>=0.9.54
32
+ Requires-Dist: pydantic>=2.0.0
33
+ Description-Content-Type: text/markdown
34
+
35
+ # OAGI Python SDK
36
+
37
+ ## Basic Usage
38
+ ```bash
39
+ pip install oagi # python >= 3.10
40
+ ```
41
+ ```bash
42
+ export OAGI_BASE_URL=""
43
+ export OAGI_API_KEY="sk-xxxx"
44
+ ```
45
+
46
+ ```python
47
+ from oagi import PyautoguiActionHandler, ScreenshotMaker, ShortTask
48
+ short_task = ShortTask()
49
+ is_completed = short_task.auto_mode(
50
+ "Search weather with Google",
51
+ max_steps=5,
52
+ executor=PyautoguiActionHandler(),
53
+ image_provider=(sm := ScreenshotMaker()),
54
+ )
55
+ ```
@@ -0,0 +1,20 @@
1
+ oagi/__init__.py,sha256=ms9ahLdHNrMWtiqX93q8Iv55ag__tO4Id0DQ3hA2TVM,1347
2
+ oagi/exceptions.py,sha256=VMwVS8ouE9nHhBpN3AZMYt5_U2kGcihWaTnBhoQLquo,1662
3
+ oagi/logging.py,sha256=CWe89mA5MKTipIvfrqSYkv2CAFNBSwHMDQMDkG_g64g,1350
4
+ oagi/pyautogui_action_handler.py,sha256=LBWmtqkXzZSJo07s3uOw-NWUE9rZZtbNAx0YI83pCbk,5482
5
+ oagi/screenshot_maker.py,sha256=lyJSMFagHeaqg59CQGMTqLvSzQN_pBbhbV2oIFG46vA,2077
6
+ oagi/short_task.py,sha256=ofcMi7vbu9W1MCSGOk_FNEHJcB02pfgNcx1-Y8UkpJY,1552
7
+ oagi/single_step.py,sha256=JEsF7ABa4wwW5Pi5AfjeKzyuKhC4kC4fcotnmnNye5o,2874
8
+ oagi/sync_client.py,sha256=XIuqAHD56BkBz5v4HshgWpjmfzs_z7TQbjDEzIcnKJA,8678
9
+ oagi/task.py,sha256=NmpNMu8CJll50zGsGtVie1kdpKeWnAAWudEa-aasBbU,3959
10
+ oagi/types/__init__.py,sha256=eh-1IEqMTY2hUrvQJeTg6vsvlE6F4Iz5C0_K86AnWn8,549
11
+ oagi/types/action_handler.py,sha256=NH8E-m5qpGqWcXzTSWfF7W0Xdp8SkzJsbhCmQ0B96cg,1075
12
+ oagi/types/image.py,sha256=KgPCCTJ6D5vHIaGZdbTE7eQEa1WlT6G9tf59ZuUCV2U,537
13
+ oagi/types/image_provider.py,sha256=oYFdOYznrK_VOR9egzOjw5wFM5w8EY2sY01pH0ANAgU,1112
14
+ oagi/types/models/__init__.py,sha256=4qhKxWXsXEVzD6U_RM6PXR45os765qigtZs1BsS4WHg,414
15
+ oagi/types/models/action.py,sha256=8Xd3IcH32ENq7uXczo-mbQ736yUOGxO_TaZTfHVRY7w,935
16
+ oagi/types/models/step.py,sha256=RSI4H_2rrUBq_xyCoWKaq7JHdJWNobtQppaKC1l0aWU,471
17
+ oagi-0.2.0.dist-info/METADATA,sha256=nk3a9mv2DvZ1LKEpV-1nHH1TEbrqKv8OALN_8LJ47tQ,2066
18
+ oagi-0.2.0.dist-info/WHEEL,sha256=C2FUgwZgiLbznR-k0b_5k3Ai_1aASOXDss3lzCUsUug,87
19
+ oagi-0.2.0.dist-info/licenses/LICENSE,sha256=sy5DLA2M29jFT4UfWsuBF9BAr3FnRkYtnAu6oDZiIf8,1075
20
+ oagi-0.2.0.dist-info/RECORD,,
@@ -1,5 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (80.9.0)
2
+ Generator: hatchling 1.26.3
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
-
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 OpenAGI Foundation
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.
1
+ MIT License
2
+
3
+ Copyright (c) 2025 OpenAGI Foundation
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.
oagi/core.py DELETED
@@ -1,2 +0,0 @@
1
- def hello():
2
- return "Hello from OpenAGI Foundation!"
@@ -1,7 +0,0 @@
1
- oagi/__init__.py,sha256=K1GAo2fdj3I1a2lP7RIu-ViQ52DJ84qV5imkQNkF0JE,25
2
- oagi/core.py,sha256=eU5aYaEmmgcUSmiPnRB9njRUI4Xrij2HcPunh67T86M,57
3
- oagi-0.0.0.dist-info/licenses/LICENSE,sha256=xHvNtuFT_mr6qQ1vGCphFj9r4Jc6h4VJLXTVYkFzgWM,1096
4
- oagi-0.0.0.dist-info/METADATA,sha256=h-xCKLcBqz9MiIIUELPUoK1Hz60Snvb8UXdMlCsGUDQ,1574
5
- oagi-0.0.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
6
- oagi-0.0.0.dist-info/top_level.txt,sha256=t4TE_HUmY4z48HHEpgpmRYWnHdmXKzSdjzLxsx7Gkd0,5
7
- oagi-0.0.0.dist-info/RECORD,,
@@ -1 +0,0 @@
1
- oagi