AbstractIntegratedModule 0.7.5__tar.gz → 0.7.6__tar.gz

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.
Files changed (23) hide show
  1. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/AbstractIntegratedModule.egg-info/PKG-INFO +5 -11
  2. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/AbstractIntegratedModule.py +187 -126
  3. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/AbstractOptimizedModules.c +200 -200
  4. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/PKG-INFO +5 -11
  5. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/README.md +4 -10
  6. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/abstract_model_storage/src/lib.rs +183 -13
  7. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/setup.py +1 -1
  8. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/AbstractIntegratedModule.egg-info/SOURCES.txt +0 -0
  9. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/AbstractIntegratedModule.egg-info/dependency_links.txt +0 -0
  10. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/AbstractIntegratedModule.egg-info/requires.txt +0 -0
  11. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/AbstractIntegratedModule.egg-info/top_level.txt +0 -0
  12. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/AbstractOptimizedModules.pyx +0 -0
  13. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/MANIFEST.in +0 -0
  14. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/abstract_model_storage/Cargo.toml +0 -0
  15. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/abstract_model_storage/pyproject.toml +0 -0
  16. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/abstract_model_storage/target/debug/build/libsqlite3-sys-ed07b882cd2aa5e2/out/bindgen.rs +0 -0
  17. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/abstract_model_storage/target/debug/build/serde_core-ebc15f2e9cad7f5f/out/private.rs +0 -0
  18. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/abstract_model_storage/target/debug/build/target-lexicon-08527f45de28143d/out/host.rs +0 -0
  19. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/abstract_model_storage/target/release/build/libsqlite3-sys-bf0400df4523274c/out/bindgen.rs +0 -0
  20. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/abstract_model_storage/target/release/build/serde_core-5cdb76131825e4af/out/private.rs +0 -0
  21. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/abstract_model_storage/target/release/build/target-lexicon-43eb95a0588bf457/out/host.rs +0 -0
  22. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/pyproject.toml +0 -0
  23. {abstractintegratedmodule-0.7.5 → abstractintegratedmodule-0.7.6}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: AbstractIntegratedModule
3
- Version: 0.7.5
3
+ Version: 0.7.6
4
4
  Summary: Library for Advanced Integrated Non-LLM AI Models - Optimized Backend Framework For Non-LLM AI Agent
5
5
  Author: Micro-Novelty
6
6
  Author-email: hernikpuspita5@gmail.com
@@ -42,7 +42,7 @@ https://github.com/Micro-Novelty/IntegratedPipeline-Specialized-Non-LLM-AI-Agent
42
42
  #### Note: The README here you are reading is a direct copy from my README Repository, to download the necessary files, you can visit my Repository with the provided link above.
43
43
 
44
44
  ### Library Short Description:
45
- - Development Stage: 0.7.4 Official Release.
45
+ - Development Stage: 0.7.6 Official Release.
46
46
  - Maintainer: Micro-Novelty.
47
47
  - library Source-Code is Open-sourced on github.
48
48
  - Purpose: Specifically Designed for providing Non-LLM AI Agent Framework for edge Devices, Optimized for ARM64 architecture.
@@ -66,16 +66,10 @@ https://github.com/Micro-Novelty/IntegratedPipeline-Specialized-Non-LLM-AI-Agent
66
66
  - Robust Advanced prediction capabilities proven effective on ARM64 Using MLP + LSTM Architectures.
67
67
  - Transformer Modules Optimized using Cython, to reduce Memory overhead and Reduce CPU Usage, With Reduced Training Time.
68
68
  - Changelog:
69
- - v0.7.4:
69
+ - v0.7.6:
70
70
  - [=] New features:
71
- - Adding Optimization and refinements, especially bug fixes in:
72
- - IntegratedPipeline lstm samples creating
73
- - IntegratedPipeline shape adaptation
74
- - IntegratedPipeline probability calibration
75
- - IntegratedPipeline auto generate labels text
76
- - IntegratedPipeline MLP samples generation.
77
- - Added New specific module in Rust for Parsing JSON values with reduced memory lookup overhead.
78
- - Fixed bug where number of classes can be None in edge cases.
71
+ - Adding Optimization and refinements for parsing JSON in Rust.
72
+ - Ensure robustness in calculating Samples similarity to prevent misleading answers in different environment.
79
73
 
80
74
  -----
81
75
 
@@ -42,7 +42,7 @@ import aiohttp
42
42
  import psutil
43
43
  from sklearn.preprocessing import StandardScaler
44
44
  import io
45
- from importlib import resources
45
+ import concurrent.futures
46
46
 
47
47
  # Optimized Modules In Cython implementation.
48
48
  try:
@@ -4656,51 +4656,60 @@ class ModelStorage:
4656
4656
  """
4657
4657
  if not isinstance(s, str) or not s:
4658
4658
  return s
4659
-
4660
- # Clean the string
4661
- s = s.replace('\n', '').replace('\r', '').replace('\t', '')
4662
- s = ' '.join(s.split()).strip()
4663
-
4664
- if not s:
4665
- return s
4666
-
4667
- # parsing as JSON array first
4668
- if s.startswith('[') and s.endswith(']'):
4659
+
4660
+ if _RUST_MODULE_AVAILABLE:
4669
4661
  try:
4670
- parsed = json.loads(s)
4671
- if isinstance(parsed, list):
4672
- return np.array(parsed, dtype=np.float32)
4673
- except (json.JSONDecodeError, ValueError):
4662
+ data = wc.parse_array_string(self.db_path, s)
4663
+ print('[+] Data successfully parsed!')
4664
+ return data
4665
+ except Exception as e:
4666
+ print(f'[!] Data cant be parsed due to: {e}')
4674
4667
  pass
4668
+ else:
4669
+ # Clean the string
4670
+ s = s.replace('\n', '').replace('\r', '').replace('\t', '')
4671
+ s = ' '.join(s.split()).strip()
4675
4672
 
4676
- # Try parsing with ast.literal_eval
4677
- try:
4678
- parsed = ast.literal_eval(s)
4679
- if isinstance(parsed, (list, tuple)):
4680
- return np.array(parsed, dtype=np.float32)
4681
- except (ValueError, SyntaxError, TypeError):
4682
- pass
4683
-
4684
- # parsing space-separated numbers
4685
- if re.fullmatch(r'[\[\]\s\d\.\,\-\+E]+', s):
4686
- parts = s.replace('[', ' ').replace(']', ' ').split()
4687
- if parts:
4673
+ if not s:
4674
+ return s
4675
+
4676
+ # parsing as JSON array first
4677
+ if s.startswith('[') and s.endswith(']'):
4678
+ try:
4679
+ parsed = json.loads(s)
4680
+ if isinstance(parsed, list):
4681
+ return np.array(parsed, dtype=np.float32)
4682
+ except (json.JSONDecodeError, ValueError):
4683
+ pass
4684
+
4685
+ # Try parsing with ast.literal_eval
4686
+ try:
4687
+ parsed = ast.literal_eval(s)
4688
+ if isinstance(parsed, (list, tuple)):
4689
+ return np.array(parsed, dtype=np.float32)
4690
+ except (ValueError, SyntaxError, TypeError):
4691
+ pass
4692
+
4693
+ # parsing space-separated numbers
4694
+ if re.fullmatch(r'[\[\]\s\d\.\,\-\+E]+', s):
4695
+ parts = s.replace('[', ' ').replace(']', ' ').split()
4696
+ if parts:
4697
+ try:
4698
+ float_values = [float(x) for x in parts]
4699
+ return np.array(float_values, dtype=np.float32)
4700
+ except ValueError:
4701
+ pass
4702
+
4703
+ # Handle comma-separated values
4704
+ if ',' in s:
4705
+ cleaned = s.replace('[', '').replace(']', '').strip()
4706
+ parts = [p.strip() for p in cleaned.split(',') if p.strip()]
4688
4707
  try:
4689
4708
  float_values = [float(x) for x in parts]
4690
4709
  return np.array(float_values, dtype=np.float32)
4691
4710
  except ValueError:
4692
4711
  pass
4693
4712
 
4694
- # Handle comma-separated values
4695
- if ',' in s:
4696
- cleaned = s.replace('[', '').replace(']', '').strip()
4697
- parts = [p.strip() for p in cleaned.split(',') if p.strip()]
4698
- try:
4699
- float_values = [float(x) for x in parts]
4700
- return np.array(float_values, dtype=np.float32)
4701
- except ValueError:
4702
- pass
4703
-
4704
4713
  # Return original string if nothing worked
4705
4714
  return s
4706
4715
 
@@ -4857,7 +4866,7 @@ class ModelStorage:
4857
4866
  if result:
4858
4867
  return json.loads(result[0])
4859
4868
  except Exception as e:
4860
- print(f'Error handling node dict: {e}')
4869
+ print(f'[!] Error handling node dict: {e}')
4861
4870
  return None
4862
4871
 
4863
4872
  def save_nodes_dict(self, memory_name, node_memory, node_id, model_type='Node'):
@@ -5231,6 +5240,7 @@ class ModelStorage:
5231
5240
  except:
5232
5241
  conn = sqlite3.connect(self.db_path)
5233
5242
 
5243
+
5234
5244
  c = conn.cursor()
5235
5245
  placeholders = ",".join(["?"] * len(agent_id))
5236
5246
 
@@ -5293,25 +5303,34 @@ class ModelStorage:
5293
5303
  except:
5294
5304
  conn = sqlite3.connect(self.db_path)
5295
5305
 
5296
- c = conn.cursor()
5297
-
5298
- c.execute("""
5299
- SELECT agent_id FROM agent_attn_storage
5300
- WHERE memory_name = ? AND is_active = 1
5301
- """, (memory_name,))
5302
-
5303
- result = c.fetchone()
5304
- conn.close()
5306
+ if _RUST_MODULE_AVAILABLE:
5307
+ try:
5308
+ agent_data = wc.load_agent_id(self.db_path, memory_name)
5309
+ print('[+] Got Agent ID Data from Database!')
5310
+ except Exception as e:
5311
+ print(f'[!] Cant load agent ID data from DB: {e}')
5312
+ return None
5313
+ else:
5314
+ c = conn.cursor()
5315
+
5316
+ c.execute("""
5317
+ SELECT agent_id FROM agent_attn_storage
5318
+ WHERE memory_name = ? AND is_active = 1
5319
+ """, (memory_name,))
5320
+
5321
+ result = c.fetchone()
5322
+ conn.close()
5305
5323
 
5306
- print(f'[+] Retrieved Agent ID of {memory_name}: result: {result}')
5307
-
5308
- if result:
5309
- return json.loads(result[0])
5324
+ print(f'[+] Retrieved Agent ID of {memory_name}: result: {result}')
5325
+
5326
+ if result:
5327
+ return json.loads(result[0])
5310
5328
  except Exception as e:
5311
- print(f'[-] Error handling ID: {e}')
5329
+ print(f'[-] Error loading ID from database: {e}')
5312
5330
 
5313
5331
  return None
5314
5332
 
5333
+
5315
5334
  def memory_exists(self, memory_name, type=None):
5316
5335
 
5317
5336
  conn = None
@@ -5321,55 +5340,62 @@ class ModelStorage:
5321
5340
  conn = sqlite3.connect(db_path)
5322
5341
  except:
5323
5342
  conn = sqlite3.connect(self.db_path)
5324
-
5325
5343
 
5326
- if type == 'Transformer':
5327
- c = conn.cursor()
5328
-
5329
- c.execute("""
5330
- SELECT 1 FROM model_attn_storage
5331
- WHERE memory_name = ? AND is_active = 1
5332
- LIMIT 1
5333
- """, (memory_name,))
5334
-
5335
- result = c.fetchone()
5336
- exists = result is not None
5337
- print(f"|| Retrieved Attention: {memory_name}")
5344
+ if _RUST_MODULE_AVAILABLE:
5345
+ try:
5346
+ exists = wc.verify_memory_exist(self.db_path, memory_name, type)
5347
+ print(f'[=] Memory exist: {exists}')
5348
+ return exists
5349
+ except:
5350
+ pass
5351
+ else:
5352
+ if type == 'Transformer':
5353
+ c = conn.cursor()
5354
+
5355
+ c.execute("""
5356
+ SELECT 1 FROM model_attn_storage
5357
+ WHERE memory_name = ? AND is_active = 1
5358
+ LIMIT 1
5359
+ """, (memory_name,))
5360
+
5361
+ result = c.fetchone()
5362
+ exists = result is not None
5363
+ print(f"|| Retrieved Attention: {memory_name}")
5338
5364
 
5339
- elif type == 'Peer':
5340
- c = conn.cursor()
5341
-
5342
- c.execute("""
5343
- SELECT 1 FROM agent_attn_storage
5344
- WHERE memory_name = ? AND is_active = 1
5345
- LIMIT 1
5346
- """, (memory_name,))
5347
-
5348
- result = c.fetchone()
5349
- exists = result is not None
5350
- print(f"|| Retrieved Peer Memory: {memory_name}")
5365
+ elif type == 'Peer':
5366
+ c = conn.cursor()
5367
+
5368
+ c.execute("""
5369
+ SELECT 1 FROM agent_attn_storage
5370
+ WHERE memory_name = ? AND is_active = 1
5371
+ LIMIT 1
5372
+ """, (memory_name,))
5373
+
5374
+ result = c.fetchone()
5375
+ exists = result is not None
5376
+ print(f"|| Retrieved Peer Memory: {memory_name}")
5351
5377
 
5352
- else:
5353
- c = conn.cursor()
5378
+ else:
5379
+ c = conn.cursor()
5354
5380
 
5355
- c.execute("""
5356
- SELECT 1 FROM model_storage
5357
- WHERE memory_name = ? AND is_active = 1
5358
- LIMIT 1
5359
- """, (memory_name,))
5360
-
5361
- result = c.fetchone()
5362
- exists = result is not None
5363
- print(f"|| Retrieved Memory: {memory_name}")
5381
+ c.execute("""
5382
+ SELECT 1 FROM model_storage
5383
+ WHERE memory_name = ? AND is_active = 1
5384
+ LIMIT 1
5385
+ """, (memory_name,))
5386
+
5387
+ result = c.fetchone()
5388
+ exists = result is not None
5389
+ print(f"|| Retrieved Memory: {memory_name}")
5364
5390
 
5365
- return exists
5391
+ return exists
5366
5392
 
5367
5393
  except sqlite3.OperationalError as e:
5368
- print(f"Database error: {e}")
5394
+ print(f"[!] Database error: {e}")
5369
5395
  return False
5370
5396
 
5371
5397
  except Exception as e:
5372
- print(f"Unexpected error: {e}")
5398
+ print(f"[!] Unexpected error in handling memory: {e}")
5373
5399
  return False
5374
5400
  finally:
5375
5401
  if conn:
@@ -6719,38 +6745,43 @@ class AgentDistributedInference:
6719
6745
  async def request_advanced_prediction_async(self, manager: Any, use_transformer: bool=False, agent_id: str=None, test_titles: List[tuple]=None, label_map: Dict[str, int]=None, rules: List[tuple]=None, X: np.ndarray=None, y: np.ndarray=None, timeout: float = 30.0, callback: Optional[Callable] = None):
6720
6746
  # Asynchronous prediction request
6721
6747
  # Local bypass - NO QUEUE
6722
- if agent_id == 'local':
6723
- logger.info(f"[=] Local request - direct execution")
6724
- # Run sync prediction in thread pool
6725
- result = await asyncio.to_thread(manager.advanced_prediction_method, test_titles, label_map, rules, X=X, y=y, show_proba=True, use_transformer=use_transformer)
6726
- logger.info(f"[=] Local result: {result[1]} || confidence: {result[2]}")
6727
- return result
6728
-
6729
- msg_id = str(uuid.uuid4())
6730
- message = Message(
6731
- id=msg_id,
6732
- type='predict_request',
6733
- sender=self.temporary_agent_id,
6734
- recipient=agent_id,
6735
- payload={'test_titles': test_titles, 'label_map': label_map, 'rules': rules, 'X':X, 'y':y},
6736
- timestamp=datetime.now(),
6737
- timeout=timeout,
6738
- callback=callback,
6739
- max_retries=self.max_retries
6740
- )
6748
+ try:
6749
+ if agent_id == 'local':
6750
+ logger.info(f"[=] Local request - direct execution")
6751
+ # Run sync prediction in thread pool
6752
+ result = await asyncio.to_thread(manager.advanced_prediction_method, test_titles, label_map, rules, X=X, y=y, show_proba=True, use_transformer=use_transformer)
6753
+ logger.info(f"[=] Local result: {result[1]} || confidence: {result[2]}")
6754
+ return result
6755
+
6756
+ msg_id = str(uuid.uuid4())
6757
+ message = Message(
6758
+ id=msg_id,
6759
+ type='predict_request',
6760
+ sender=self.temporary_agent_id,
6761
+ recipient=agent_id,
6762
+ payload={'test_titles': test_titles, 'label_map': label_map, 'rules': rules, 'X':X, 'y':y},
6763
+ timestamp=datetime.now(),
6764
+ timeout=timeout,
6765
+ callback=callback,
6766
+ max_retries=self.max_retries
6767
+ )
6741
6768
 
6742
- logger.info(f"[=] Remote request - publishing to queue")
6743
- response = await self.message_queue.publish(message)
6744
- logger.info(f"[=] Queue response type: {type(response)}")
6769
+ logger.info(f"[=] Remote request - publishing to queue")
6770
+ response = await self.message_queue.publish(message)
6771
+ logger.info(f"[=] Queue response type: {type(response)}")
6745
6772
 
6746
- # Extract prediction from response if needed
6747
- if isinstance(response, dict) and 'prediction' in response:
6773
+ # Extract prediction from response if needed
6774
+ if isinstance(response, dict) and 'prediction' in response:
6775
+ return response
6776
+ elif isinstance(response, dict) and 'result' in response:
6777
+ return response['result']
6778
+ else:
6779
+ return response
6780
+ except Exception as e:
6781
+ print(f'[!] Cannot request advanced prediction async: {e}')
6782
+ response = {'prediction': None, 'result': None}
6748
6783
  return response
6749
- elif isinstance(response, dict) and 'result' in response:
6750
- return response['result']
6751
- else:
6752
- return response
6753
-
6784
+
6754
6785
 
6755
6786
 
6756
6787
  def request_prediction_direct(self, agent_id, text, timeout=5):
@@ -6819,7 +6850,6 @@ class AgentDistributedInference:
6819
6850
 
6820
6851
  def request_prediction_batch(self, agent_id: str, texts, timeout: float = 30.0) -> List[Any]:
6821
6852
  # Batch async prediction requests (parallelized)
6822
- import concurrent.futures
6823
6853
 
6824
6854
  with concurrent.futures.ThreadPoolExecutor(max_workers=len(texts)) as executor:
6825
6855
  futures = [
@@ -8966,7 +8996,7 @@ class IntegratedPipeline:
8966
8996
  if isinstance(memory, dict):
8967
8997
  for key, value in list(memory.items()):
8968
8998
  is_val_corrupted, reason, _ = self.is_memory_corrupted(value)
8969
- if is_val_corrupted:
8999
+ if is_val_corrupted and not key.startswith('supervised'):
8970
9000
  print(f'[!] Removing corrupted entry {key}: {reason}')
8971
9001
  del memory[key]
8972
9002
 
@@ -10675,6 +10705,8 @@ class AccurateAnswerCache:
10675
10705
  self.pipeline = pipeline
10676
10706
  self.similarity_threshold = similarity_threshold
10677
10707
  self.max_size = max_size
10708
+ self.max_threshold = 0.7
10709
+
10678
10710
  self.cache = {}
10679
10711
  self.exact_hash_index = {} # O(1) exact match lookup
10680
10712
 
@@ -10709,8 +10741,19 @@ class AccurateAnswerCache:
10709
10741
  print(f'[💎] Verified answer cached: {prediction} (source={source})')
10710
10742
 
10711
10743
  def lookup(self, x_mlp, input_ids=None):
10744
+ confidence_threshold = self.pipeline.confidence_threshold
10745
+ if confidence_threshold <= 0.5:
10746
+ confidence_treshold = self.max_threshold
10747
+
10712
10748
  if not self.cache:
10713
10749
  return None
10750
+
10751
+ AME = self.pipeline.AME_Encoder(x_mlp)
10752
+ anisotropy = self.pipeline.anisotropy_measurement(x_mlp)
10753
+ if np.isinf(AME) or np.isnan(AME):
10754
+ AME = (1.0 - self.pipeline.confidence_threshold)
10755
+ if np.isinf(anisotropy) or np.isnan(anisotropy):
10756
+ anisotropy = 0.15
10714
10757
 
10715
10758
  # FAST PATH — O(1) hash lookup
10716
10759
  if input_ids is not None:
@@ -10746,10 +10789,26 @@ class AccurateAnswerCache:
10746
10789
  if min_len > 0:
10747
10790
  seq_sim = float(np.mean(ids_a[:min_len] == ids_b[:min_len]))
10748
10791
 
10749
- combined_sim = mlp_sim * 0.7 + seq_sim * 0.3
10750
- if combined_sim > best_combined_sim:
10751
- best_combined_sim = combined_sim
10752
- best_match = entry
10792
+ combined_env_sim = mlp_sim * confidence_threshold + seq_sim * anisotropy
10793
+ deterministic_modelling_sim = mlp_sim * 0.7 + seq_sim * AME
10794
+
10795
+ combinatorial_absolute_factor = (
10796
+ deterministic_modelling_sim > best_combined_sim and
10797
+ AME < 0.5 and
10798
+ entry['confidence'] > 0.5
10799
+ )
10800
+ dynamic_environmental_factor = (
10801
+ combined_env_sim > best_combined_sim and
10802
+ AME > 0.5 and
10803
+ entry['confidence'] > confidence_threshold
10804
+ )
10805
+
10806
+ if combinatorial_absolute_factor:
10807
+ best_combined_sim = deterministic_modelling_sim
10808
+ else:
10809
+ best_combined_sim = combined_env_sim
10810
+
10811
+ best_match = entry
10753
10812
 
10754
10813
  if best_match and best_combined_sim >= self.similarity_threshold:
10755
10814
  best_match['hit_count'] += 1
@@ -10786,6 +10845,8 @@ class AccurateAnswerCache:
10786
10845
  self.exact_hash_index.pop(entry['ids_hash'], None)
10787
10846
  del self.cache[lru_key]
10788
10847
 
10848
+
10849
+
10789
10850
 
10790
10851
  class RateLimiter:
10791
10852
  # Token bucket rate limiter