dodle commited on
Commit
86c188f
·
verified ·
1 Parent(s): 4892b12

Upload folder using huggingface_hub

Browse files
README.md CHANGED
@@ -54,9 +54,9 @@ This writes `noe-model.dodl` and `noe-model.F32.gguf` in the current directory,
54
 
55
  Each step reads the input and current state, chooses an action, runs it, and updates the model. Rules and eligible goals can take priority. A model trained with `--train-actions` can use its network to choose among `rest`, `explore`, `learn`, and `observe`. An untrained model uses its existing rules and behavior instead. Steps update memory, rules, and the outcome self-model, but do not train network weights online.
56
 
57
- The engine records a workspace snapshot for each step. This includes the input, active goal, recalled episodes, candidate predictions, expected outcome, actual outcome, and `decisionSource`. Episodes are selected by case- and punctuation-normalized word overlap and recency, not semantic understanding.
58
 
59
- When a goal is unmet, previously observed action effects can help guide the choice. Explicit non-`observe` rules still take priority, and unknown actions fall back to the existing policy. Uncertainty values are simple heuristics based on observation counts and word overlap, not calibrated probabilities. Reply providers receive the recalled episodes and pre-action workspace; their analysis does not control actions.
60
 
61
  These are software traces and decision heuristics, not evidence of subjective experience. Values such as `novelty`, `stress`, `recovery`, and `arousal` are bounded software signals. They are not biological measurements, and the model does not simulate quantum effects or establish consciousness.
62
 
@@ -129,7 +129,41 @@ print(report["test_scenarios"]["prediction"]["success_rate"])
129
 
130
  This example is intentionally small and synthetic; it does not establish generalization. Supply larger, representative demonstrations and independently designed validation and held-out tasks, including conflicting goals. To prevent source or task leakage, add a non-empty `group` string to every training episode, validation episode, and test scenario. Groups may repeat within a split but must be disjoint across splits. Grouping is optional for compatibility; the caller must select meaningful group identities. The trainer also rejects exact duplicate scenarios across the sets, but cannot detect subtler leakage.
131
 
132
- Demonstration policies use the `action-context-v2` feature schema: state, compact text features, the active goal's state deficits, and relevance scores for recalled actions. Existing `action-state-text-v1` models retain their original encoding. Neither schema represents the full workspace; the runtime handles workspace-based planning separately.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
 
134
  ### Safety rules
135
 
@@ -202,6 +236,37 @@ with open("my-model.dodl", "wb") as model_file:
202
 
203
  The provider writes the reply and may return a short analysis. The local engine still chooses and runs the action. `respond()` updates the engine just like `step()`, so export the model if you want to keep the new state. Load `my-model.dodl` in a later run to continue from it. Provider request failures raise `LLMProviderError`.
204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  ## Connect a biocomputation service
206
 
207
  `BiocomputationProvider` is a client for a separately deployed gateway. Noesis does not perform biological computation, operate bacteria, or control lab equipment. Connect the gateway to an existing, approved platform; do not expose platform controls directly to model-generated text.
 
54
 
55
  Each step reads the input and current state, chooses an action, runs it, and updates the model. Rules and eligible goals can take priority. A model trained with `--train-actions` can use its network to choose among `rest`, `explore`, `learn`, and `observe`. An untrained model uses its existing rules and behavior instead. Steps update memory, rules, and the outcome self-model, but do not train network weights online.
56
 
57
+ The engine records a workspace snapshot for each step. This includes the input, active goal, recalled episodes, candidate predictions, expected outcome, actual outcome, and `decisionSource`. Episodes are selected by case- and punctuation-normalized word overlap, with rarer query words weighted more heavily and recency used to break ties. This is lexical matching, not semantic understanding.
58
 
59
+ When a goal is unmet, previously observed action effects can help guide the choice. Explicit non-`observe` rules still take priority, and unknown actions fall back to the existing policy. Uncertainty values are simple heuristics based on observation counts and word overlap, not calibrated probabilities. Provider analysis does not control actions.
60
 
61
  These are software traces and decision heuristics, not evidence of subjective experience. Values such as `novelty`, `stress`, `recovery`, and `arousal` are bounded software signals. They are not biological measurements, and the model does not simulate quantum effects or establish consciousness.
62
 
 
129
 
130
  This example is intentionally small and synthetic; it does not establish generalization. Supply larger, representative demonstrations and independently designed validation and held-out tasks, including conflicting goals. To prevent source or task leakage, add a non-empty `group` string to every training episode, validation episode, and test scenario. Groups may repeat within a split but must be disjoint across splits. Grouping is optional for compatibility; the caller must select meaningful group identities. The trainer also rejects exact duplicate scenarios across the sets, but cannot detect subtler leakage.
131
 
132
+ Demonstration policies use the `action-context-v2` feature schema: state, compact text features, the active goal's state deficits, and relevance scores for recalled actions. Existing `action-state-text-v1` models retain their original encoding. Neither schema represents the full workspace; the runtime handles workspace-based planning separately. When test scenarios are supplied, `report["test_comparison"]` summarizes each policy's success-rate difference from the rule baseline and its override rate. This comparison still measures only the simulation.
133
+
134
+ ### Evaluate application outcomes
135
+
136
+ Record independently assessed outcomes from representative tasks in the surrounding application. Compare methods on equivalent tasks using the same success criteria and an evaluation design that avoids order and selection bias. `task_id` must identify the same task across methods; each method/task pair may appear once.
137
+
138
+ ```python
139
+ from me import evaluate_task_outcomes
140
+
141
+ results = evaluate_task_outcomes([
142
+ {"task_id": "task-1", "method": "policy", "success": True},
143
+ {"task_id": "task-1", "method": "rule_baseline", "success": False},
144
+ ])
145
+ print(results["methods"], results["vs_rule_baseline"])
146
+ ```
147
+
148
+ The report includes each method's task count and success rate, plus the paired task count and success-rate difference against `rule_baseline`. Unpaired tasks contribute to their method's overall rate but not the paired comparison. These summaries do not establish statistical significance or eliminate bias; collect enough independently labeled results before deciding whether to deploy a trained policy.
149
+
150
+ ### Evaluate memory retrieval
151
+
152
+ Use representative queries and independently labeled relevant episode IDs to measure retrieval before changing its ranking or adding semantic search:
153
+
154
+ ```python
155
+ from me import MemoryStore, evaluate_memory_retrieval
156
+
157
+ memory = MemoryStore()
158
+ memory.add({"input": {"value": "billing question"}, "action": "observe"})
159
+ results = evaluate_memory_retrieval(memory, [{
160
+ "input": {"value": "billing question"},
161
+ "relevant_ids": [memory.items[0]["id"]],
162
+ }], count=3)
163
+ print(results["recall"], results["mrr"])
164
+ ```
165
+
166
+ The report gives mean recall at `count` and mean reciprocal rank. The example only illustrates the API; use held-out queries including paraphrases and irrelevant overlaps to assess retrieval quality.
167
 
168
  ### Safety rules
169
 
 
236
 
237
  The provider writes the reply and may return a short analysis. The local engine still chooses and runs the action. `respond()` updates the engine just like `step()`, so export the model if you want to keep the new state. Load `my-model.dodl` in a later run to continue from it. Provider request failures raise `LLMProviderError`.
238
 
239
+ By default, `respond()` sends the current input and the numeric energy, curiosity, confidence, and stability signals, but no stored memory or workspace. The current input can itself contain sensitive information. To redact it or explicitly include selected context, pass a trusted `context_filter` callable. It receives copies of `user_input`, full `state` (including the pre-action workspace), and recalled `memories`, and must return a dictionary with exactly those three keys:
240
+
241
+ ```python
242
+ def select_context(context):
243
+ return {
244
+ "user_input": {"type": "user_input", "value": "[redacted]"},
245
+ "state": {},
246
+ "memories": [],
247
+ }
248
+
249
+ result = engine.respond({"type": "user_input", "value": "private"},
250
+ LLMProvider(), context_filter=select_context)
251
+ ```
252
+
253
+ This changes what the provider sees, not the input processed locally or stored in the model. The filter must redact every sensitive field it chooses to include. Calling `LLMProvider.generate()` directly sends the context supplied by its caller.
254
+
255
+ Retries are disabled by default. `LLMProvider(max_retries=1)` opts into at most one retry (maximum two are allowed) for HTTP 429 or 503, with bounded backoff. Numeric `Retry-After` values up to two seconds are honored; longer, malformed, or HTTP-date values are not retried. Other HTTP failures and transport errors are not retried. Retrying generation can incur additional cost and extend total latency; the timeout applies per request.
256
+
257
+ ### Observability
258
+
259
+ Pass an `event_callback` to `AIEngine` to receive content-free provider and local decision events:
260
+
261
+ ```python
262
+ events = []
263
+ engine = AIEngine(event_callback=events.append)
264
+ engine.step({"type": "user_input", "value": "hello"})
265
+ print(events[-1])
266
+ ```
267
+
268
+ Provider events report success or error and elapsed seconds, without inputs, replies, or exception messages. Decision events report the decision source, action, and local execution success. Local success is not an independently measured application outcome. Callback exceptions are ignored so a telemetry failure does not alter model behavior; the callback is responsible for exporting or storing events safely.
269
+
270
  ## Connect a biocomputation service
271
 
272
  `BiocomputationProvider` is a client for a separately deployed gateway. Noesis does not perform biological computation, operate bacteria, or control lab equipment. Connect the gateway to an existing, approved platform; do not expose platform controls directly to model-generated text.
me.py CHANGED
@@ -657,17 +657,26 @@ class MemoryStore:
657
  tokens = set(re.findall(r"\w+", text.casefold())) if isinstance(text, str) else set()
658
  if not tokens:
659
  return []
660
- matches = []
661
  for index, item in enumerate(self.items):
662
  stored_input = item.get("input")
663
  stored_text = stored_input.get("value") if isinstance(stored_input, dict) else None
664
  if not isinstance(stored_text, str):
665
  continue
666
  stored_tokens = set(re.findall(r"\w+", stored_text.casefold()))
667
- overlap = len(tokens & stored_tokens)
 
 
 
 
 
 
 
668
  if not overlap:
669
  continue
670
- relevance = overlap / len(tokens | stored_tokens)
 
 
671
  recency = (index + 1) / max(len(self.items), 1)
672
  matches.append((relevance, recency, item))
673
  matches.sort(key=lambda match: (match[0], match[1]), reverse=True)
@@ -681,6 +690,31 @@ class MemoryStore:
681
  self.items.clear()
682
 
683
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
684
  def _js_number(value):
685
  if value is None:
686
  return 0
@@ -1045,10 +1079,13 @@ def create_gguf_model_file(path, model):
1045
 
1046
 
1047
  class AIEngine:
1048
- def __init__(self, model=None, provider=None):
 
 
1049
  self.model = model if model is not None else create_model()
1050
  validate_model(self.model)
1051
  self.provider = provider
 
1052
  self.random = Random(self.model["randomSeed"])
1053
  stored_network = self.model["network"]
1054
  self.network = TinyNetwork(self.random)
@@ -1073,6 +1110,13 @@ class AIEngine:
1073
  self.workspace = self.state.setdefault("workspace", create_initial_workspace())
1074
  self.goals = self.model["goals"]
1075
 
 
 
 
 
 
 
 
1076
  def encode_input(self, input_value, workspace=None):
1077
  vector = array("f", [0]) * self.network.input_size
1078
  contextual = self.model["network"].get("featureSchema") == "action-context-v2"
@@ -1424,6 +1468,12 @@ class AIEngine:
1424
  }
1425
  self.learn(evaluation, input_vector)
1426
  self.sync_model()
 
 
 
 
 
 
1427
  return copy.deepcopy({
1428
  "perception": perception,
1429
  "interpretation": interpretation,
@@ -1435,22 +1485,36 @@ class AIEngine:
1435
  "state": self.state,
1436
  })
1437
 
1438
- def respond(self, input_value, provider=None):
1439
  """Generate a provider reply, then run one local engine step."""
1440
  active_provider = provider or self.provider or LLMProvider()
1441
  workspace = self.open_workspace(self.observe(input_value), persist=False)
1442
- provider_state = copy.deepcopy(self.state)
1443
- provider_state["workspace"] = copy.deepcopy(workspace)
1444
  provider_context = {
1445
- "user_input": input_value,
1446
- "state": provider_state,
1447
- "memories": [match["episode"] for match in workspace["memories"]],
1448
  }
1449
- if hasattr(active_provider, "generate_with_analysis"):
1450
- provider_response = active_provider.generate_with_analysis(**provider_context)
1451
- else:
1452
- provider_response = active_provider.generate(**provider_context)
1453
- normalized = normalize_provider_response(provider_response)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1454
  result = self.step(input_value, provider_analysis=normalized["analysis"], workspace=workspace)
1455
  result["reply"] = normalized["reply"]
1456
  return result
@@ -1502,6 +1566,39 @@ class AIEngine:
1502
  return self.behavior.program
1503
 
1504
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1505
  def evaluate_action_scenarios(model, scenarios):
1506
  """Compare prediction-informed, policy-only, and threshold-baseline behavior."""
1507
  if not isinstance(model, dict):
@@ -1721,6 +1818,15 @@ def train_action_model_from_episodes(path, training_episodes, validation_episode
1721
  report = {"validation": _action_policy_metrics(_network_from_model(model), validation)}
1722
  if test_scenarios is not None:
1723
  report["test_scenarios"] = evaluate_action_scenarios(model, test_scenarios)
 
 
 
 
 
 
 
 
 
1724
  _write_model_artifacts(((path, serialize_model(model)), (gguf_path, serialize_gguf_model(model))))
1725
  return model, report
1726
 
 
657
  tokens = set(re.findall(r"\w+", text.casefold())) if isinstance(text, str) else set()
658
  if not tokens:
659
  return []
660
+ documents = []
661
  for index, item in enumerate(self.items):
662
  stored_input = item.get("input")
663
  stored_text = stored_input.get("value") if isinstance(stored_input, dict) else None
664
  if not isinstance(stored_text, str):
665
  continue
666
  stored_tokens = set(re.findall(r"\w+", stored_text.casefold()))
667
+ documents.append((index, item, stored_tokens))
668
+ weights = {
669
+ token: 1 + math.log((len(documents) + 1) / (1 + sum(token in document for _, _, document in documents)))
670
+ for token in tokens
671
+ }
672
+ matches = []
673
+ for index, item, stored_tokens in documents:
674
+ overlap = tokens & stored_tokens
675
  if not overlap:
676
  continue
677
+ relevance = sum(weights[token] for token in overlap) / (
678
+ sum(weights.values()) + len(stored_tokens - tokens)
679
+ )
680
  recency = (index + 1) / max(len(self.items), 1)
681
  matches.append((relevance, recency, item))
682
  matches.sort(key=lambda match: (match[0], match[1]), reverse=True)
 
690
  self.items.clear()
691
 
692
 
693
+ def evaluate_memory_retrieval(memory, queries, count=3):
694
+ """Score labeled retrieval queries against an existing memory store."""
695
+ if not isinstance(memory, MemoryStore):
696
+ raise ValueError("memory must be a MemoryStore.")
697
+ if isinstance(count, bool) or not isinstance(count, int) or count < 1:
698
+ raise ValueError("count must be a positive integer.")
699
+ if not isinstance(queries, list) or not queries:
700
+ raise ValueError("queries must be a non-empty list.")
701
+ recall = 0.0
702
+ reciprocal_rank = 0.0
703
+ for query in queries:
704
+ if not isinstance(query, dict) or not isinstance(query.get("relevant_ids"), list) or not query["relevant_ids"]:
705
+ raise ValueError("Each query must have a non-empty relevant_ids list.")
706
+ relevant = query["relevant_ids"]
707
+ if any(not isinstance(identifier, str) or not identifier for identifier in relevant) or len(set(relevant)) != len(relevant):
708
+ raise ValueError("Relevant IDs must be distinct non-empty strings.")
709
+ known_ids = {item.get("id") for item in memory.items}
710
+ if not set(relevant) <= known_ids:
711
+ raise ValueError("Relevant IDs must exist in memory.")
712
+ found = [match["episode"]["id"] for match in memory.recall(query.get("input"), count)]
713
+ recall += len(set(found) & set(relevant)) / len(relevant)
714
+ reciprocal_rank += next((1 / rank for rank, identifier in enumerate(found, 1) if identifier in relevant), 0)
715
+ return {"queries": len(queries), "count": count, "recall": recall / len(queries), "mrr": reciprocal_rank / len(queries)}
716
+
717
+
718
  def _js_number(value):
719
  if value is None:
720
  return 0
 
1079
 
1080
 
1081
  class AIEngine:
1082
+ def __init__(self, model=None, provider=None, *, event_callback=None):
1083
+ if event_callback is not None and not callable(event_callback):
1084
+ raise ValueError("event_callback must be callable.")
1085
  self.model = model if model is not None else create_model()
1086
  validate_model(self.model)
1087
  self.provider = provider
1088
+ self.event_callback = event_callback
1089
  self.random = Random(self.model["randomSeed"])
1090
  stored_network = self.model["network"]
1091
  self.network = TinyNetwork(self.random)
 
1110
  self.workspace = self.state.setdefault("workspace", create_initial_workspace())
1111
  self.goals = self.model["goals"]
1112
 
1113
+ def _emit_event(self, event):
1114
+ if self.event_callback is not None:
1115
+ try:
1116
+ self.event_callback(event)
1117
+ except Exception:
1118
+ pass
1119
+
1120
  def encode_input(self, input_value, workspace=None):
1121
  vector = array("f", [0]) * self.network.input_size
1122
  contextual = self.model["network"].get("featureSchema") == "action-context-v2"
 
1468
  }
1469
  self.learn(evaluation, input_vector)
1470
  self.sync_model()
1471
+ self._emit_event({
1472
+ "event": "decision",
1473
+ "source": workspace.get("decisionSource") if workspace.get("decisionSource") in ("safety_rule", "rule", "goal", "prediction", "policy", "behavior") else "unknown",
1474
+ "action": action["type"] if action["type"] in ACTION_LABELS else "other",
1475
+ "success": bool(result.get("success")),
1476
+ })
1477
  return copy.deepcopy({
1478
  "perception": perception,
1479
  "interpretation": interpretation,
 
1485
  "state": self.state,
1486
  })
1487
 
1488
+ def respond(self, input_value, provider=None, *, context_filter=None):
1489
  """Generate a provider reply, then run one local engine step."""
1490
  active_provider = provider or self.provider or LLMProvider()
1491
  workspace = self.open_workspace(self.observe(input_value), persist=False)
 
 
1492
  provider_context = {
1493
+ "user_input": copy.deepcopy(input_value),
1494
+ "state": {key: self.state[key] for key in ("energy", "curiosity", "confidence", "stability")},
1495
+ "memories": [],
1496
  }
1497
+ if context_filter is not None:
1498
+ full_state = copy.deepcopy(self.state)
1499
+ full_state["workspace"] = copy.deepcopy(workspace)
1500
+ provider_context = context_filter({
1501
+ "user_input": copy.deepcopy(input_value),
1502
+ "state": full_state,
1503
+ "memories": [copy.deepcopy(match["episode"]) for match in workspace["memories"]],
1504
+ })
1505
+ if not isinstance(provider_context, dict) or set(provider_context) != {"user_input", "state", "memories"}:
1506
+ raise ValueError("context_filter must return user_input, state, and memories.")
1507
+ started = time.monotonic()
1508
+ try:
1509
+ if hasattr(active_provider, "generate_with_analysis"):
1510
+ provider_response = active_provider.generate_with_analysis(**provider_context)
1511
+ else:
1512
+ provider_response = active_provider.generate(**provider_context)
1513
+ normalized = normalize_provider_response(provider_response)
1514
+ except Exception:
1515
+ self._emit_event({"event": "provider", "outcome": "error", "duration_seconds": time.monotonic() - started})
1516
+ raise
1517
+ self._emit_event({"event": "provider", "outcome": "success", "duration_seconds": time.monotonic() - started})
1518
  result = self.step(input_value, provider_analysis=normalized["analysis"], workspace=workspace)
1519
  result["reply"] = normalized["reply"]
1520
  return result
 
1566
  return self.behavior.program
1567
 
1568
 
1569
+ def evaluate_task_outcomes(records):
1570
+ """Summarize independently measured application outcomes by method and task."""
1571
+ if not isinstance(records, list) or not records:
1572
+ raise ValueError("records must be a non-empty list.")
1573
+ methods = {}
1574
+ for record in records:
1575
+ if not isinstance(record, dict):
1576
+ raise ValueError("Each outcome must be an object.")
1577
+ task_id, method, success = (record.get(key) for key in ("task_id", "method", "success"))
1578
+ if not isinstance(task_id, str) or not task_id.strip() or not isinstance(method, str) or not method.strip() or not isinstance(success, bool):
1579
+ raise ValueError("Each outcome needs a task_id, method, and boolean success.")
1580
+ tasks = methods.setdefault(method, {})
1581
+ if task_id in tasks:
1582
+ raise ValueError("Each method and task_id pair must be unique.")
1583
+ tasks[task_id] = success
1584
+ summaries = {
1585
+ method: {"tasks": len(tasks), "success_rate": sum(tasks.values()) / len(tasks)}
1586
+ for method, tasks in methods.items()
1587
+ }
1588
+ comparisons = {}
1589
+ if "rule_baseline" in methods:
1590
+ baseline = methods["rule_baseline"]
1591
+ for method, tasks in methods.items():
1592
+ if method == "rule_baseline":
1593
+ continue
1594
+ shared = tasks.keys() & baseline.keys()
1595
+ comparisons[method] = {
1596
+ "paired_tasks": len(shared),
1597
+ "success_rate_difference": (sum(int(tasks[task]) - int(baseline[task]) for task in shared) / len(shared)) if shared else None,
1598
+ }
1599
+ return {"methods": summaries, "vs_rule_baseline": comparisons}
1600
+
1601
+
1602
  def evaluate_action_scenarios(model, scenarios):
1603
  """Compare prediction-informed, policy-only, and threshold-baseline behavior."""
1604
  if not isinstance(model, dict):
 
1818
  report = {"validation": _action_policy_metrics(_network_from_model(model), validation)}
1819
  if test_scenarios is not None:
1820
  report["test_scenarios"] = evaluate_action_scenarios(model, test_scenarios)
1821
+ results = report["test_scenarios"]
1822
+ report["test_comparison"] = {
1823
+ label: {
1824
+ "scenarios": len(results[label]["scenarios"]),
1825
+ "success_rate_difference": results[label]["success_rate"] - results["rule_baseline"]["success_rate"],
1826
+ "override_rate": results[label]["override_rate"],
1827
+ }
1828
+ for label in ("prediction", "policy")
1829
+ }
1830
  _write_model_artifacts(((path, serialize_model(model)), (gguf_path, serialize_gguf_model(model))))
1831
  return model, report
1832
 
model_providers.py CHANGED
@@ -2,6 +2,7 @@ import http.client
2
  import json
3
  import math
4
  import os
 
5
  import urllib.error
6
  import urllib.parse
7
  import urllib.request
@@ -436,7 +437,7 @@ class LLMProvider:
436
 
437
  MAX_PAYLOAD_SIZE = 1024 * 1024
438
 
439
- def __init__(self, provider=None, api_key=None, model=None, timeout=30, base_url=None):
440
  self.provider = (provider or os.environ.get("NOESIS_PROVIDER", "openai")).lower()
441
  if self.provider not in ("openai", "gemini", "openai-compatible"):
442
  raise ValueError("Provider must be 'openai', 'gemini', or 'openai-compatible'.")
@@ -470,6 +471,9 @@ class LLMProvider:
470
  if not math.isfinite(timeout) or timeout <= 0:
471
  raise ValueError("LLM timeout must be a positive finite number.")
472
  self.timeout = timeout
 
 
 
473
  self.base_url = (
474
  base_url
475
  or os.environ.get("NOESIS_BASE_URL")
@@ -552,39 +556,53 @@ class LLMProvider:
552
  headers={"Content-Type": "application/json", **headers},
553
  method="POST",
554
  )
555
- try:
556
- with urllib.request.urlopen(request, timeout=self.timeout) as response:
557
- response_headers = getattr(response, "headers", None)
558
- content_type = (
559
- response_headers.get("Content-Type")
560
- if response_headers is not None
561
- else None
562
- )
563
- if content_type is not None:
564
- media_type = content_type.split(";", 1)[0].strip().lower()
565
- if media_type != "application/json" and not media_type.endswith(
566
- "+json"
567
- ):
568
- raise LLMProviderError(
569
- "LLM API response must use a JSON content type."
570
- )
571
- response_data = response.read(self.MAX_PAYLOAD_SIZE + 1)
572
- except urllib.error.HTTPError as error:
573
- raise LLMProviderError(
574
- f"{self.provider} API request failed with HTTP {error.code}."
575
- ) from error
576
- except LLMProviderError:
577
- raise
578
- except (
579
- urllib.error.URLError,
580
- TimeoutError,
581
- OSError,
582
- http.client.HTTPException,
583
- ValueError,
584
- ) as error:
585
- raise LLMProviderError(
586
- f"{self.provider} API request failed ({type(error).__name__})."
587
- ) from error
 
 
 
 
 
 
 
 
 
 
 
 
 
 
588
  if len(response_data) > self.MAX_PAYLOAD_SIZE:
589
  raise LLMProviderError("LLM API response exceeds the 1 MiB limit.")
590
  try:
 
2
  import json
3
  import math
4
  import os
5
+ import time
6
  import urllib.error
7
  import urllib.parse
8
  import urllib.request
 
437
 
438
  MAX_PAYLOAD_SIZE = 1024 * 1024
439
 
440
+ def __init__(self, provider=None, api_key=None, model=None, timeout=30, base_url=None, *, max_retries=0):
441
  self.provider = (provider or os.environ.get("NOESIS_PROVIDER", "openai")).lower()
442
  if self.provider not in ("openai", "gemini", "openai-compatible"):
443
  raise ValueError("Provider must be 'openai', 'gemini', or 'openai-compatible'.")
 
471
  if not math.isfinite(timeout) or timeout <= 0:
472
  raise ValueError("LLM timeout must be a positive finite number.")
473
  self.timeout = timeout
474
+ if isinstance(max_retries, bool) or not isinstance(max_retries, int) or not 0 <= max_retries <= 2:
475
+ raise ValueError("max_retries must be an integer between 0 and 2.")
476
+ self.max_retries = max_retries
477
  self.base_url = (
478
  base_url
479
  or os.environ.get("NOESIS_BASE_URL")
 
556
  headers={"Content-Type": "application/json", **headers},
557
  method="POST",
558
  )
559
+ for attempt in range(self.max_retries + 1):
560
+ try:
561
+ with urllib.request.urlopen(request, timeout=self.timeout) as response:
562
+ response_headers = getattr(response, "headers", None)
563
+ content_type = (
564
+ response_headers.get("Content-Type")
565
+ if response_headers is not None
566
+ else None
567
+ )
568
+ if content_type is not None:
569
+ media_type = content_type.split(";", 1)[0].strip().lower()
570
+ if media_type != "application/json" and not media_type.endswith(
571
+ "+json"
572
+ ):
573
+ raise LLMProviderError(
574
+ "LLM API response must use a JSON content type."
575
+ )
576
+ response_data = response.read(self.MAX_PAYLOAD_SIZE + 1)
577
+ break
578
+ except urllib.error.HTTPError as error:
579
+ delay = 0.25 * (2 ** attempt)
580
+ retry_after = error.headers.get("Retry-After") if error.headers else None
581
+ if retry_after is not None:
582
+ try:
583
+ retry_delay = float(retry_after)
584
+ delay = max(delay, retry_delay) if math.isfinite(retry_delay) and retry_delay >= 0 else float("inf")
585
+ except (TypeError, ValueError):
586
+ delay = float("inf")
587
+ if error.code not in (429, 503) or attempt >= self.max_retries or not math.isfinite(delay) or delay > 2:
588
+ error.close()
589
+ raise LLMProviderError(
590
+ f"{self.provider} API request failed with HTTP {error.code}."
591
+ ) from error
592
+ error.close()
593
+ time.sleep(delay)
594
+ except LLMProviderError:
595
+ raise
596
+ except (
597
+ urllib.error.URLError,
598
+ TimeoutError,
599
+ OSError,
600
+ http.client.HTTPException,
601
+ ValueError,
602
+ ) as error:
603
+ raise LLMProviderError(
604
+ f"{self.provider} API request failed ({type(error).__name__})."
605
+ ) from error
606
  if len(response_data) > self.MAX_PAYLOAD_SIZE:
607
  raise LLMProviderError("LLM API response exceeds the 1 MiB limit.")
608
  try:
noe-model.F32.gguf CHANGED
Binary files a/noe-model.F32.gguf and b/noe-model.F32.gguf differ
 
noe-model.dodl CHANGED
Binary files a/noe-model.dodl and b/noe-model.dodl differ
 
noe-pixel-model.F32.gguf CHANGED
Binary files a/noe-pixel-model.F32.gguf and b/noe-pixel-model.F32.gguf differ
 
noe-pixel-model.dodl CHANGED
Binary files a/noe-pixel-model.dodl and b/noe-pixel-model.dodl differ