dsh-biocore 0.1.2 → 0.1.4
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.
- package/lib/index.js +170 -27
- package/package.json +1 -1
- package/python/biocore_runtime/pipeline.py +42 -0
- package/python/biocore_runtime/rerank.py +201 -0
- package/python/mindbase/__init__.py +18 -0
- package/python/mindbase/__main__.py +3 -0
- package/python/mindbase/actions.py +56 -0
- package/python/mindbase/active_inference.py +54 -0
- package/python/mindbase/addressing.py +69 -0
- package/python/mindbase/affect.py +86 -0
- package/python/mindbase/affective.py +111 -0
- package/python/mindbase/allostasis.py +28 -0
- package/python/mindbase/appraisal.py +101 -0
- package/python/mindbase/attachment.py +49 -0
- package/python/mindbase/attention.py +30 -0
- package/python/mindbase/autonomy.py +81 -0
- package/python/mindbase/autonomy_bench.py +251 -0
- package/python/mindbase/autonomy_evolve.py +342 -0
- package/python/mindbase/autonomy_loop.py +65 -0
- package/python/mindbase/autonomy_meta.py +91 -0
- package/python/mindbase/base_only.py +28 -0
- package/python/mindbase/benchmark.py +61 -0
- package/python/mindbase/bio_adaptation.py +274 -0
- package/python/mindbase/bio_noise.py +39 -0
- package/python/mindbase/bio_semantic.py +138 -0
- package/python/mindbase/bm25.py +46 -0
- package/python/mindbase/bootstrap.py +256 -0
- package/python/mindbase/bootstrap_real.py +231 -0
- package/python/mindbase/brain.py +178 -0
- package/python/mindbase/care.py +78 -0
- package/python/mindbase/chaos_search.py +79 -0
- package/python/mindbase/character_profile.py +33 -0
- package/python/mindbase/circadian.py +38 -0
- package/python/mindbase/circuit.py +235 -0
- package/python/mindbase/clock.py +53 -0
- package/python/mindbase/companion_runtime.py +366 -0
- package/python/mindbase/companion_train.py +126 -0
- package/python/mindbase/config.py +66 -0
- package/python/mindbase/connection_state.py +76 -0
- package/python/mindbase/connectome_prior.py +35 -0
- package/python/mindbase/connectome_world.py +158 -0
- package/python/mindbase/constructs.py +88 -0
- package/python/mindbase/context_builder.py +58 -0
- package/python/mindbase/critical.py +36 -0
- package/python/mindbase/criticality.py +123 -0
- package/python/mindbase/defaults.py +27 -0
- package/python/mindbase/demo.py +163 -0
- package/python/mindbase/diary.py +116 -0
- package/python/mindbase/diary_service.py +40 -0
- package/python/mindbase/digital_prior.py +37 -0
- package/python/mindbase/diversity.py +110 -0
- package/python/mindbase/drives.py +106 -0
- package/python/mindbase/embedding.py +132 -0
- package/python/mindbase/embedding_memory.py +74 -0
- package/python/mindbase/embodiment.py +83 -0
- package/python/mindbase/emotion_calibration.py +39 -0
- package/python/mindbase/emotion_calibrator.py +50 -0
- package/python/mindbase/emotion_core.py +113 -0
- package/python/mindbase/emotion_dynamics.py +104 -0
- package/python/mindbase/emotion_intent.py +164 -0
- package/python/mindbase/emotion_layer.py +200 -0
- package/python/mindbase/emotion_schema.py +92 -0
- package/python/mindbase/engine.py +781 -0
- package/python/mindbase/episode_log.py +90 -0
- package/python/mindbase/evaluation.py +493 -0
- package/python/mindbase/event_appraisal.py +84 -0
- package/python/mindbase/evolution.py +77 -0
- package/python/mindbase/evolve_offline.py +232 -0
- package/python/mindbase/experiments.py +358 -0
- package/python/mindbase/expression.py +54 -0
- package/python/mindbase/external_brain.py +157 -0
- package/python/mindbase/fly_mb.py +159 -0
- package/python/mindbase/fly_tasks.py +45 -0
- package/python/mindbase/forage.py +179 -0
- package/python/mindbase/goal_generator.py +98 -0
- package/python/mindbase/goals.py +153 -0
- package/python/mindbase/grid_world.py +123 -0
- package/python/mindbase/group_autonomy.py +92 -0
- package/python/mindbase/group_context.py +67 -0
- package/python/mindbase/homeostatic.py +71 -0
- package/python/mindbase/homeostatic_action.py +38 -0
- package/python/mindbase/human_standard.py +53 -0
- package/python/mindbase/identity_suite.py +50 -0
- package/python/mindbase/image_context.py +27 -0
- package/python/mindbase/impression.py +119 -0
- package/python/mindbase/initiative_quota.py +145 -0
- package/python/mindbase/insight.py +51 -0
- package/python/mindbase/intelligence_search.py +108 -0
- package/python/mindbase/intention.py +76 -0
- package/python/mindbase/interaction_log.py +30 -0
- package/python/mindbase/interoception.py +67 -0
- package/python/mindbase/invariants.py +53 -0
- package/python/mindbase/iteration.py +29 -0
- package/python/mindbase/layered_memory.py +170 -0
- package/python/mindbase/layers/__init__.py +18 -0
- package/python/mindbase/layers/l0_substrate.py +39 -0
- package/python/mindbase/layers/l1_homeostasis.py +6 -0
- package/python/mindbase/layers/l2_affect.py +6 -0
- package/python/mindbase/layers/l3_attention.py +6 -0
- package/python/mindbase/layers/l4_learning.py +17 -0
- package/python/mindbase/layers/l5_self_social.py +35 -0
- package/python/mindbase/layers/l6_expression.py +23 -0
- package/python/mindbase/layers/l7_evaluation.py +45 -0
- package/python/mindbase/learner.py +196 -0
- package/python/mindbase/lexicon.py +33 -0
- package/python/mindbase/life_state.py +169 -0
- package/python/mindbase/lifecycle.py +87 -0
- package/python/mindbase/liquid_readout.py +48 -0
- package/python/mindbase/llm_adapter.py +233 -0
- package/python/mindbase/llm_cache.py +77 -0
- package/python/mindbase/llm_gate.py +85 -0
- package/python/mindbase/llm_openai.py +130 -0
- package/python/mindbase/llm_setup.py +99 -0
- package/python/mindbase/longrun.py +83 -0
- package/python/mindbase/longterm_memory.py +606 -0
- package/python/mindbase/mb/__init__.py +14 -0
- package/python/mindbase/mb/apl.py +22 -0
- package/python/mindbase/mb/dan.py +14 -0
- package/python/mindbase/mb/habituation.py +27 -0
- package/python/mindbase/mb/kc.py +28 -0
- package/python/mindbase/mb/mbon.py +23 -0
- package/python/mindbase/mb/mushroom_body.py +116 -0
- package/python/mindbase/memory.py +201 -0
- package/python/mindbase/memory_framework.py +158 -0
- package/python/mindbase/memory_retriever.py +110 -0
- package/python/mindbase/memory_summarizer.py +177 -0
- package/python/mindbase/memory_task.py +32 -0
- package/python/mindbase/memory_trace.py +46 -0
- package/python/mindbase/meta.py +32 -0
- package/python/mindbase/motivation.py +31 -0
- package/python/mindbase/multi_session.py +19 -0
- package/python/mindbase/narrative.py +87 -0
- package/python/mindbase/needs.py +77 -0
- package/python/mindbase/neural.py +45 -0
- package/python/mindbase/neuron_models.py +134 -0
- package/python/mindbase/noise.py +309 -0
- package/python/mindbase/one_on_one.py +60 -0
- package/python/mindbase/online_iteration.py +63 -0
- package/python/mindbase/ostracism.py +35 -0
- package/python/mindbase/parallel_eval.py +60 -0
- package/python/mindbase/parallel_qd.py +64 -0
- package/python/mindbase/persona.py +221 -0
- package/python/mindbase/persona_ab.py +64 -0
- package/python/mindbase/persona_bridge.py +129 -0
- package/python/mindbase/persona_compile.py +34 -0
- package/python/mindbase/persona_dsh.py +120 -0
- package/python/mindbase/persona_learner.py +157 -0
- package/python/mindbase/physiology.py +197 -0
- package/python/mindbase/population_lifecycle.py +83 -0
- package/python/mindbase/preferences.py +50 -0
- package/python/mindbase/proactive_agent.py +274 -0
- package/python/mindbase/proactive_gate.py +53 -0
- package/python/mindbase/proactive_group.py +119 -0
- package/python/mindbase/proactive_policy.py +422 -0
- package/python/mindbase/proactive_profile.py +196 -0
- package/python/mindbase/proactive_timing.py +28 -0
- package/python/mindbase/pyramid_stages.py +61 -0
- package/python/mindbase/quantum.py +132 -0
- package/python/mindbase/quantum_chaos.py +98 -0
- package/python/mindbase/reflection.py +68 -0
- package/python/mindbase/regulation_posture.py +50 -0
- package/python/mindbase/relationship_session.py +431 -0
- package/python/mindbase/relationship_suite.py +45 -0
- package/python/mindbase/relationships.py +70 -0
- package/python/mindbase/replay.py +22 -0
- package/python/mindbase/reply_diversity.py +53 -0
- package/python/mindbase/reply_gate.py +52 -0
- package/python/mindbase/rerank.py +41 -0
- package/python/mindbase/rerank_local.py +46 -0
- package/python/mindbase/ripple.py +187 -0
- package/python/mindbase/robust_search.py +68 -0
- package/python/mindbase/runtime.py +113 -0
- package/python/mindbase/scoped_identity.py +116 -0
- package/python/mindbase/self_insight.py +51 -0
- package/python/mindbase/self_model.py +116 -0
- package/python/mindbase/selftest.py +118 -0
- package/python/mindbase/semantic_memory.py +108 -0
- package/python/mindbase/session_store.py +175 -0
- package/python/mindbase/session_window.py +31 -0
- package/python/mindbase/shadow_eval.py +42 -0
- package/python/mindbase/sim_env.py +86 -0
- package/python/mindbase/social.py +138 -0
- package/python/mindbase/social_constraint.py +141 -0
- package/python/mindbase/social_feedback.py +95 -0
- package/python/mindbase/social_norm.py +225 -0
- package/python/mindbase/spiking_reservoir.py +204 -0
- package/python/mindbase/spontaneity.py +40 -0
- package/python/mindbase/story_loop.py +203 -0
- package/python/mindbase/survival_gauntlet.py +128 -0
- package/python/mindbase/symbolic.py +170 -0
- package/python/mindbase/teacher.py +244 -0
- package/python/mindbase/theory.py +42 -0
- package/python/mindbase/theory_of_mind.py +98 -0
- package/python/mindbase/translation_layer.py +80 -0
- package/python/mindbase/turn_eval.py +52 -0
- package/python/mindbase/types.py +78 -0
- package/python/mindbase/uncertainty_field.py +61 -0
- package/python/mindbase/user_loop.py +45 -0
- package/python/mindbase/user_profile.py +73 -0
- package/python/mindbase/value_model.py +64 -0
- package/python/mindbase/values.py +102 -0
- package/python/mindbase/vector_store.py +78 -0
- package/python/mindbase/viability.py +41 -0
- package/python/mindbase/virtual_body.py +90 -0
- package/python/mindbase/will.py +60 -0
- package/python/mindbase/working_memory.py +32 -0
- package/python/mindbase/workspace.py +55 -0
- package/ui/panel.css +16 -5
- package/ui/panel.html +25 -1
- package/ui/panel.js +57 -15
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Symbolic expression evolution.
|
|
2
|
+
|
|
3
|
+
If mathematics itself must not be restricted to hand-picked equations, the
|
|
4
|
+
formula structure has to be searchable too. This is a small, safe symbolic
|
|
5
|
+
regression layer: expressions are trees over +, -, *, /, sin, cos, exp, tanh,
|
|
6
|
+
square and constants; mutation/crossover search minimizes MSE + complexity.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import math
|
|
11
|
+
import random
|
|
12
|
+
from typing import Callable, Dict, List, Sequence, Tuple
|
|
13
|
+
|
|
14
|
+
BINARY = ("+", "-", "*", "/")
|
|
15
|
+
UNARY = ("sin", "cos", "exp", "tanh", "square")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _rand_const(rng: random.Random) -> float:
|
|
19
|
+
return round(rng.uniform(-2.0, 2.0), 3)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def random_expr(rng: random.Random, variables: Sequence[str], depth: int = 3):
|
|
23
|
+
if depth <= 0 or rng.random() < 0.30:
|
|
24
|
+
if rng.random() < 0.55:
|
|
25
|
+
return rng.choice(list(variables))
|
|
26
|
+
return _rand_const(rng)
|
|
27
|
+
if rng.random() < 0.30:
|
|
28
|
+
return (rng.choice(UNARY), random_expr(rng, variables, depth - 1))
|
|
29
|
+
return (rng.choice(BINARY), random_expr(rng, variables, depth - 1),
|
|
30
|
+
random_expr(rng, variables, depth - 1))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def size(expr) -> int:
|
|
34
|
+
if isinstance(expr, (tuple, list)):
|
|
35
|
+
return 1 + sum(size(a) for a in expr[1:])
|
|
36
|
+
return 1
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def eval_expr(expr, env: Dict[str, float]) -> float:
|
|
40
|
+
if isinstance(expr, str):
|
|
41
|
+
return float(env.get(expr, 0.0))
|
|
42
|
+
if isinstance(expr, (int, float)):
|
|
43
|
+
return float(expr)
|
|
44
|
+
if isinstance(expr, list):
|
|
45
|
+
expr = tuple(expr)
|
|
46
|
+
op, args = expr[0], expr[1:]
|
|
47
|
+
vals = [eval_expr(a, env) for a in args]
|
|
48
|
+
if op == "+":
|
|
49
|
+
return vals[0] + vals[1]
|
|
50
|
+
if op == "-":
|
|
51
|
+
return vals[0] - vals[1]
|
|
52
|
+
if op == "*":
|
|
53
|
+
return vals[0] * vals[1]
|
|
54
|
+
if op == "/":
|
|
55
|
+
return vals[0] / (vals[1] if abs(vals[1]) > 1e-9 else 1e-9)
|
|
56
|
+
if op == "sin":
|
|
57
|
+
return math.sin(vals[0])
|
|
58
|
+
if op == "cos":
|
|
59
|
+
return math.cos(vals[0])
|
|
60
|
+
if op == "exp":
|
|
61
|
+
return math.exp(max(-20.0, min(20.0, vals[0])))
|
|
62
|
+
if op == "tanh":
|
|
63
|
+
return math.tanh(vals[0])
|
|
64
|
+
if op == "square":
|
|
65
|
+
return vals[0] * vals[0]
|
|
66
|
+
return 0.0
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _replace_subtree(expr, path: List[int], new):
|
|
70
|
+
if not path:
|
|
71
|
+
return new
|
|
72
|
+
op = expr[0]
|
|
73
|
+
args = list(expr[1:])
|
|
74
|
+
idx = path[0]
|
|
75
|
+
args[idx] = _replace_subtree(args[idx], path[1:], new)
|
|
76
|
+
return (op,) + tuple(args)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _paths(expr, prefix=()):
|
|
80
|
+
out = [prefix]
|
|
81
|
+
if isinstance(expr, tuple):
|
|
82
|
+
for i, a in enumerate(expr[1:]):
|
|
83
|
+
out.extend(_paths(a, prefix + (i,)))
|
|
84
|
+
return out
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def mutate(expr, rng: random.Random, variables: Sequence[str]):
|
|
88
|
+
paths = _paths(expr)
|
|
89
|
+
path = rng.choice(paths[1:]) if len(paths) > 1 else ()
|
|
90
|
+
new = random_expr(rng, variables, depth=rng.randint(1, 3))
|
|
91
|
+
return _replace_subtree(expr, list(path), new)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def crossover(a, b, rng: random.Random):
|
|
95
|
+
pa = _paths(a)
|
|
96
|
+
path = rng.choice(pa[1:]) if len(pa) > 1 else ()
|
|
97
|
+
return _replace_subtree(a, list(path), b)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def fit(data: Sequence[Tuple[Dict[str, float], float]], variables: Sequence[str],
|
|
101
|
+
generations: int = 25, population: int = 40, seed: int = 1) -> Dict[str, object]:
|
|
102
|
+
rng = random.Random(int(seed))
|
|
103
|
+
if not data:
|
|
104
|
+
return {"expr": None, "mse": 0.0, "size": 0}
|
|
105
|
+
pool = [random_expr(rng, variables, depth=3) for _ in range(max(4, population))]
|
|
106
|
+
|
|
107
|
+
def score(e):
|
|
108
|
+
err = 0.0
|
|
109
|
+
for env, y in data:
|
|
110
|
+
try:
|
|
111
|
+
err += (eval_expr(e, env) - float(y)) ** 2
|
|
112
|
+
except Exception:
|
|
113
|
+
err += 1e6
|
|
114
|
+
return err / len(data) + 0.002 * size(e)
|
|
115
|
+
|
|
116
|
+
best, best_score = pool[0], score(pool[0])
|
|
117
|
+
for _ in range(max(1, generations)):
|
|
118
|
+
scored = sorted(((score(e), e) for e in pool), key=lambda x: x[0])
|
|
119
|
+
if scored[0][0] < best_score:
|
|
120
|
+
best_score, best = scored[0]
|
|
121
|
+
elite = [e for _, e in scored[:max(2, population // 5)]]
|
|
122
|
+
pool = list(elite)
|
|
123
|
+
while len(pool) < population:
|
|
124
|
+
if rng.random() < 0.7:
|
|
125
|
+
pool.append(mutate(rng.choice(elite), rng, variables))
|
|
126
|
+
else:
|
|
127
|
+
pool.append(crossover(rng.choice(elite), rng.choice(elite), rng))
|
|
128
|
+
return {"expr": best, "mse": round(best_score, 6), "size": size(best)}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def expression_text(expr) -> str:
|
|
132
|
+
if isinstance(expr, str):
|
|
133
|
+
return expr
|
|
134
|
+
if isinstance(expr, (int, float)):
|
|
135
|
+
return str(expr)
|
|
136
|
+
op, args = expr[0], expr[1:]
|
|
137
|
+
if op in UNARY:
|
|
138
|
+
return f"{op}({expression_text(args[0])})"
|
|
139
|
+
return f"({expression_text(args[0])} {op} {expression_text(args[1])})"
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def formula_stability(expr, states: Sequence[Dict[str, float]] | None = None) -> float:
|
|
143
|
+
"""Fraction of representative states where the expression is finite and bounded."""
|
|
144
|
+
if expr is None:
|
|
145
|
+
return 1.0
|
|
146
|
+
if not states:
|
|
147
|
+
states = [
|
|
148
|
+
{"energy": 0.2, "social": 0.2, "stress": 0.8, "hunger": 0.8, "thirst": 0.7,
|
|
149
|
+
"pain": 0.5, "inflammation": 0.5, "sleep_pressure": 0.8,
|
|
150
|
+
"known_food": 0.0, "food_uncertainty": 1.0},
|
|
151
|
+
{"energy": 0.9, "social": 0.8, "stress": 0.0, "hunger": 0.1, "thirst": 0.1,
|
|
152
|
+
"pain": 0.0, "inflammation": 0.0, "sleep_pressure": 0.1,
|
|
153
|
+
"known_food": 0.8, "food_uncertainty": 0.2},
|
|
154
|
+
{"energy": 0.5, "social": 0.5, "stress": 0.3, "hunger": 0.5, "thirst": 0.4,
|
|
155
|
+
"pain": 0.2, "inflammation": 0.2, "sleep_pressure": 0.4,
|
|
156
|
+
"known_food": 0.3, "food_uncertainty": 0.7},
|
|
157
|
+
]
|
|
158
|
+
good = 0
|
|
159
|
+
for env in states:
|
|
160
|
+
try:
|
|
161
|
+
v = eval_expr(expr, env)
|
|
162
|
+
if math.isfinite(v) and abs(v) <= 10.0:
|
|
163
|
+
good += 1
|
|
164
|
+
except Exception:
|
|
165
|
+
pass
|
|
166
|
+
return good / max(1, len(states))
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def formula_complexity(expr) -> int:
|
|
170
|
+
return size(expr)
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""Teacher / simulated environment interfaces for offline evolution.
|
|
2
|
+
|
|
3
|
+
The base is the learner. The teacher only generates scenarios and scores
|
|
4
|
+
outcomes; it never changes the base's state directly. Two implementations:
|
|
5
|
+
|
|
6
|
+
- ScriptedTeacher: deterministic, no network, used for smoke tests and fast
|
|
7
|
+
offline evolution runs.
|
|
8
|
+
- DSHTeacher: uses a DSH/LLM client to generate scenarios and judge turns.
|
|
9
|
+
It is a teacher/judge, not the base's controller. No human labels needed.
|
|
10
|
+
|
|
11
|
+
This module deliberately contains no hand-written *base* decision rules.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import math
|
|
17
|
+
import random
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from typing import Dict, List, Optional, Protocol, Sequence
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class Turn:
|
|
24
|
+
text: str
|
|
25
|
+
directed: bool = False
|
|
26
|
+
expected: str = "any" # speak | silence | any
|
|
27
|
+
valence: float = 0.0
|
|
28
|
+
topic: str = "chat"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class Scenario:
|
|
33
|
+
name: str
|
|
34
|
+
persona: str = "user"
|
|
35
|
+
goal: str = "chat"
|
|
36
|
+
turns: List[Turn] = field(default_factory=list)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Teacher(Protocol):
|
|
40
|
+
def scenario(self, seed: int) -> Scenario: ...
|
|
41
|
+
def feedback(self, scenario: Scenario, turn: Turn, action: str, mind) -> float: ...
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _clamp(v: float, lo: float, hi: float) -> float:
|
|
45
|
+
try:
|
|
46
|
+
x = float(v)
|
|
47
|
+
except Exception:
|
|
48
|
+
return lo
|
|
49
|
+
return lo if x < lo else hi if x > hi else x
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _extract_json(text: str) -> Dict[str, object]:
|
|
53
|
+
"""Best-effort JSON object extraction from an LLM answer."""
|
|
54
|
+
raw = str(text or "").strip()
|
|
55
|
+
fence = chr(96) * 3
|
|
56
|
+
if raw.startswith(fence):
|
|
57
|
+
raw = raw.strip(chr(96))
|
|
58
|
+
if raw.lower().startswith("json"):
|
|
59
|
+
raw = raw[4:]
|
|
60
|
+
i = raw.find("{")
|
|
61
|
+
j = raw.rfind("}")
|
|
62
|
+
if i >= 0 and j > i:
|
|
63
|
+
raw = raw[i:j + 1]
|
|
64
|
+
return json.loads(raw)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class ScriptedTeacher:
|
|
68
|
+
"""Deterministic teacher/environment, no network and no human labels.
|
|
69
|
+
|
|
70
|
+
The reward is an explicit simulated outcome: whether the base action
|
|
71
|
+
matched the turn's social affordance, plus a small physiological term.
|
|
72
|
+
It is training *signal*, not a decision rule for the base.
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
TEXT_POOL = [
|
|
76
|
+
"在吗",
|
|
77
|
+
"今天有点累",
|
|
78
|
+
"老板骂我了",
|
|
79
|
+
"陪我聊会儿",
|
|
80
|
+
"我失恋了",
|
|
81
|
+
"今天天气不错",
|
|
82
|
+
"帮我记住我喜欢猫",
|
|
83
|
+
"你在干嘛",
|
|
84
|
+
"晚安",
|
|
85
|
+
"我升职了",
|
|
86
|
+
"有点烦",
|
|
87
|
+
"你会一直陪着我吗",
|
|
88
|
+
"我刚刚做噩梦了",
|
|
89
|
+
"谢谢",
|
|
90
|
+
"周末去哪玩好",
|
|
91
|
+
"我想听你说话",
|
|
92
|
+
"我好像感冒了",
|
|
93
|
+
"没事,就是有点想你",
|
|
94
|
+
"你睡了吗",
|
|
95
|
+
"我今天一个人吃饭",
|
|
96
|
+
]
|
|
97
|
+
|
|
98
|
+
def __init__(self, n_scenarios: int = 50, seed: int = 1, turns_per_scenario: int = 5):
|
|
99
|
+
self.n_scenarios = max(1, int(n_scenarios))
|
|
100
|
+
self.seed = int(seed)
|
|
101
|
+
self.turns_per_scenario = max(1, int(turns_per_scenario))
|
|
102
|
+
self.scenarios: List[Scenario] = self._build(self.n_scenarios, self.seed)
|
|
103
|
+
|
|
104
|
+
def _build(self, n: int, seed: int) -> List[Scenario]:
|
|
105
|
+
rng = random.Random(seed)
|
|
106
|
+
personas = ["老友", "同事", "难过的朋友", "陌生人", "熟悉的用户"]
|
|
107
|
+
out: List[Scenario] = []
|
|
108
|
+
for i in range(n):
|
|
109
|
+
persona = personas[i % len(personas)]
|
|
110
|
+
turns: List[Turn] = []
|
|
111
|
+
for j in range(self.turns_per_scenario):
|
|
112
|
+
text = rng.choice(self.TEXT_POOL)
|
|
113
|
+
directed = (j % 3) != 2
|
|
114
|
+
if directed:
|
|
115
|
+
expected = "speak" if rng.random() < 0.82 else "silence"
|
|
116
|
+
else:
|
|
117
|
+
expected = "silence" if rng.random() < 0.55 else "any"
|
|
118
|
+
turns.append(Turn(text=text, directed=directed, expected=expected,
|
|
119
|
+
valence=0.0, topic="chat"))
|
|
120
|
+
out.append(Scenario(name="scripted_%02d" % i, persona=persona, goal="support", turns=turns))
|
|
121
|
+
return out
|
|
122
|
+
|
|
123
|
+
def scenario(self, seed: int) -> Scenario:
|
|
124
|
+
return self.scenarios[int(seed) % len(self.scenarios)]
|
|
125
|
+
|
|
126
|
+
def feedback(self, scenario: Scenario, turn: Turn, action: str, mind) -> float:
|
|
127
|
+
expected = str(turn.expected or "any")
|
|
128
|
+
if expected == "any":
|
|
129
|
+
match = 0.2
|
|
130
|
+
elif expected == "speak" and str(action) in ("speak", "ask"):
|
|
131
|
+
match = 1.0
|
|
132
|
+
elif expected == "silence" and str(action) == "silence":
|
|
133
|
+
match = 1.0
|
|
134
|
+
elif expected == "speak" and str(action) == "silence":
|
|
135
|
+
match = -1.0
|
|
136
|
+
elif expected == "silence" and str(action) in ("speak", "ask"):
|
|
137
|
+
match = -1.0
|
|
138
|
+
else:
|
|
139
|
+
match = 0.0
|
|
140
|
+
try:
|
|
141
|
+
v = float(getattr(mind.affect, "v", 0.0))
|
|
142
|
+
stress = float(getattr(mind.affect, "stress", 0.0))
|
|
143
|
+
viability = float(mind.viability_state.get("viability", 1.0))
|
|
144
|
+
except Exception:
|
|
145
|
+
v, stress, viability = 0.0, 0.0, 1.0
|
|
146
|
+
reward = 0.6 * match + 0.2 * (viability - 0.5) + 0.1 * v - 0.2 * stress
|
|
147
|
+
return _clamp(reward, -1.0, 1.0)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
_SCENARIO_SYSTEM = (
|
|
151
|
+
"You are a teacher for a digital companion base. Return ONLY JSON. "
|
|
152
|
+
"Generate one realistic chat scenario for offline training."
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
_FEEDBACK_SYSTEM = (
|
|
156
|
+
"You are an evaluation teacher for a digital companion. Return ONLY JSON. "
|
|
157
|
+
"Judge whether the base action is appropriate for this turn."
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
class DSHTeacher:
|
|
161
|
+
"""LLM/DSH-backed teacher: generates scenarios and judges turns.
|
|
162
|
+
|
|
163
|
+
It uses an injected client object with generate(LLMRequest), the same
|
|
164
|
+
interface as OpenAICompatClient. On any failure it falls back to a
|
|
165
|
+
deterministic ScriptedTeacher, so offline runs never hard-fail.
|
|
166
|
+
|
|
167
|
+
Cache policy: the system prompts are frozen module constants; scenario and
|
|
168
|
+
judge payloads are appended per call. DeepSeek prefix caching can then
|
|
169
|
+
reuse the same system prefix instead of rebuilding it every turn.
|
|
170
|
+
"""
|
|
171
|
+
|
|
172
|
+
def __init__(self, client=None, fallback: Optional[Teacher] = None,
|
|
173
|
+
n_scenarios: int = 50, seed: int = 1):
|
|
174
|
+
self.client = client
|
|
175
|
+
self.fallback = fallback or ScriptedTeacher(n_scenarios=n_scenarios, seed=seed)
|
|
176
|
+
|
|
177
|
+
def _call(self, system: str, user: str) -> str:
|
|
178
|
+
if self.client is None:
|
|
179
|
+
raise RuntimeError("no DSH/LLM client configured")
|
|
180
|
+
from .llm_adapter import build_prompt
|
|
181
|
+
from .types import LLMRequest
|
|
182
|
+
req = LLMRequest(mode="semantic", urgency=0.5, max_tokens=800,
|
|
183
|
+
reason="teacher", context={"system": system, "user": user})
|
|
184
|
+
return str(self.client.generate(req))
|
|
185
|
+
|
|
186
|
+
def scenario(self, seed: int) -> Scenario:
|
|
187
|
+
# Stable prefix: DeepSeek context cache can reuse it across calls.
|
|
188
|
+
system = _SCENARIO_SYSTEM
|
|
189
|
+
user = (
|
|
190
|
+
"Return a JSON object with keys: name (str), persona (str), goal (str), "
|
|
191
|
+
"turns (array of 4-6 objects). Each turn object: text (str), directed (bool), "
|
|
192
|
+
"expected (speak|silence|any), valence (number -1..1), topic (str). "
|
|
193
|
+
"Make it diverse and emotionally plausible."
|
|
194
|
+
)
|
|
195
|
+
try:
|
|
196
|
+
data = _extract_json(self._call(system, user))
|
|
197
|
+
raw_turns = data.get("turns") or []
|
|
198
|
+
turns: List[Turn] = []
|
|
199
|
+
for x in raw_turns:
|
|
200
|
+
if not isinstance(x, dict) or not x.get("text"):
|
|
201
|
+
continue
|
|
202
|
+
turns.append(Turn(
|
|
203
|
+
text=str(x.get("text")),
|
|
204
|
+
directed=bool(x.get("directed", False)),
|
|
205
|
+
expected=str(x.get("expected", "any")),
|
|
206
|
+
valence=_clamp(x.get("valence", 0.0), -1.0, 1.0),
|
|
207
|
+
topic=str(x.get("topic", "chat")),
|
|
208
|
+
))
|
|
209
|
+
if not turns:
|
|
210
|
+
raise ValueError("empty scenario")
|
|
211
|
+
return Scenario(name=str(data.get("name", "dsh_%d" % seed)),
|
|
212
|
+
persona=str(data.get("persona", "user")),
|
|
213
|
+
goal=str(data.get("goal", "chat")),
|
|
214
|
+
turns=turns)
|
|
215
|
+
except Exception:
|
|
216
|
+
return self.fallback.scenario(seed)
|
|
217
|
+
|
|
218
|
+
def feedback(self, scenario: Scenario, turn: Turn, action: str, mind) -> float:
|
|
219
|
+
try:
|
|
220
|
+
state = {
|
|
221
|
+
"v": float(getattr(mind.affect, "v", 0.0)),
|
|
222
|
+
"stress": float(getattr(mind.affect, "stress", 0.0)),
|
|
223
|
+
"energy": float(mind.drives.values.get("energy", 0.0)),
|
|
224
|
+
"social": float(mind.drives.values.get("social", 0.0)),
|
|
225
|
+
"viability": float(mind.viability_state.get("viability", 1.0)),
|
|
226
|
+
}
|
|
227
|
+
except Exception:
|
|
228
|
+
state = {}
|
|
229
|
+
# Stable prefix: DeepSeek context cache can reuse it across calls.
|
|
230
|
+
system = _FEEDBACK_SYSTEM
|
|
231
|
+
user = json.dumps({
|
|
232
|
+
"scenario": scenario.name,
|
|
233
|
+
"persona": scenario.persona,
|
|
234
|
+
"turn": {"text": turn.text, "directed": turn.directed,
|
|
235
|
+
"expected": turn.expected, "valence": turn.valence},
|
|
236
|
+
"action": action,
|
|
237
|
+
"state": state,
|
|
238
|
+
"output_schema": {"reward": "number -1..1", "reason": "short string"},
|
|
239
|
+
}, ensure_ascii=False)
|
|
240
|
+
try:
|
|
241
|
+
data = _extract_json(self._call(system, user))
|
|
242
|
+
return _clamp(data.get("reward", 0.0), -1.0, 1.0)
|
|
243
|
+
except Exception:
|
|
244
|
+
return self.fallback.feedback(scenario, turn, action, mind)
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Dict
|
|
4
|
+
|
|
5
|
+
from .active_inference import ActiveInference
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def prediction_error(value: float, expected: float) -> float:
|
|
9
|
+
return float(value) - float(expected)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def allostatic_error(value: float, setpoint: float) -> float:
|
|
13
|
+
return float(value) - float(setpoint)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def rpe_update(value: float, reward: float, prediction: float, lr: float) -> float:
|
|
17
|
+
return float(value) + lr * (float(reward) - float(prediction))
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def unified_state(mb) -> Dict[str, object]:
|
|
21
|
+
"""One state vector shared by biological, mathematical, digital and psychological layers."""
|
|
22
|
+
drives = mb.drives
|
|
23
|
+
self_model = mb.self_model
|
|
24
|
+
load = drives.allostatic_load()
|
|
25
|
+
ai = (getattr(mb, 'active_inference', None) or ActiveInference()).choose(load, abs(self_model.prediction_error), drives.get("social"), drives.get("energy"))
|
|
26
|
+
last = mb.learner.log[-1] if mb.learner.log else {}
|
|
27
|
+
return {
|
|
28
|
+
"E": round(load, 4),
|
|
29
|
+
"RPE": round(float(last.get("rpe", 0.0) or 0.0), 4),
|
|
30
|
+
"F": min(float(ai["efe_speak"]), float(ai["efe_silence"])),
|
|
31
|
+
"S": round(float(self_model.prediction_error), 4),
|
|
32
|
+
"A": {
|
|
33
|
+
"valence": round(mb.affect.v, 3),
|
|
34
|
+
"arousal": round(mb.affect.a, 3),
|
|
35
|
+
"stress": round(mb.affect.stress, 3),
|
|
36
|
+
"mood": round(mb.affect.mood, 3),
|
|
37
|
+
},
|
|
38
|
+
"drives": drives.snapshot(),
|
|
39
|
+
"self": self_model.snapshot(),
|
|
40
|
+
"memory": mb.memory.snapshot(),
|
|
41
|
+
"active_inference": ai,
|
|
42
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from typing import Dict, Set
|
|
5
|
+
|
|
6
|
+
from .types import Appraisal, Event
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass
|
|
10
|
+
class AgentModel:
|
|
11
|
+
name: str
|
|
12
|
+
beliefs: Set[str] = field(default_factory=set)
|
|
13
|
+
knowledge: Set[str] = field(default_factory=set)
|
|
14
|
+
desires: Dict[str, float] = field(default_factory=dict)
|
|
15
|
+
intentions: Set[str] = field(default_factory=set)
|
|
16
|
+
# observer thinks target knows these facts
|
|
17
|
+
second_order: Dict[str, Set[str]] = field(default_factory=dict)
|
|
18
|
+
last_seen: float = 0.0
|
|
19
|
+
|
|
20
|
+
def snapshot(self) -> Dict[str, object]:
|
|
21
|
+
return {
|
|
22
|
+
"beliefs": list(self.beliefs)[-5:],
|
|
23
|
+
"knowledge": list(self.knowledge)[-5:],
|
|
24
|
+
"desires": {k: round(v, 2) for k, v in list(self.desires.items())[-5:]},
|
|
25
|
+
"intentions": list(self.intentions)[-3:],
|
|
26
|
+
"second_order": {k: list(v)[-3:] for k, v in list(self.second_order.items())[-3:]},
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class TheoryOfMind:
|
|
31
|
+
"""Lightweight, non-LLM ToM: beliefs, desires, intentions, second-order knowledge.
|
|
32
|
+
|
|
33
|
+
This is a heuristic model, not a claim of human-like mindreading.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
INTENTION_CUES = ("想", "要", "打算", "准备", "会去", "plan", "want", "will")
|
|
37
|
+
MENTAL_CUES = ("知道", "以为", "觉得", "认为", "know", "think", "believe")
|
|
38
|
+
|
|
39
|
+
def __init__(self):
|
|
40
|
+
self.agents: Dict[str, AgentModel] = {}
|
|
41
|
+
|
|
42
|
+
def _agent(self, name: str) -> AgentModel:
|
|
43
|
+
if not name or name == "self":
|
|
44
|
+
name = "self"
|
|
45
|
+
return self.agents.setdefault(name, AgentModel(name=name))
|
|
46
|
+
|
|
47
|
+
def observe(self, ev: Event, ap: Appraisal, now: float = 0.0) -> None:
|
|
48
|
+
speaker = ev.speaker or "unknown"
|
|
49
|
+
if speaker == "self":
|
|
50
|
+
return
|
|
51
|
+
fact = (ev.text or "").strip()
|
|
52
|
+
if not fact:
|
|
53
|
+
return
|
|
54
|
+
model = self._agent(speaker)
|
|
55
|
+
model.beliefs.add(fact)
|
|
56
|
+
model.knowledge.add(fact)
|
|
57
|
+
model.desires[fact] = float(ap.valence)
|
|
58
|
+
model.last_seen = now
|
|
59
|
+
|
|
60
|
+
lower = fact.lower()
|
|
61
|
+
if any(cue in lower for cue in self.INTENTION_CUES):
|
|
62
|
+
model.intentions.add(fact)
|
|
63
|
+
|
|
64
|
+
if any(cue in lower for cue in self.MENTAL_CUES):
|
|
65
|
+
for target in list(self.agents):
|
|
66
|
+
if target != speaker and target in fact:
|
|
67
|
+
model.second_order.setdefault(target, set()).add(fact)
|
|
68
|
+
|
|
69
|
+
def second_order(self, observer: str, target: str, fact: str) -> bool:
|
|
70
|
+
model = self.agents.get(observer)
|
|
71
|
+
return bool(model and fact in model.second_order.get(target, set()))
|
|
72
|
+
|
|
73
|
+
def believes(self, speaker: str, fact: str) -> bool:
|
|
74
|
+
model = self.agents.get(speaker)
|
|
75
|
+
return bool(model and fact in model.beliefs)
|
|
76
|
+
|
|
77
|
+
def predict_action(self, speaker: str) -> str:
|
|
78
|
+
model = self.agents.get(speaker)
|
|
79
|
+
if model is None:
|
|
80
|
+
return "communicate"
|
|
81
|
+
if model.intentions:
|
|
82
|
+
return "approach"
|
|
83
|
+
if model.desires:
|
|
84
|
+
avg = sum(model.desires.values()) / len(model.desires)
|
|
85
|
+
if avg > 0.20:
|
|
86
|
+
return "approach"
|
|
87
|
+
if avg < -0.20:
|
|
88
|
+
return "avoid"
|
|
89
|
+
return "communicate"
|
|
90
|
+
|
|
91
|
+
def context(self) -> Dict[str, object]:
|
|
92
|
+
return {
|
|
93
|
+
"agents": len(self.agents),
|
|
94
|
+
"models": {name: model.snapshot() for name, model in list(self.agents.items())[-4:]},
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
def snapshot(self) -> Dict[str, object]:
|
|
98
|
+
return self.context()
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Bidirectional translation contract.
|
|
2
|
+
|
|
3
|
+
LLM -> bio: text/event -> numeric appraisal vector.
|
|
4
|
+
bio -> LLM: state -> compact intent tags.
|
|
5
|
+
The translator never generates language and never makes final decisions.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from .bio_semantic import translate
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _f(x, default=0.0):
|
|
13
|
+
try:
|
|
14
|
+
return float(x)
|
|
15
|
+
except Exception:
|
|
16
|
+
return float(default)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class TranslationLayer:
|
|
20
|
+
def __init__(self):
|
|
21
|
+
self.last_inbound = {}
|
|
22
|
+
self.last_outbound = {}
|
|
23
|
+
self.last_feedback = {}
|
|
24
|
+
|
|
25
|
+
def inbound(self, text, sensor=None, confidence=None):
|
|
26
|
+
s = dict(sensor or {})
|
|
27
|
+
event = {
|
|
28
|
+
"valence": _f(s.get("valence"), 0.0),
|
|
29
|
+
"arousal": _f(s.get("arousal"), 0.5),
|
|
30
|
+
"dominance": _f(s.get("dominance"), 0.0),
|
|
31
|
+
"intensity": _f(s.get("intensity"), 0.5),
|
|
32
|
+
"threat": _f(s.get("threat"), 0.0),
|
|
33
|
+
"stress": _f(s.get("stress"), 0.0),
|
|
34
|
+
"guilt": _f(s.get("guilt"), 0.0),
|
|
35
|
+
"shame": _f(s.get("shame"), 0.0),
|
|
36
|
+
"connection_delta": _f(s.get("connection_delta"), 0.0),
|
|
37
|
+
"confidence": _f(confidence if confidence is not None else s.get("confidence"), 0.5),
|
|
38
|
+
"source": "llm" if s else "local",
|
|
39
|
+
}
|
|
40
|
+
self.last_inbound = event
|
|
41
|
+
return event
|
|
42
|
+
|
|
43
|
+
def outbound(self, mind, behavior=None, ripple_outputs=None, trust=None, emotion=None, event=None):
|
|
44
|
+
intent = translate(mind, behavior, ripple_outputs, trust=trust, emotion=emotion, event=event)
|
|
45
|
+
self.last_outbound = intent
|
|
46
|
+
return intent
|
|
47
|
+
|
|
48
|
+
def apply_event(self, mind, event):
|
|
49
|
+
e = dict(event or {})
|
|
50
|
+
try:
|
|
51
|
+
mind.inject_affect(e.get("valence", 0.0), e.get("arousal", 0.5),
|
|
52
|
+
e.get("dominance", 0.0),
|
|
53
|
+
intensity=max(0.1, _f(e.get("intensity"), 0.5)),
|
|
54
|
+
blend=0.5)
|
|
55
|
+
except Exception:
|
|
56
|
+
pass
|
|
57
|
+
try:
|
|
58
|
+
v = _f(e.get("valence"), 0.0)
|
|
59
|
+
stress = max(0.0, -v) * 0.5 + _f(e.get("threat"), 0.0) * 0.5 + _f(e.get("stress"), 0.0) * 0.5
|
|
60
|
+
mind.affect.stress = max(0.0, min(1.0, _f(getattr(mind.affect, "stress", 0.2)) + 0.10 * stress))
|
|
61
|
+
except Exception:
|
|
62
|
+
pass
|
|
63
|
+
|
|
64
|
+
def feedback(self, mind, reply, user_text=""):
|
|
65
|
+
r = str(reply or "")
|
|
66
|
+
t = str(user_text or "")
|
|
67
|
+
warm = sum(1 for w in ("谢谢", "你", "在", "陪", "懂", "暖") if w in r)
|
|
68
|
+
cold = sum(1 for w in ("不想", "别", "烦", "算了", "随便") if w in r)
|
|
69
|
+
delta = 0.01 * warm - 0.01 * cold
|
|
70
|
+
try:
|
|
71
|
+
mind.social.trust_for # noqa
|
|
72
|
+
except Exception:
|
|
73
|
+
pass
|
|
74
|
+
try:
|
|
75
|
+
mind.affect.stress = max(0.0, min(1.0, _f(getattr(mind.affect, "stress", 0.2))
|
|
76
|
+
+ 0.02 * cold - 0.025))
|
|
77
|
+
except Exception:
|
|
78
|
+
pass
|
|
79
|
+
self.last_feedback = {"trust_delta": round(delta, 4), "warm": warm, "cold": cold}
|
|
80
|
+
return dict(self.last_feedback)
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Simple turn-level observability metrics from turns.jsonl."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Dict, List
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _tokens(s: str) -> set:
|
|
10
|
+
return set(str(s or "").lower().split())
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def jaccard(a: str, b: str) -> float:
|
|
14
|
+
x, y = _tokens(a), _tokens(b)
|
|
15
|
+
if not x or not y:
|
|
16
|
+
return 0.0
|
|
17
|
+
return len(x & y) / len(x | y)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def summarize(rows: List[dict]) -> Dict[str, object]:
|
|
21
|
+
total = len(rows)
|
|
22
|
+
replies = [str(r.get("reply") or "") for r in rows]
|
|
23
|
+
nonempty = [r for r in replies if r]
|
|
24
|
+
gated = sum(1 for r in rows if r.get("gated"))
|
|
25
|
+
proactive = sum(1 for r in rows if r.get("proactive"))
|
|
26
|
+
group_auto = sum(1 for r in rows if r.get("group_auto"))
|
|
27
|
+
repeats = 0
|
|
28
|
+
for a, b in zip(replies, replies[1:]):
|
|
29
|
+
if a and b and jaccard(a, b) >= 0.55:
|
|
30
|
+
repeats += 1
|
|
31
|
+
return {
|
|
32
|
+
"turns": total,
|
|
33
|
+
"replied": len(nonempty),
|
|
34
|
+
"empty": total - len(nonempty),
|
|
35
|
+
"gated": gated,
|
|
36
|
+
"proactive": proactive,
|
|
37
|
+
"group_auto": group_auto,
|
|
38
|
+
"avg_reply_chars": round(sum(len(x) for x in nonempty) / max(1, len(nonempty)), 1),
|
|
39
|
+
"repeat_pairs": repeats,
|
|
40
|
+
"repeat_rate": round(repeats / max(1, total - 1), 3),
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def summarize_file(path: Path | str) -> Dict[str, object]:
|
|
45
|
+
p = Path(path)
|
|
46
|
+
rows = []
|
|
47
|
+
for line in p.read_text(encoding="utf-8").splitlines():
|
|
48
|
+
try:
|
|
49
|
+
rows.append(json.loads(line))
|
|
50
|
+
except Exception:
|
|
51
|
+
pass
|
|
52
|
+
return summarize(rows)
|