anthromesh 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- anthromesh/__init__.py +3 -0
- anthromesh/adapters/__init__.py +18 -0
- anthromesh/adapters/base.py +218 -0
- anthromesh/adapters/cloud.py +151 -0
- anthromesh/adapters/factory.py +31 -0
- anthromesh/adapters/heuristic.py +113 -0
- anthromesh/adapters/local.py +91 -0
- anthromesh/benchmarks/__init__.py +3 -0
- anthromesh/benchmarks/datasets.py +207 -0
- anthromesh/benchmarks/empirical.py +176 -0
- anthromesh/benchmarks/panel_cohort.py +67 -0
- anthromesh/benchmarks/public_twin.py +414 -0
- anthromesh/benchmarks/public_validation.py +435 -0
- anthromesh/benchmarks/replay.py +174 -0
- anthromesh/benchmarks/runner.py +140 -0
- anthromesh/benchmarks/study.py +245 -0
- anthromesh/benchmarks/study_report.py +170 -0
- anthromesh/capture/__init__.py +1 -0
- anthromesh/capture/github_webhook.py +51 -0
- anthromesh/capture/graph.py +221 -0
- anthromesh/capture/workflows.py +70 -0
- anthromesh/cli.py +807 -0
- anthromesh/client.py +96 -0
- anthromesh/cohort/__init__.py +3 -0
- anthromesh/cohort/categorical_anchor.py +240 -0
- anthromesh/cohort/clustering.py +93 -0
- anthromesh/cohort/human_anchor.py +92 -0
- anthromesh/cohort/ingest.py +104 -0
- anthromesh/cohort/oracle.py +153 -0
- anthromesh/cohort/twin_priors.py +118 -0
- anthromesh/config.py +48 -0
- anthromesh/gate/__init__.py +15 -0
- anthromesh/gate/calibration.py +95 -0
- anthromesh/gate/conformal.py +73 -0
- anthromesh/gate/engine.py +293 -0
- anthromesh/gate/fast.py +62 -0
- anthromesh/gate/fit.py +56 -0
- anthromesh/judgment/__init__.py +1 -0
- anthromesh/judgment/elicitation.py +206 -0
- anthromesh/judgment/monitor.py +128 -0
- anthromesh/judgment/panel.py +389 -0
- anthromesh/judgment/settings.py +41 -0
- anthromesh/models/__init__.py +39 -0
- anthromesh/models/cohort.py +76 -0
- anthromesh/models/decision.py +81 -0
- anthromesh/models/escalation.py +70 -0
- anthromesh/models/policy.py +41 -0
- anthromesh/models/validity.py +17 -0
- anthromesh/protocols/__init__.py +4 -0
- anthromesh/protocols/a2a_server.py +414 -0
- anthromesh/protocols/capabilities.py +52 -0
- anthromesh/protocols/delegation.py +373 -0
- anthromesh/protocols/mcp_server.py +500 -0
- anthromesh/protocols/oauth.py +177 -0
- anthromesh/ros_gate.py +141 -0
- anthromesh/twin/__init__.py +3 -0
- anthromesh/twin/engine.py +116 -0
- anthromesh/twin/inbox.py +221 -0
- anthromesh/vault/__init__.py +5 -0
- anthromesh/vault/dense.py +171 -0
- anthromesh/vault/encryption.py +50 -0
- anthromesh/vault/policy_engine.py +123 -0
- anthromesh/vault/postgres.py +92 -0
- anthromesh/vault/privacy.py +264 -0
- anthromesh/vault/retrieval.py +135 -0
- anthromesh/vault/storage.py +937 -0
- anthromesh-0.2.0.dist-info/METADATA +493 -0
- anthromesh-0.2.0.dist-info/RECORD +73 -0
- anthromesh-0.2.0.dist-info/WHEEL +5 -0
- anthromesh-0.2.0.dist-info/entry_points.txt +2 -0
- anthromesh-0.2.0.dist-info/licenses/LICENSE +201 -0
- anthromesh-0.2.0.dist-info/licenses/NOTICE +2 -0
- anthromesh-0.2.0.dist-info/top_level.txt +1 -0
anthromesh/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from .base import BaseModelAdapter, StructuredPrediction
|
|
2
|
+
from .cloud import AnthropicAdapter, GeminiAdapter, OpenAIAdapter
|
|
3
|
+
from .factory import create_adapter, list_supported_adapters
|
|
4
|
+
from .heuristic import HeuristicAdapter
|
|
5
|
+
from .local import OllamaAdapter, VLLMAdapter
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"AnthropicAdapter",
|
|
9
|
+
"BaseModelAdapter",
|
|
10
|
+
"GeminiAdapter",
|
|
11
|
+
"HeuristicAdapter",
|
|
12
|
+
"OllamaAdapter",
|
|
13
|
+
"OpenAIAdapter",
|
|
14
|
+
"StructuredPrediction",
|
|
15
|
+
"VLLMAdapter",
|
|
16
|
+
"create_adapter",
|
|
17
|
+
"list_supported_adapters",
|
|
18
|
+
]
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
import urllib.error
|
|
6
|
+
import urllib.request
|
|
7
|
+
from contextlib import contextmanager
|
|
8
|
+
from contextvars import ContextVar
|
|
9
|
+
from time import monotonic
|
|
10
|
+
from abc import ABC, abstractmethod
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from pydantic import BaseModel, Field
|
|
14
|
+
|
|
15
|
+
from anthromesh.models import CandidateOption, CohortArchetype, DecisionLog, QueryContext
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class StructuredPrediction(BaseModel):
|
|
19
|
+
chosen_option: str
|
|
20
|
+
rationale: str
|
|
21
|
+
self_reported_confidence: float = Field(default=0.5, ge=0.0, le=1.0)
|
|
22
|
+
option_scores: dict[str, float] = Field(default_factory=dict)
|
|
23
|
+
raw_text: str = ""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
_inference_deadline: ContextVar[float | None] = ContextVar("anthromesh_inference_deadline", default=None)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@contextmanager
|
|
30
|
+
def inference_budget(seconds: float | None):
|
|
31
|
+
if seconds is None:
|
|
32
|
+
yield
|
|
33
|
+
return
|
|
34
|
+
token = _inference_deadline.set(monotonic() + seconds)
|
|
35
|
+
try:
|
|
36
|
+
yield
|
|
37
|
+
remaining_inference_time()
|
|
38
|
+
finally:
|
|
39
|
+
_inference_deadline.reset(token)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def remaining_inference_time() -> float | None:
|
|
43
|
+
deadline = _inference_deadline.get()
|
|
44
|
+
if deadline is None:
|
|
45
|
+
return None
|
|
46
|
+
remaining = deadline - monotonic()
|
|
47
|
+
if remaining <= 0:
|
|
48
|
+
raise TimeoutError("Inference budget exhausted.")
|
|
49
|
+
return remaining
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def post_json(
|
|
53
|
+
url: str,
|
|
54
|
+
payload: dict[str, Any],
|
|
55
|
+
headers: dict[str, str] | None = None,
|
|
56
|
+
timeout: float = 45.0,
|
|
57
|
+
) -> dict[str, Any]:
|
|
58
|
+
"""HTTP JSON POST using httpx when installed, falling back to stdlib urllib."""
|
|
59
|
+
remaining = remaining_inference_time()
|
|
60
|
+
if remaining is not None:
|
|
61
|
+
timeout = min(timeout, remaining)
|
|
62
|
+
req_headers = {"Content-Type": "application/json", **(headers or {})}
|
|
63
|
+
try:
|
|
64
|
+
import httpx # type: ignore
|
|
65
|
+
|
|
66
|
+
try:
|
|
67
|
+
with httpx.Client(timeout=timeout) as client:
|
|
68
|
+
resp = client.post(url, json=payload, headers=req_headers)
|
|
69
|
+
resp.raise_for_status()
|
|
70
|
+
return resp.json()
|
|
71
|
+
except httpx.TimeoutException as exc:
|
|
72
|
+
raise TimeoutError("Inference request exceeded its timeout.") from exc
|
|
73
|
+
except ImportError:
|
|
74
|
+
body = json.dumps(payload).encode("utf-8")
|
|
75
|
+
req = urllib.request.Request(url, data=body, headers=req_headers, method="POST")
|
|
76
|
+
try:
|
|
77
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
78
|
+
return json.loads(resp.read().decode("utf-8"))
|
|
79
|
+
except urllib.error.HTTPError as exc:
|
|
80
|
+
detail = exc.read().decode("utf-8", errors="replace")
|
|
81
|
+
raise RuntimeError(f"HTTP {exc.code} from {url}: {detail}") from exc
|
|
82
|
+
except urllib.error.URLError as exc:
|
|
83
|
+
if isinstance(exc.reason, TimeoutError):
|
|
84
|
+
raise TimeoutError("Inference request exceeded its timeout.") from exc
|
|
85
|
+
raise
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def extract_json_object(text: str) -> dict[str, Any]:
|
|
89
|
+
"""Extracts the first JSON object from model output, tolerating markdown code fences."""
|
|
90
|
+
cleaned = text.strip()
|
|
91
|
+
fence = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", cleaned, flags=re.DOTALL)
|
|
92
|
+
if fence:
|
|
93
|
+
cleaned = fence.group(1)
|
|
94
|
+
else:
|
|
95
|
+
start = cleaned.find("{")
|
|
96
|
+
end = cleaned.rfind("}")
|
|
97
|
+
if start != -1 and end != -1 and end > start:
|
|
98
|
+
cleaned = cleaned[start : end + 1]
|
|
99
|
+
return json.loads(cleaned)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class BaseModelAdapter(ABC):
|
|
103
|
+
"""Pluggable inference adapter contract for local runners (Ollama/vLLM) and cloud APIs."""
|
|
104
|
+
|
|
105
|
+
adapter_name: str = "base"
|
|
106
|
+
|
|
107
|
+
def __init__(self, model: str) -> None:
|
|
108
|
+
self.model = model
|
|
109
|
+
|
|
110
|
+
@abstractmethod
|
|
111
|
+
def predict_decision(
|
|
112
|
+
self,
|
|
113
|
+
query: QueryContext,
|
|
114
|
+
evidence: list[tuple[DecisionLog, float]],
|
|
115
|
+
) -> StructuredPrediction:
|
|
116
|
+
"""Predicts which candidate option the human subject would choose given retrieved evidence."""
|
|
117
|
+
|
|
118
|
+
@abstractmethod
|
|
119
|
+
def simulate_cohort_archetype(
|
|
120
|
+
self,
|
|
121
|
+
stimulus: str,
|
|
122
|
+
options: list[CandidateOption],
|
|
123
|
+
archetype: CohortArchetype,
|
|
124
|
+
) -> StructuredPrediction:
|
|
125
|
+
"""Predicts how a specific cohort archetype responds to a research stimulus."""
|
|
126
|
+
|
|
127
|
+
def predict_persona(self, query: QueryContext, persona: str) -> StructuredPrediction:
|
|
128
|
+
"""Predict a choice from a short consented persona and the case only."""
|
|
129
|
+
system = (
|
|
130
|
+
"Estimate which option the person described in the input would choose. "
|
|
131
|
+
"Return a JSON object with chosen_option, rationale, self_reported_confidence, "
|
|
132
|
+
"and option_scores keyed by every option ID."
|
|
133
|
+
)
|
|
134
|
+
user = json.dumps({
|
|
135
|
+
"persona": persona, "domain": query.domain, "context": query.context,
|
|
136
|
+
"candidate_options": [item.model_dump() for item in query.candidate_options],
|
|
137
|
+
}, ensure_ascii=False)
|
|
138
|
+
return self.parse_prediction(self._chat(system, user), query.candidate_options)
|
|
139
|
+
|
|
140
|
+
def _chat(self, system: str, user: str) -> str:
|
|
141
|
+
raise NotImplementedError("This adapter cannot run prompt-only inference.")
|
|
142
|
+
|
|
143
|
+
@staticmethod
|
|
144
|
+
def build_decision_prompt(
|
|
145
|
+
query: QueryContext,
|
|
146
|
+
evidence: list[tuple[DecisionLog, float]],
|
|
147
|
+
) -> tuple[str, str]:
|
|
148
|
+
system = (
|
|
149
|
+
"You are a provenance-grounded human behavioral prediction engine. "
|
|
150
|
+
"Do NOT default to generic or average advice. Base your prediction strictly on the "
|
|
151
|
+
"retrieved past human decisions, trade-offs, and rationales. "
|
|
152
|
+
"Respond ONLY with a valid JSON object matching: "
|
|
153
|
+
'{"chosen_option": "<option_id>", "rationale": "<concise rationale citing evidence>", '
|
|
154
|
+
'"self_reported_confidence": <float 0..1>, "option_scores": {"<option_id>": <float 0..1>}}.'
|
|
155
|
+
)
|
|
156
|
+
ev_lines = []
|
|
157
|
+
for idx, (dec, sim) in enumerate(evidence, 1):
|
|
158
|
+
ev_lines.append(
|
|
159
|
+
f"[{idx}] id={dec.decision_id} sim={sim:.2f} domain={dec.domain}\n"
|
|
160
|
+
f" context: {dec.context}\n"
|
|
161
|
+
f" chosen: {dec.chosen_action} | rejected: {', '.join(dec.rejected_options)}\n"
|
|
162
|
+
f" rationale: {dec.rationale}"
|
|
163
|
+
)
|
|
164
|
+
opt_lines = [f"- {o.option_id}: {o.label} ({o.description})" for o in query.candidate_options]
|
|
165
|
+
user = (
|
|
166
|
+
f"Subject: {query.subject_id}\nDomain: {query.domain}\n"
|
|
167
|
+
f"Current Context: {query.context}\n\n"
|
|
168
|
+
f"Candidate Options:\n" + "\n".join(opt_lines) + "\n\n"
|
|
169
|
+
f"Retrieved Historical Evidence:\n"
|
|
170
|
+
+ ("\n".join(ev_lines) if ev_lines else "NONE (no prior evidence available)")
|
|
171
|
+
)
|
|
172
|
+
return system, user
|
|
173
|
+
|
|
174
|
+
@staticmethod
|
|
175
|
+
def build_cohort_prompt(
|
|
176
|
+
stimulus: str,
|
|
177
|
+
options: list[CandidateOption],
|
|
178
|
+
archetype: CohortArchetype,
|
|
179
|
+
) -> tuple[str, str]:
|
|
180
|
+
system = (
|
|
181
|
+
"You are simulating a specific human cohort archetype for empirical research. "
|
|
182
|
+
"Preserve authentic human variance and minority/long-tail viewpoints—do NOT collapse "
|
|
183
|
+
"to polite consensus. Respond ONLY with valid JSON: "
|
|
184
|
+
'{"chosen_option": "<option_id>", "rationale": "<in-character rationale>", '
|
|
185
|
+
'"self_reported_confidence": <float 0..1>, "option_scores": {"<option_id>": <float 0..1>}}.'
|
|
186
|
+
)
|
|
187
|
+
opt_lines = [f"- {o.option_id}: {o.label} ({o.description})" for o in options]
|
|
188
|
+
user = (
|
|
189
|
+
f"Archetype: {archetype.label} (long_tail={archetype.is_long_tail})\n"
|
|
190
|
+
f"Traits: {json.dumps(archetype.traits)}\n"
|
|
191
|
+
f"Prior Tendencies: {json.dumps(archetype.prior_tendencies)}\n"
|
|
192
|
+
f"Sample Past Rationales: {json.dumps(archetype.sample_rationales)}\n\n"
|
|
193
|
+
f"Research Stimulus: {stimulus}\n\n"
|
|
194
|
+
f"Options:\n" + "\n".join(opt_lines)
|
|
195
|
+
)
|
|
196
|
+
return system, user
|
|
197
|
+
|
|
198
|
+
@staticmethod
|
|
199
|
+
def parse_prediction(raw_text: str, options: list[CandidateOption]) -> StructuredPrediction:
|
|
200
|
+
valid_ids = {o.option_id for o in options}
|
|
201
|
+
parsed = extract_json_object(raw_text)
|
|
202
|
+
chosen = str(parsed.get("chosen_option", "")).strip()
|
|
203
|
+
if chosen not in valid_ids:
|
|
204
|
+
chosen = options[0].option_id
|
|
205
|
+
conf = float(parsed.get("self_reported_confidence", 0.5))
|
|
206
|
+
conf = max(0.0, min(1.0, conf))
|
|
207
|
+
scores = {
|
|
208
|
+
k: max(0.0, min(1.0, float(v)))
|
|
209
|
+
for k, v in (parsed.get("option_scores") or {}).items()
|
|
210
|
+
if k in valid_ids
|
|
211
|
+
}
|
|
212
|
+
return StructuredPrediction(
|
|
213
|
+
chosen_option=chosen,
|
|
214
|
+
rationale=str(parsed.get("rationale", "")).strip() or "Predicted from behavioral context.",
|
|
215
|
+
self_reported_confidence=conf,
|
|
216
|
+
option_scores=scores,
|
|
217
|
+
raw_text=raw_text,
|
|
218
|
+
)
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from anthromesh.models import CandidateOption, CohortArchetype, DecisionLog, QueryContext
|
|
4
|
+
from .base import BaseModelAdapter, StructuredPrediction, post_json
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class OpenAIAdapter(BaseModelAdapter):
|
|
8
|
+
"""Cloud inference adapter for OpenAI Chat Completions API."""
|
|
9
|
+
|
|
10
|
+
adapter_name = "openai"
|
|
11
|
+
|
|
12
|
+
def __init__(
|
|
13
|
+
self,
|
|
14
|
+
model: str = "gpt-4o-mini",
|
|
15
|
+
api_key: str | None = None,
|
|
16
|
+
base_url: str = "https://api.openai.com/v1",
|
|
17
|
+
) -> None:
|
|
18
|
+
super().__init__(model=model)
|
|
19
|
+
if not api_key:
|
|
20
|
+
raise ValueError("OPENAI_API_KEY is required for OpenAIAdapter.")
|
|
21
|
+
self.api_key = api_key
|
|
22
|
+
self.base_url = base_url.rstrip("/")
|
|
23
|
+
|
|
24
|
+
def _chat(self, system: str, user: str) -> str:
|
|
25
|
+
payload = {
|
|
26
|
+
"model": self.model,
|
|
27
|
+
"temperature": 0.2,
|
|
28
|
+
"response_format": {"type": "json_object"},
|
|
29
|
+
"messages": [
|
|
30
|
+
{"role": "system", "content": system},
|
|
31
|
+
{"role": "user", "content": user},
|
|
32
|
+
],
|
|
33
|
+
}
|
|
34
|
+
headers = {"Authorization": f"Bearer {self.api_key}"}
|
|
35
|
+
data = post_json(f"{self.base_url}/chat/completions", payload, headers=headers)
|
|
36
|
+
return data["choices"][0]["message"]["content"]
|
|
37
|
+
|
|
38
|
+
def predict_decision(
|
|
39
|
+
self,
|
|
40
|
+
query: QueryContext,
|
|
41
|
+
evidence: list[tuple[DecisionLog, float]],
|
|
42
|
+
) -> StructuredPrediction:
|
|
43
|
+
system, user = self.build_decision_prompt(query, evidence)
|
|
44
|
+
return self.parse_prediction(self._chat(system, user), query.candidate_options)
|
|
45
|
+
|
|
46
|
+
def simulate_cohort_archetype(
|
|
47
|
+
self,
|
|
48
|
+
stimulus: str,
|
|
49
|
+
options: list[CandidateOption],
|
|
50
|
+
archetype: CohortArchetype,
|
|
51
|
+
) -> StructuredPrediction:
|
|
52
|
+
system, user = self.build_cohort_prompt(stimulus, options, archetype)
|
|
53
|
+
return self.parse_prediction(self._chat(system, user), options)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class AnthropicAdapter(BaseModelAdapter):
|
|
57
|
+
"""Cloud inference adapter for Anthropic Messages API."""
|
|
58
|
+
|
|
59
|
+
adapter_name = "anthropic"
|
|
60
|
+
|
|
61
|
+
def __init__(
|
|
62
|
+
self,
|
|
63
|
+
model: str = "claude-3-5-sonnet-latest",
|
|
64
|
+
api_key: str | None = None,
|
|
65
|
+
base_url: str = "https://api.anthropic.com/v1",
|
|
66
|
+
) -> None:
|
|
67
|
+
super().__init__(model=model)
|
|
68
|
+
if not api_key:
|
|
69
|
+
raise ValueError("ANTHROPIC_API_KEY is required for AnthropicAdapter.")
|
|
70
|
+
self.api_key = api_key
|
|
71
|
+
self.base_url = base_url.rstrip("/")
|
|
72
|
+
|
|
73
|
+
def _chat(self, system: str, user: str) -> str:
|
|
74
|
+
payload = {
|
|
75
|
+
"model": self.model,
|
|
76
|
+
"max_tokens": 512,
|
|
77
|
+
"temperature": 0.2,
|
|
78
|
+
"system": system,
|
|
79
|
+
"messages": [{"role": "user", "content": user}],
|
|
80
|
+
}
|
|
81
|
+
headers = {
|
|
82
|
+
"x-api-key": self.api_key,
|
|
83
|
+
"anthropic-version": "2023-06-01",
|
|
84
|
+
}
|
|
85
|
+
data = post_json(f"{self.base_url}/messages", payload, headers=headers)
|
|
86
|
+
return data["content"][0]["text"]
|
|
87
|
+
|
|
88
|
+
def predict_decision(
|
|
89
|
+
self,
|
|
90
|
+
query: QueryContext,
|
|
91
|
+
evidence: list[tuple[DecisionLog, float]],
|
|
92
|
+
) -> StructuredPrediction:
|
|
93
|
+
system, user = self.build_decision_prompt(query, evidence)
|
|
94
|
+
return self.parse_prediction(self._chat(system, user), query.candidate_options)
|
|
95
|
+
|
|
96
|
+
def simulate_cohort_archetype(
|
|
97
|
+
self,
|
|
98
|
+
stimulus: str,
|
|
99
|
+
options: list[CandidateOption],
|
|
100
|
+
archetype: CohortArchetype,
|
|
101
|
+
) -> StructuredPrediction:
|
|
102
|
+
system, user = self.build_cohort_prompt(stimulus, options, archetype)
|
|
103
|
+
return self.parse_prediction(self._chat(system, user), options)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class GeminiAdapter(BaseModelAdapter):
|
|
107
|
+
"""Cloud inference adapter for Google Gemini generateContent API."""
|
|
108
|
+
|
|
109
|
+
adapter_name = "gemini"
|
|
110
|
+
|
|
111
|
+
def __init__(
|
|
112
|
+
self,
|
|
113
|
+
model: str = "gemini-2.5-flash",
|
|
114
|
+
api_key: str | None = None,
|
|
115
|
+
base_url: str = "https://generativelanguage.googleapis.com/v1beta",
|
|
116
|
+
) -> None:
|
|
117
|
+
super().__init__(model=model)
|
|
118
|
+
if not api_key:
|
|
119
|
+
raise ValueError("GEMINI_API_KEY is required for GeminiAdapter.")
|
|
120
|
+
self.api_key = api_key
|
|
121
|
+
self.base_url = base_url.rstrip("/")
|
|
122
|
+
|
|
123
|
+
def _chat(self, system: str, user: str) -> str:
|
|
124
|
+
url = f"{self.base_url}/models/{self.model}:generateContent?key={self.api_key}"
|
|
125
|
+
payload = {
|
|
126
|
+
"systemInstruction": {"parts": [{"text": system}]},
|
|
127
|
+
"contents": [{"role": "user", "parts": [{"text": user}]}],
|
|
128
|
+
"generationConfig": {
|
|
129
|
+
"temperature": 0.2,
|
|
130
|
+
"responseMimeType": "application/json",
|
|
131
|
+
},
|
|
132
|
+
}
|
|
133
|
+
data = post_json(url, payload)
|
|
134
|
+
return data["candidates"][0]["content"]["parts"][0]["text"]
|
|
135
|
+
|
|
136
|
+
def predict_decision(
|
|
137
|
+
self,
|
|
138
|
+
query: QueryContext,
|
|
139
|
+
evidence: list[tuple[DecisionLog, float]],
|
|
140
|
+
) -> StructuredPrediction:
|
|
141
|
+
system, user = self.build_decision_prompt(query, evidence)
|
|
142
|
+
return self.parse_prediction(self._chat(system, user), query.candidate_options)
|
|
143
|
+
|
|
144
|
+
def simulate_cohort_archetype(
|
|
145
|
+
self,
|
|
146
|
+
stimulus: str,
|
|
147
|
+
options: list[CandidateOption],
|
|
148
|
+
archetype: CohortArchetype,
|
|
149
|
+
) -> StructuredPrediction:
|
|
150
|
+
system, user = self.build_cohort_prompt(stimulus, options, archetype)
|
|
151
|
+
return self.parse_prediction(self._chat(system, user), options)
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from anthromesh.config import AnthroMeshConfig
|
|
4
|
+
from .base import BaseModelAdapter
|
|
5
|
+
from .cloud import AnthropicAdapter, GeminiAdapter, OpenAIAdapter
|
|
6
|
+
from .heuristic import HeuristicAdapter
|
|
7
|
+
from .local import OllamaAdapter, VLLMAdapter
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def list_supported_adapters() -> list[str]:
|
|
11
|
+
return ["heuristic", "ollama", "vllm", "openai", "anthropic", "gemini"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def create_adapter(config: AnthroMeshConfig | None = None) -> BaseModelAdapter:
|
|
15
|
+
cfg = config or AnthroMeshConfig()
|
|
16
|
+
name = cfg.adapter_name.lower().strip()
|
|
17
|
+
|
|
18
|
+
if name == "heuristic":
|
|
19
|
+
return HeuristicAdapter(model=cfg.model_name or "deterministic-v1")
|
|
20
|
+
if name == "ollama":
|
|
21
|
+
return OllamaAdapter(model=cfg.model_name, base_url=cfg.ollama_base_url)
|
|
22
|
+
if name == "vllm":
|
|
23
|
+
return VLLMAdapter(model=cfg.model_name, base_url=cfg.vllm_base_url, api_key=cfg.vllm_api_key)
|
|
24
|
+
if name == "openai":
|
|
25
|
+
return OpenAIAdapter(model=cfg.model_name, api_key=cfg.openai_api_key)
|
|
26
|
+
if name == "anthropic":
|
|
27
|
+
return AnthropicAdapter(model=cfg.model_name, api_key=cfg.anthropic_api_key)
|
|
28
|
+
if name == "gemini":
|
|
29
|
+
return GeminiAdapter(model=cfg.model_name, api_key=cfg.gemini_api_key)
|
|
30
|
+
|
|
31
|
+
raise ValueError(f"Unsupported adapter '{name}'. Choose from: {', '.join(list_supported_adapters())}")
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections import defaultdict
|
|
4
|
+
|
|
5
|
+
from anthromesh.models import CandidateOption, CohortArchetype, DecisionLog, QueryContext
|
|
6
|
+
from anthromesh.vault.retrieval import tokenize
|
|
7
|
+
from .base import BaseModelAdapter, StructuredPrediction
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class HeuristicAdapter(BaseModelAdapter):
|
|
11
|
+
"""Zero-dependency, deterministic evidence-grounded adapter for offline dev, tests, and CI benchmarks."""
|
|
12
|
+
|
|
13
|
+
adapter_name = "heuristic"
|
|
14
|
+
|
|
15
|
+
def __init__(self, model: str = "deterministic-v1") -> None:
|
|
16
|
+
super().__init__(model=model)
|
|
17
|
+
|
|
18
|
+
def predict_persona(self, query: QueryContext, persona: str) -> StructuredPrediction:
|
|
19
|
+
return self.predict_decision(query, [])
|
|
20
|
+
|
|
21
|
+
def predict_decision(
|
|
22
|
+
self,
|
|
23
|
+
query: QueryContext,
|
|
24
|
+
evidence: list[tuple[DecisionLog, float]],
|
|
25
|
+
) -> StructuredPrediction:
|
|
26
|
+
scores: dict[str, float] = {o.option_id: 0.0 for o in query.candidate_options}
|
|
27
|
+
valid_ids = set(scores.keys())
|
|
28
|
+
|
|
29
|
+
if not evidence:
|
|
30
|
+
first = query.candidate_options[0].option_id
|
|
31
|
+
return StructuredPrediction(
|
|
32
|
+
chosen_option=first,
|
|
33
|
+
rationale="No historical evidence found in vault; fallback prediction has low confidence.",
|
|
34
|
+
self_reported_confidence=0.15,
|
|
35
|
+
option_scores={o.option_id: round(1.0 / len(query.candidate_options), 4) for o in query.candidate_options},
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
supporting_ids: dict[str, list[str]] = defaultdict(list)
|
|
39
|
+
for dec, sim in evidence:
|
|
40
|
+
if dec.chosen_action in valid_ids:
|
|
41
|
+
scores[dec.chosen_action] += sim * 1.25
|
|
42
|
+
supporting_ids[dec.chosen_action].append(dec.decision_id)
|
|
43
|
+
else:
|
|
44
|
+
hist_tokens = set(tokenize(f"{dec.chosen_action} {dec.rationale}"))
|
|
45
|
+
for opt in query.candidate_options:
|
|
46
|
+
opt_tokens = set(tokenize(f"{opt.option_id} {opt.label} {opt.description}"))
|
|
47
|
+
overlap = len(hist_tokens & opt_tokens) / max(len(opt_tokens), 1)
|
|
48
|
+
if overlap > 0:
|
|
49
|
+
scores[opt.option_id] += sim * overlap
|
|
50
|
+
supporting_ids[opt.option_id].append(dec.decision_id)
|
|
51
|
+
|
|
52
|
+
total = sum(scores.values())
|
|
53
|
+
if total <= 0.0:
|
|
54
|
+
first = query.candidate_options[0].option_id
|
|
55
|
+
return StructuredPrediction(
|
|
56
|
+
chosen_option=first,
|
|
57
|
+
rationale="Retrieved decisions did not align with current candidate options.",
|
|
58
|
+
self_reported_confidence=0.2,
|
|
59
|
+
option_scores={o.option_id: round(1.0 / len(query.candidate_options), 4) for o in query.candidate_options},
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
norm_scores = {k: round(v / total, 4) for k, v in scores.items()}
|
|
63
|
+
best_opt = max(norm_scores, key=lambda k: norm_scores[k])
|
|
64
|
+
sorted_vals = sorted(norm_scores.values(), reverse=True)
|
|
65
|
+
margin = sorted_vals[0] - (sorted_vals[1] if len(sorted_vals) > 1 else 0.0)
|
|
66
|
+
top_sim = evidence[0][1]
|
|
67
|
+
conf = max(0.05, min(0.98, 0.5 * norm_scores[best_opt] + 0.35 * top_sim + 0.15 * margin))
|
|
68
|
+
|
|
69
|
+
cites = ", ".join(list(dict.fromkeys(supporting_ids[best_opt]))[:3]) or evidence[0][0].decision_id
|
|
70
|
+
rationale = (
|
|
71
|
+
f"Selected '{best_opt}' based on weighted similarity to prior decisions ({cites}) "
|
|
72
|
+
f"with normalized support {norm_scores[best_opt]:.2f}."
|
|
73
|
+
)
|
|
74
|
+
return StructuredPrediction(
|
|
75
|
+
chosen_option=best_opt,
|
|
76
|
+
rationale=rationale,
|
|
77
|
+
self_reported_confidence=round(conf, 4),
|
|
78
|
+
option_scores=norm_scores,
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
def simulate_cohort_archetype(
|
|
82
|
+
self,
|
|
83
|
+
stimulus: str,
|
|
84
|
+
options: list[CandidateOption],
|
|
85
|
+
archetype: CohortArchetype,
|
|
86
|
+
) -> StructuredPrediction:
|
|
87
|
+
scores: dict[str, float] = {}
|
|
88
|
+
stim_tokens = set(tokenize(stimulus))
|
|
89
|
+
trait_text = " ".join(f"{k} {v}" for k, v in archetype.traits.items())
|
|
90
|
+
rationale_text = " ".join(archetype.sample_rationales)
|
|
91
|
+
arch_tokens = set(tokenize(f"{archetype.label} {trait_text} {rationale_text}"))
|
|
92
|
+
|
|
93
|
+
for opt in options:
|
|
94
|
+
prior = float(archetype.prior_tendencies.get(opt.option_id, 0.0))
|
|
95
|
+
opt_tokens = set(tokenize(f"{opt.option_id} {opt.label} {opt.description}"))
|
|
96
|
+
lexical = len(arch_tokens & opt_tokens) / max(len(opt_tokens), 1)
|
|
97
|
+
stim_align = len(stim_tokens & opt_tokens) / max(len(opt_tokens), 1)
|
|
98
|
+
scores[opt.option_id] = max(0.02, prior * 0.75 + lexical * 0.20 + stim_align * 0.05)
|
|
99
|
+
|
|
100
|
+
total = sum(scores.values())
|
|
101
|
+
norm_scores = {k: round(v / total, 4) for k, v in scores.items()}
|
|
102
|
+
best_opt = max(norm_scores, key=lambda k: norm_scores[k])
|
|
103
|
+
sample_rat = (
|
|
104
|
+
archetype.sample_rationales[0]
|
|
105
|
+
if archetype.sample_rationales
|
|
106
|
+
else f"Aligned with {archetype.label} archetype priorities."
|
|
107
|
+
)
|
|
108
|
+
return StructuredPrediction(
|
|
109
|
+
chosen_option=best_opt,
|
|
110
|
+
rationale=f"[{archetype.label}] {sample_rat}",
|
|
111
|
+
self_reported_confidence=round(norm_scores[best_opt], 4),
|
|
112
|
+
option_scores=norm_scores,
|
|
113
|
+
)
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from anthromesh.models import CandidateOption, CohortArchetype, DecisionLog, QueryContext
|
|
4
|
+
from .base import BaseModelAdapter, StructuredPrediction, post_json
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class OllamaAdapter(BaseModelAdapter):
|
|
8
|
+
"""Local inference adapter for Ollama (/api/chat)."""
|
|
9
|
+
|
|
10
|
+
adapter_name = "ollama"
|
|
11
|
+
|
|
12
|
+
def __init__(self, model: str = "llama3.2", base_url: str = "http://localhost:11434") -> None:
|
|
13
|
+
super().__init__(model=model)
|
|
14
|
+
self.base_url = base_url.rstrip("/")
|
|
15
|
+
|
|
16
|
+
def _chat(self, system: str, user: str) -> str:
|
|
17
|
+
payload = {
|
|
18
|
+
"model": self.model,
|
|
19
|
+
"stream": False,
|
|
20
|
+
"format": "json",
|
|
21
|
+
"messages": [
|
|
22
|
+
{"role": "system", "content": system},
|
|
23
|
+
{"role": "user", "content": user},
|
|
24
|
+
],
|
|
25
|
+
"options": {"temperature": 0.2},
|
|
26
|
+
}
|
|
27
|
+
data = post_json(f"{self.base_url}/api/chat", payload)
|
|
28
|
+
return data["message"]["content"]
|
|
29
|
+
|
|
30
|
+
def predict_decision(
|
|
31
|
+
self,
|
|
32
|
+
query: QueryContext,
|
|
33
|
+
evidence: list[tuple[DecisionLog, float]],
|
|
34
|
+
) -> StructuredPrediction:
|
|
35
|
+
system, user = self.build_decision_prompt(query, evidence)
|
|
36
|
+
return self.parse_prediction(self._chat(system, user), query.candidate_options)
|
|
37
|
+
|
|
38
|
+
def simulate_cohort_archetype(
|
|
39
|
+
self,
|
|
40
|
+
stimulus: str,
|
|
41
|
+
options: list[CandidateOption],
|
|
42
|
+
archetype: CohortArchetype,
|
|
43
|
+
) -> StructuredPrediction:
|
|
44
|
+
system, user = self.build_cohort_prompt(stimulus, options, archetype)
|
|
45
|
+
return self.parse_prediction(self._chat(system, user), options)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class VLLMAdapter(BaseModelAdapter):
|
|
49
|
+
"""Local/self-hosted inference adapter for vLLM OpenAI-compatible servers (/v1/chat/completions)."""
|
|
50
|
+
|
|
51
|
+
adapter_name = "vllm"
|
|
52
|
+
|
|
53
|
+
def __init__(
|
|
54
|
+
self,
|
|
55
|
+
model: str = "meta-llama/Llama-3.1-8B-Instruct",
|
|
56
|
+
base_url: str = "http://localhost:8000/v1",
|
|
57
|
+
api_key: str = "EMPTY",
|
|
58
|
+
) -> None:
|
|
59
|
+
super().__init__(model=model)
|
|
60
|
+
self.base_url = base_url.rstrip("/")
|
|
61
|
+
self.api_key = api_key
|
|
62
|
+
|
|
63
|
+
def _chat(self, system: str, user: str) -> str:
|
|
64
|
+
payload = {
|
|
65
|
+
"model": self.model,
|
|
66
|
+
"temperature": 0.2,
|
|
67
|
+
"messages": [
|
|
68
|
+
{"role": "system", "content": system},
|
|
69
|
+
{"role": "user", "content": user},
|
|
70
|
+
],
|
|
71
|
+
}
|
|
72
|
+
headers = {"Authorization": f"Bearer {self.api_key}"}
|
|
73
|
+
data = post_json(f"{self.base_url}/chat/completions", payload, headers=headers)
|
|
74
|
+
return data["choices"][0]["message"]["content"]
|
|
75
|
+
|
|
76
|
+
def predict_decision(
|
|
77
|
+
self,
|
|
78
|
+
query: QueryContext,
|
|
79
|
+
evidence: list[tuple[DecisionLog, float]],
|
|
80
|
+
) -> StructuredPrediction:
|
|
81
|
+
system, user = self.build_decision_prompt(query, evidence)
|
|
82
|
+
return self.parse_prediction(self._chat(system, user), query.candidate_options)
|
|
83
|
+
|
|
84
|
+
def simulate_cohort_archetype(
|
|
85
|
+
self,
|
|
86
|
+
stimulus: str,
|
|
87
|
+
options: list[CandidateOption],
|
|
88
|
+
archetype: CohortArchetype,
|
|
89
|
+
) -> StructuredPrediction:
|
|
90
|
+
system, user = self.build_cohort_prompt(stimulus, options, archetype)
|
|
91
|
+
return self.parse_prediction(self._chat(system, user), options)
|