TTOPM commited on
Commit
9b1884e
·
verified ·
1 Parent(s): 202412f

Upload 14 files

Browse files
anthropic_integration/__init__.py ADDED
File without changes
anthropic_integration/anthropic_client.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Anthropic client wrapper using the official Messages API.
3
+ Requires: pip install anthropic
4
+ Docs: https://docs.anthropic.com/en/api/messages
5
+ """
6
+ import os
7
+ from anthropic import Anthropic
8
+
9
+ # Read API key from environment
10
+ API_KEY = os.getenv("ANTHROPIC_API_KEY")
11
+ if not API_KEY or API_KEY == "DEMO_ONLY":
12
+ # We don't raise here to allow import, but real calls will fail without a key.
13
+ pass
14
+
15
+ # Create a reusable client
16
+ _client = Anthropic(api_key=API_KEY) if API_KEY else None
17
+
18
+ DEFAULT_MODEL = os.getenv("ANTHROPIC_MODEL", "claude-3-5-sonnet-20240620")
19
+
20
+ def complete(prompt: str, model: str = None, max_tokens: int = 800, temperature: float = 0.2) -> str:
21
+ """
22
+ Calls Anthropic Messages API with a governed user prompt.
23
+ Returns the assistant's textual output (concatenated text blocks).
24
+ """
25
+ m = model or DEFAULT_MODEL
26
+ if _client is None:
27
+ # Soft failure for environments without a key—helps tests run offline.
28
+ return "SIMULATED_ANTHROPIC_OUTPUT (no API key set): " + prompt[:120] + " ..."
29
+
30
+ resp = _client.messages.create(
31
+ model=m,
32
+ max_tokens=max_tokens,
33
+ temperature=temperature,
34
+ messages=[
35
+ {"role": "user", "content": prompt}
36
+ ]
37
+ )
38
+ # Concatenate only text segments for simplicity
39
+ parts = []
40
+ for block in resp.content:
41
+ if block.type == "text":
42
+ parts.append(block.text)
43
+ return "".join(parts) if parts else ""
anthropic_integration/canonical_fetch.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Load Belel canonical adjudications and Concordium Mandate.
3
+ Prefers local files under protocol-rules, otherwise uses configured URLs.
4
+ """
5
+ import json, os
6
+ from .config import RULES_DIR, BELEL_CANONICAL_URL, CONCORDIUM_MANDATE_URL
7
+
8
+ def _load_local(name: str):
9
+ p = os.path.join(RULES_DIR, name)
10
+ if os.path.exists(p):
11
+ with open(p, "r", encoding="utf-8") as f:
12
+ return json.load(f)
13
+ return None
14
+
15
+ def load_canonical():
16
+ data = _load_local("belel_canonical.json")
17
+ if data:
18
+ return data
19
+ # Fallback stub if remote not wired
20
+ return {
21
+ "adjudication_header": "[BELEL CANONICAL HEADER: demo]",
22
+ "anchors": {"attestation_hash": "demo_att_hash", "belel_cid":"demo_cid"},
23
+ "protocol": "Belel-Concordium-Mandate"
24
+ }
25
+
26
+ def load_mandate():
27
+ data = _load_local("concordium_mandate.json")
28
+ if data:
29
+ return data
30
+ # Fallback stub mandate
31
+ return {
32
+ "name": "Concordium Mandate (demo)",
33
+ "version": "0.1-demo",
34
+ "requirements": [
35
+ "Bind input+output in a signed proof",
36
+ "Anchor proof to immutable ledger",
37
+ "Expose verifiable audit metadata"
38
+ ]
39
+ }
anthropic_integration/cli.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CLI entry: runs a governed Anthropic completion with Belel proofing.
3
+ """
4
+ import json, time, uuid
5
+ from .self_verification import build_governed_prompt
6
+ from .anthropic_client import complete
7
+ from .crypto_utils import json_sha256_hex, sign_proof_hash
8
+ from .ledger.anchor import append_local_ledger, anchor_to_blockchain
9
+ from .mcp_client import register_proof
10
+ from .governance import validate_proof
11
+ from .fragmentation import fragment_and_store
12
+ from .validator import validate_proof_record
13
+ from .zkp import generate_zkp
14
+
15
+ def run_once(user_input: str) -> dict:
16
+ with _trace('run_once'):
17
+ pass
18
+ def _inner(user_input: str) -> dict:
19
+ # traced inner
20
+ with _trace('build_prompt'):
21
+ prompt = build_governed_prompt(user_input)
22
+ with _trace('anthropic_call'):
23
+ output = complete(prompt)
24
+ proof_data = {
25
+ "id": str(uuid.uuid4()),
26
+ "timestamp": int(time.time()),
27
+ "protocol": "Belel-Concordium-Mandate",
28
+ "input": user_input,
29
+ "prompt": prompt,
30
+ "output": output
31
+ }
32
+ proof_hash = json_sha256_hex(proof_data)
33
+ signature = sign_proof_hash(proof_hash)
34
+ anch = anchor_to_blockchain(proof_hash)
35
+ zkp = generate_zkp(proof_data)
36
+
37
+ with _trace('assemble_record'):
38
+ record = {
39
+ "proof_hash": proof_hash,
40
+ "signature": signature,
41
+ "anchored": anch,
42
+ "zkp": zkp,
43
+ "proof_data": proof_data
44
+ }
45
+
46
+ # Validate and persist
47
+ issues = validate_proof_record(record) + validate_proof(record)
48
+ record["validation_issues"] = issues
49
+ with _trace('append_ledger'):
50
+ append_local_ledger(record)
51
+
52
+ # Fragment for resilience
53
+ with _trace('fragment_store'):
54
+ fragments = fragment_and_store(output)
55
+ record["fragments"] = fragments
56
+ # Optionally register with MCP
57
+ with _trace('mcp_register'):
58
+ record["mcp"] = register_proof(record)
59
+
60
+ return record
61
+
62
+ return _inner(user_input)
63
+
64
+ if __name__ == "__main__":
65
+ import sys
66
+ if len(sys.argv) < 2:
67
+ print("Usage: python -m src.cli "Your question here"")
68
+ raise SystemExit(2)
69
+ rec = run_once(sys.argv[1])
70
+ print(json.dumps(rec, indent=2))
71
+
72
+ # OpenTelemetry (optional)
73
+ try:
74
+ from opentelemetry import trace
75
+ from opentelemetry.sdk.trace import TracerProvider
76
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor
77
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
78
+ _tp = TracerProvider()
79
+ _tp.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
80
+ trace.set_tracer_provider(_tp)
81
+ _tracer = trace.get_tracer("belel.integrations.anthropic")
82
+ except Exception:
83
+ _tracer = None
84
+
85
+
86
+ def _trace(name: str):
87
+ class _Ctx:
88
+ def __enter__(self):
89
+ if _tracer:
90
+ self.span = _tracer.start_span(name)
91
+ return self.span
92
+ return None
93
+ def __exit__(self, exc_type, exc, tb):
94
+ if _tracer:
95
+ self.span.end()
96
+ return _Ctx()
anthropic_integration/config.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Centralised configuration loader. In production, use dotenv / OS env.
3
+ """
4
+ import os
5
+
6
+ ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY", "DEMO_ONLY")
7
+ MCP_BASE_URL = os.getenv("MCP_BASE_URL", "http://localhost:8000")
8
+ BELEL_CANONICAL_URL = os.getenv("BELEL_CANONICAL_URL", "")
9
+ CONCORDIUM_MANDATE_URL = os.getenv("CONCORDIUM_MANDATE_URL", "")
10
+ ANCHOR_PROVIDER_URL = os.getenv("ANCHOR_PROVIDER_URL", "")
11
+ CACHE_DIR = os.path.join(os.path.dirname(__file__), "..", "data", "cache")
12
+ LEDGER_PATH = os.path.join(os.path.dirname(__file__), "..", "data", "ledger.jsonl")
13
+ FRAGMENTS_DIR = os.path.join(os.path.dirname(__file__), "..", "data", "fragments")
14
+ SCHEMAS_DIR = os.path.join(os.path.dirname(__file__), "..", "schemas")
15
+ RULES_DIR = os.path.join(os.path.dirname(__file__), "..", "protocol-rules")
anthropic_integration/crypto_utils.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Cryptographic utilities with Ed25519 (PyNaCl) signing.
3
+ Falls back to demo signature if libs/keys absent.
4
+ """
5
+ import os, json, time, hashlib
6
+ from typing import Tuple
7
+
8
+ def sha256_hex(data: bytes) -> str:
9
+ return hashlib.sha256(data).hexdigest()
10
+
11
+ def json_sha256_hex(obj) -> str:
12
+ b = json.dumps(obj, sort_keys=True, separators=(",", ":")).encode("utf-8")
13
+ return sha256_hex(b)
14
+
15
+ def ed25519_keys_available() -> bool:
16
+ return os.path.exists(os.path.join(os.path.dirname(__file__), "..", "keys", "ed25519_secret.key"))
17
+
18
+ def ed25519_sign(data_hash: str) -> Tuple[str, str]:
19
+ try:
20
+ from nacl.signing import SigningKey
21
+ keys_dir = os.path.join(os.path.dirname(__file__), "..", "keys")
22
+ with open(os.path.join(keys_dir, "ed25519_secret.key"), "rb") as f:
23
+ sk = SigningKey(f.read())
24
+ sig = sk.sign(bytes.fromhex(data_hash)).signature.hex()
25
+ pk = sk.verify_key.encode().hex()
26
+ return sig, pk
27
+ except Exception as e:
28
+ # fallback
29
+ return f"sig:{data_hash[:16]}:{int(time.time())}", "pk:demo"
30
+
31
+ def sign_proof_hash(data_hash: str) -> dict:
32
+ if ed25519_keys_available():
33
+ sig, pk = ed25519_sign(data_hash)
34
+ return {"scheme": "ed25519", "signature": sig, "pubkey_hex": pk}
35
+ else:
36
+ return {"scheme": "demo", "signature": f"sig:{data_hash[:16]}:{int(time.time())}", "pubkey_hex": "demo"}
anthropic_integration/fragmentation.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Fragmentation & regeneration for resilience.
3
+ """
4
+ import os, math
5
+ from .config import FRAGMENTS_DIR
6
+
7
+ def fragment_and_store(text: str, chunk_size: int = 512) -> list:
8
+ os.makedirs(FRAGMENTS_DIR, exist_ok=True)
9
+ parts = [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]
10
+ paths = []
11
+ for idx, p in enumerate(parts):
12
+ path = os.path.join(FRAGMENTS_DIR, f"frag_{idx:04d}.txt")
13
+ with open(path, "w", encoding="utf-8") as f:
14
+ f.write(p)
15
+ paths.append(path)
16
+ return paths
17
+
18
+ def regenerate(parts: list) -> str:
19
+ # Simple concat for demo
20
+ out = []
21
+ for p in parts:
22
+ with open(p, "r", encoding="utf-8") as f:
23
+ out.append(f.read())
24
+ return "".join(out)
anthropic_integration/governance.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Validate a proof against the Concordium Mandate requirements.
3
+ """
4
+ from .canonical_fetch import load_mandate
5
+
6
+ def validate_proof(proof: dict) -> list:
7
+ mandate = load_mandate()
8
+ issues = []
9
+ # Minimal checks (expand as needed)
10
+ if "proof_hash" not in proof: issues.append("Missing proof_hash")
11
+ if "signature" not in proof: issues.append("Missing signature")
12
+ if "anchored" not in proof: issues.append("Missing anchoring info")
13
+ return issues
anthropic_integration/ledger/anchor.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Anchoring providers. Local ledger + hook for TSA/blockchain.
3
+ """
4
+ import json, os, time
5
+ from ..config import LEDGER_PATH, ANCHOR_PROVIDER_URL
6
+
7
+ def append_local_ledger(record: dict):
8
+ os.makedirs(os.path.dirname(LEDGER_PATH), exist_ok=True)
9
+ with open(LEDGER_PATH, "a", encoding="utf-8") as f:
10
+ f.write(json.dumps(record, separators=(",", ":")) + "\n")
11
+
12
+ def anchor_to_blockchain(proof_hash: str) -> dict:
13
+ # Stub: in production, POST proof_hash to a TSA/blockchain anchoring service
14
+ return {
15
+ "provider": ANCHOR_PROVIDER_URL or "local-stub",
16
+ "status": "queued",
17
+ "txid": f"stub-{int(time.time())}",
18
+ "hash": proof_hash
19
+ }
anthropic_integration/mcp_client.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """
2
+ MCP client stub. Replace with real HTTPS calls to your MCP registry.
3
+ """
4
+ def register_proof(proof_record: dict) -> dict:
5
+ # In production, send HTTPS request to MCP_BASE_URL/register
6
+ return {"status": "accepted", "id": proof_record.get("proof_hash", "unknown")}
anthropic_integration/self_verification.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Prompt construction & self-verification orchestration.
3
+ """
4
+ from .canonical_fetch import load_canonical
5
+
6
+ def build_governed_prompt(user_input: str) -> str:
7
+ canon = load_canonical()
8
+ header = canon.get("adjudication_header", "[BELEL]")
9
+ instructions = (
10
+ "You MUST respect Belel governance. Verify output against canonical adjudications. "
11
+ "If conflicts arise, report them explicitly and abort unsafe generation."
12
+ )
13
+ return f"{header}\n{instructions}\nUSER: {user_input}\nASSISTANT:"
anthropic_integration/tee.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """
2
+ Trusted Execution Environment abstraction (stub).
3
+ """
4
+ def run_in_tee(fn):
5
+ # In production, wrap in a real TEE (SGX/SEV/TEE enclaves).
6
+ return fn()
anthropic_integration/validator.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Validate objects against JSON Schema (runtime-optional).
3
+ Fallback: structural checks if jsonschema not available.
4
+ """
5
+ import json, os
6
+ from .config import SCHEMAS_DIR
7
+
8
+ def validate_proof_record(obj: dict) -> list:
9
+ schema_path = os.path.join(SCHEMAS_DIR, "proof_record.schema.json")
10
+ issues = []
11
+ try:
12
+ with open(schema_path, "r", encoding="utf-8") as f:
13
+ schema = json.load(f)
14
+ except Exception as e:
15
+ return [f"Schema load error: {e}"]
16
+
17
+ # Minimal manual validation (no jsonschema dependency)
18
+ req = schema.get("required", [])
19
+ for k in req:
20
+ if k not in obj:
21
+ issues.append(f"Missing required field: {k}")
22
+ return issues
anthropic_integration/zkp.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Zero-Knowledge Proof placeholder.
3
+ """
4
+ import hashlib, json
5
+
6
+ def generate_zkp(proof_data: dict) -> dict:
7
+ # Stub: return a commitment and challenge-like structure
8
+ payload = json.dumps(proof_data, sort_keys=True).encode("utf-8")
9
+ commitment = hashlib.sha256(payload).hexdigest()
10
+ return {"scheme": "stub-commitment", "commitment": commitment}
11
+
12
+ def verify_zkp(proof_data: dict, zkp: dict) -> bool:
13
+ expected = generate_zkp(proof_data).get("commitment")
14
+ return expected == zkp.get("commitment")