ws-bom-robot-app 0.0.104__py3-none-any.whl → 0.0.106__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.
@@ -1,216 +1,216 @@
1
- import asyncio, logging, aiohttp
2
- from ws_bom_robot_app.llm.vector_store.integration.base import IntegrationStrategy
3
- from langchain_core.documents import Document
4
- from ws_bom_robot_app.llm.vector_store.loader.base import Loader
5
- from typing import List, Union, Optional, Dict, Any, Literal
6
- from pydantic import BaseModel, Field, AliasChoices, field_validator
7
- import json
8
- import os
9
-
10
-
11
- class AuthConfig(BaseModel):
12
- """
13
- Configuration for API authentication.
14
-
15
- Attributes:
16
- type: Type of authentication (bearer, basic, api_key, custom, none)
17
- token: Bearer token or API key value
18
- username: Username for basic auth
19
- password: Password for basic auth
20
- header_name: Custom header name for API key
21
- prefix: Prefix for the auth value (e.g., 'Bearer', 'Token')
22
- """
23
- type: Literal["bearer", "basic", "api_key", "custom", "none"] = Field(default="none")
24
- token: Optional[str] = Field(default=None)
25
- username: Optional[str] = Field(default=None)
26
- password: Optional[str] = Field(default=None)
27
- header_name: Optional[str] = Field(default=None, validation_alias=AliasChoices("headerName", "header_name"))
28
- prefix: Optional[str] = Field(default=None)
29
-
30
-
31
- class ApiParams(BaseModel):
32
- """
33
- Generic API Integration Parameters.
34
-
35
- Attributes:
36
- url: The base URL of the API endpoint
37
- method: HTTP method (GET, POST, PUT, DELETE, PATCH)
38
- headers: Custom headers to include in the request
39
- params: Query parameters for the request
40
- body: Request body for POST/PUT/PATCH requests
41
- auth: Authentication configuration
42
- response_data_path: JSON path to extract data from response (e.g., 'data.items', 'results')
43
- max_retries: Maximum number of retry attempts for failed requests
44
- retry_delay: Base delay in seconds between retries (uses exponential backoff)
45
- timeout: Request timeout in seconds
46
- """
47
- url: str = Field(validation_alias=AliasChoices("url", "endpoint"))
48
- method: Literal["GET", "POST", "PUT", "DELETE", "PATCH"] = Field(default="GET")
49
- headers: Optional[Dict[str, str]] = Field(default_factory=dict)
50
- params: Optional[Dict[str, Any]] = Field(default_factory=dict)
51
- body: Optional[Union[Dict[str, Any], str]] = Field(default=None)
52
- auth: Optional[AuthConfig] = Field(default_factory=lambda: AuthConfig())
53
- response_data_path: Optional[str] = Field(default=None, validation_alias=AliasChoices("responseDataPath", "response_data_path"))
54
- max_retries: int = Field(default=5, validation_alias=AliasChoices("maxRetries", "max_retries"))
55
- retry_delay: float = Field(default=1.0, validation_alias=AliasChoices("retryDelay", "retry_delay"))
56
- timeout: int = Field(default=30)
57
-
58
- @field_validator('auth', mode='before')
59
- @classmethod
60
- def parse_auth(cls, v):
61
- """Parse auth config from dict if needed"""
62
- if isinstance(v, dict):
63
- return AuthConfig(**v)
64
- return v or AuthConfig()
65
-
66
-
67
- class Api(IntegrationStrategy):
68
- """
69
- Generic API Integration that supports:
70
- - Multiple HTTP methods (GET, POST, PUT, DELETE, PATCH)
71
- - Various authentication types (Bearer, Basic, API Key, Custom)
72
- - Custom headers and parameters
73
- - Automatic retry with exponential backoff
74
- - Flexible response data extraction
75
- """
76
-
77
- def __init__(self, knowledgebase_path: str, data: dict[str, Union[str, int, list]]):
78
- super().__init__(knowledgebase_path, data)
79
- self.__data = ApiParams.model_validate(self.data)
80
-
81
- def working_subdirectory(self) -> str:
82
- return 'api_integration'
83
-
84
- async def run(self) -> None:
85
- """Fetch data from the API and save to JSON file"""
86
- _data = await self.__fetch_data()
87
- json_file_path = os.path.join(self.working_directory, 'api_data.json')
88
- with open(json_file_path, 'w', encoding='utf-8') as f:
89
- json.dump(_data, f, ensure_ascii=False, indent=2)
90
- logging.info(f"Saved {len(_data) if isinstance(_data, list) else 1} items to {json_file_path}")
91
-
92
- async def load(self) -> list[Document]:
93
- """Load data from API and convert to documents"""
94
- await self.run()
95
- await asyncio.sleep(1)
96
- return await Loader(self.working_directory).load()
97
-
98
- def __prepare_headers(self) -> Dict[str, str]:
99
- """Prepare request headers with authentication"""
100
- headers = self.__data.headers.copy() if self.__data.headers else {}
101
-
102
- # Add Content-Type if not present
103
- if 'Content-Type' not in headers and self.__data.method in ["POST", "PUT", "PATCH"]:
104
- headers['Content-Type'] = 'application/json'
105
-
106
- # Add authentication
107
- auth = self.__data.auth
108
- if auth.type == "bearer":
109
- prefix = auth.prefix or "Bearer"
110
- headers['Authorization'] = f"{prefix} {auth.token}"
111
- elif auth.type == "basic":
112
- import base64
113
- credentials = f"{auth.username}:{auth.password}"
114
- encoded = base64.b64encode(credentials.encode()).decode()
115
- headers['Authorization'] = f"Basic {encoded}"
116
- elif auth.type == "api_key" and auth.header_name:
117
- prefix = f"{auth.prefix} " if auth.prefix else ""
118
- headers[auth.header_name] = f"{prefix}{auth.token}"
119
-
120
- return headers
121
-
122
- def __get_nested_value(self, data: Any, path: Optional[str]) -> Any:
123
- """Extract nested value from data using dot notation path"""
124
- if not path:
125
- return data
126
-
127
- keys = path.split('.')
128
- current = data
129
- for key in keys:
130
- if isinstance(current, dict):
131
- current = current.get(key)
132
- elif isinstance(current, list) and key.isdigit():
133
- current = current[int(key)]
134
- else:
135
- return None
136
-
137
- if current is None:
138
- return None
139
-
140
- return current
141
-
142
- async def __make_request(
143
- self,
144
- url: str,
145
- headers: Dict[str, str],
146
- params: Optional[Dict[str, Any]] = None
147
- ) -> Dict[str, Any]:
148
- """Make HTTP request with retry logic"""
149
- retry_count = 0
150
-
151
- while retry_count <= self.__data.max_retries:
152
- try:
153
- timeout = aiohttp.ClientTimeout(total=self.__data.timeout)
154
-
155
- async with aiohttp.ClientSession(timeout=timeout) as session:
156
- request_kwargs = {
157
- "headers": headers,
158
- "params": params or self.__data.params
159
- }
160
-
161
- # Add body for POST/PUT/PATCH
162
- if self.__data.method in ["POST", "PUT", "PATCH"] and self.__data.body:
163
- if isinstance(self.__data.body, dict):
164
- request_kwargs["json"] = self.__data.body
165
- else:
166
- request_kwargs["data"] = self.__data.body
167
-
168
- async with session.request(
169
- self.__data.method,
170
- url,
171
- **request_kwargs
172
- ) as response:
173
- # Check response status
174
- if response.status == 429: # Rate limit
175
- retry_count += 1
176
- if retry_count > self.__data.max_retries:
177
- raise Exception("Rate limit exceeded. Maximum retries reached.")
178
-
179
- wait_time = self.__data.retry_delay * (2 ** retry_count)
180
- logging.warning(f"Rate limited. Waiting {wait_time}s (Attempt {retry_count}/{self.__data.max_retries})")
181
- await asyncio.sleep(wait_time)
182
- continue
183
-
184
- response.raise_for_status()
185
-
186
- # Parse response
187
- try:
188
- data = await response.json()
189
- return data
190
- except aiohttp.ContentTypeError:
191
- text = await response.text()
192
- logging.warning(f"Non-JSON response received: {text[:200]}")
193
- return {"text": text}
194
-
195
- except aiohttp.ClientError as e:
196
- retry_count += 1
197
- if retry_count > self.__data.max_retries:
198
- raise Exception(f"Request failed after {self.__data.max_retries} retries: {e}")
199
-
200
- wait_time = self.__data.retry_delay * (2 ** retry_count)
201
- logging.warning(f"Request error: {e}. Retrying in {wait_time}s...")
202
- await asyncio.sleep(wait_time)
203
- continue
204
-
205
- raise Exception("Maximum retries exceeded")
206
-
207
- async def __fetch_data(self) -> Any:
208
- """Fetch data from API"""
209
- headers = self.__prepare_headers()
210
- response = await self.__make_request(self.__data.url, headers)
211
-
212
- # Extract data from response using path if specified
213
- data = self.__get_nested_value(response, self.__data.response_data_path)
214
- result = data if data is not None else response
215
-
216
- return result
1
+ import asyncio, logging, aiohttp
2
+ from ws_bom_robot_app.llm.vector_store.integration.base import IntegrationStrategy
3
+ from langchain_core.documents import Document
4
+ from ws_bom_robot_app.llm.vector_store.loader.base import Loader
5
+ from typing import List, Union, Optional, Dict, Any, Literal
6
+ from pydantic import BaseModel, Field, AliasChoices, field_validator
7
+ import json
8
+ import os
9
+
10
+
11
+ class AuthConfig(BaseModel):
12
+ """
13
+ Configuration for API authentication.
14
+
15
+ Attributes:
16
+ type: Type of authentication (bearer, basic, api_key, custom, none)
17
+ token: Bearer token or API key value
18
+ username: Username for basic auth
19
+ password: Password for basic auth
20
+ header_name: Custom header name for API key
21
+ prefix: Prefix for the auth value (e.g., 'Bearer', 'Token')
22
+ """
23
+ type: Literal["bearer", "basic", "api_key", "custom", "none"] = Field(default="none")
24
+ token: Optional[str] = Field(default=None)
25
+ username: Optional[str] = Field(default=None)
26
+ password: Optional[str] = Field(default=None)
27
+ header_name: Optional[str] = Field(default=None, validation_alias=AliasChoices("headerName", "header_name"))
28
+ prefix: Optional[str] = Field(default=None)
29
+
30
+
31
+ class ApiParams(BaseModel):
32
+ """
33
+ Generic API Integration Parameters.
34
+
35
+ Attributes:
36
+ url: The base URL of the API endpoint
37
+ method: HTTP method (GET, POST, PUT, DELETE, PATCH)
38
+ headers: Custom headers to include in the request
39
+ params: Query parameters for the request
40
+ body: Request body for POST/PUT/PATCH requests
41
+ auth: Authentication configuration
42
+ response_data_path: JSON path to extract data from response (e.g., 'data.items', 'results')
43
+ max_retries: Maximum number of retry attempts for failed requests
44
+ retry_delay: Base delay in seconds between retries (uses exponential backoff)
45
+ timeout: Request timeout in seconds
46
+ """
47
+ url: str = Field(validation_alias=AliasChoices("url", "endpoint"))
48
+ method: Literal["GET", "POST", "PUT", "DELETE", "PATCH"] = Field(default="GET")
49
+ headers: Optional[Dict[str, str]] = Field(default_factory=dict)
50
+ params: Optional[Dict[str, Any]] = Field(default_factory=dict)
51
+ body: Optional[Union[Dict[str, Any], str]] = Field(default=None)
52
+ auth: Optional[AuthConfig] = Field(default_factory=lambda: AuthConfig())
53
+ response_data_path: Optional[str] = Field(default=None, validation_alias=AliasChoices("responseDataPath", "response_data_path"))
54
+ max_retries: int = Field(default=5, validation_alias=AliasChoices("maxRetries", "max_retries"))
55
+ retry_delay: float = Field(default=1.0, validation_alias=AliasChoices("retryDelay", "retry_delay"))
56
+ timeout: int = Field(default=30)
57
+
58
+ @field_validator('auth', mode='before')
59
+ @classmethod
60
+ def parse_auth(cls, v):
61
+ """Parse auth config from dict if needed"""
62
+ if isinstance(v, dict):
63
+ return AuthConfig(**v)
64
+ return v or AuthConfig()
65
+
66
+
67
+ class Api(IntegrationStrategy):
68
+ """
69
+ Generic API Integration that supports:
70
+ - Multiple HTTP methods (GET, POST, PUT, DELETE, PATCH)
71
+ - Various authentication types (Bearer, Basic, API Key, Custom)
72
+ - Custom headers and parameters
73
+ - Automatic retry with exponential backoff
74
+ - Flexible response data extraction
75
+ """
76
+
77
+ def __init__(self, knowledgebase_path: str, data: dict[str, Union[str, int, list]]):
78
+ super().__init__(knowledgebase_path, data)
79
+ self.__data = ApiParams.model_validate(self.data)
80
+
81
+ def working_subdirectory(self) -> str:
82
+ return 'api_integration'
83
+
84
+ async def run(self) -> None:
85
+ """Fetch data from the API and save to JSON file"""
86
+ _data = await self.__fetch_data()
87
+ json_file_path = os.path.join(self.working_directory, 'api_data.json')
88
+ with open(json_file_path, 'w', encoding='utf-8') as f:
89
+ json.dump(_data, f, ensure_ascii=False, indent=2)
90
+ logging.info(f"Saved {len(_data) if isinstance(_data, list) else 1} items to {json_file_path}")
91
+
92
+ async def load(self) -> list[Document]:
93
+ """Load data from API and convert to documents"""
94
+ await self.run()
95
+ await asyncio.sleep(1)
96
+ return await Loader(self.working_directory).load()
97
+
98
+ def __prepare_headers(self) -> Dict[str, str]:
99
+ """Prepare request headers with authentication"""
100
+ headers = self.__data.headers.copy() if self.__data.headers else {}
101
+
102
+ # Add Content-Type if not present
103
+ if 'Content-Type' not in headers and self.__data.method in ["POST", "PUT", "PATCH"]:
104
+ headers['Content-Type'] = 'application/json'
105
+
106
+ # Add authentication
107
+ auth = self.__data.auth
108
+ if auth.type == "bearer":
109
+ prefix = auth.prefix or "Bearer"
110
+ headers['Authorization'] = f"{prefix} {auth.token}"
111
+ elif auth.type == "basic":
112
+ import base64
113
+ credentials = f"{auth.username}:{auth.password}"
114
+ encoded = base64.b64encode(credentials.encode()).decode()
115
+ headers['Authorization'] = f"Basic {encoded}"
116
+ elif auth.type == "api_key" and auth.header_name:
117
+ prefix = f"{auth.prefix} " if auth.prefix else ""
118
+ headers[auth.header_name] = f"{prefix}{auth.token}"
119
+
120
+ return headers
121
+
122
+ def __get_nested_value(self, data: Any, path: Optional[str]) -> Any:
123
+ """Extract nested value from data using dot notation path"""
124
+ if not path:
125
+ return data
126
+
127
+ keys = path.split('.')
128
+ current = data
129
+ for key in keys:
130
+ if isinstance(current, dict):
131
+ current = current.get(key)
132
+ elif isinstance(current, list) and key.isdigit():
133
+ current = current[int(key)]
134
+ else:
135
+ return None
136
+
137
+ if current is None:
138
+ return None
139
+
140
+ return current
141
+
142
+ async def __make_request(
143
+ self,
144
+ url: str,
145
+ headers: Dict[str, str],
146
+ params: Optional[Dict[str, Any]] = None
147
+ ) -> Dict[str, Any]:
148
+ """Make HTTP request with retry logic"""
149
+ retry_count = 0
150
+
151
+ while retry_count <= self.__data.max_retries:
152
+ try:
153
+ timeout = aiohttp.ClientTimeout(total=self.__data.timeout)
154
+
155
+ async with aiohttp.ClientSession(timeout=timeout) as session:
156
+ request_kwargs = {
157
+ "headers": headers,
158
+ "params": params or self.__data.params
159
+ }
160
+
161
+ # Add body for POST/PUT/PATCH
162
+ if self.__data.method in ["POST", "PUT", "PATCH"] and self.__data.body:
163
+ if isinstance(self.__data.body, dict):
164
+ request_kwargs["json"] = self.__data.body
165
+ else:
166
+ request_kwargs["data"] = self.__data.body
167
+
168
+ async with session.request(
169
+ self.__data.method,
170
+ url,
171
+ **request_kwargs
172
+ ) as response:
173
+ # Check response status
174
+ if response.status == 429: # Rate limit
175
+ retry_count += 1
176
+ if retry_count > self.__data.max_retries:
177
+ raise Exception("Rate limit exceeded. Maximum retries reached.")
178
+
179
+ wait_time = self.__data.retry_delay * (2 ** retry_count)
180
+ logging.warning(f"Rate limited. Waiting {wait_time}s (Attempt {retry_count}/{self.__data.max_retries})")
181
+ await asyncio.sleep(wait_time)
182
+ continue
183
+
184
+ response.raise_for_status()
185
+
186
+ # Parse response
187
+ try:
188
+ data = await response.json()
189
+ return data
190
+ except aiohttp.ContentTypeError:
191
+ text = await response.text()
192
+ logging.warning(f"Non-JSON response received: {text[:200]}")
193
+ return {"text": text}
194
+
195
+ except aiohttp.ClientError as e:
196
+ retry_count += 1
197
+ if retry_count > self.__data.max_retries:
198
+ raise Exception(f"Request failed after {self.__data.max_retries} retries: {e}")
199
+
200
+ wait_time = self.__data.retry_delay * (2 ** retry_count)
201
+ logging.warning(f"Request error: {e}. Retrying in {wait_time}s...")
202
+ await asyncio.sleep(wait_time)
203
+ continue
204
+
205
+ raise Exception("Maximum retries exceeded")
206
+
207
+ async def __fetch_data(self) -> Any:
208
+ """Fetch data from API"""
209
+ headers = self.__prepare_headers()
210
+ response = await self.__make_request(self.__data.url, headers)
211
+
212
+ # Extract data from response using path if specified
213
+ data = self.__get_nested_value(response, self.__data.response_data_path)
214
+ result = data if data is not None else response
215
+
216
+ return result