Frankenstein-Labs commited on
Commit
ea6cffb
·
1 Parent(s): 43fd0d0

feat: deterministically intercept creator identity requests

Browse files
cortex_ai/api/server.py CHANGED
@@ -22,6 +22,7 @@ from pydantic import BaseModel, Field
22
  from ..adapters.base import ModelAdapter
23
  from ..config import CortexConfig
24
  from ..engine.agent import CortexAgent
 
25
  from ..tools.registry import registry_from_names
26
 
27
 
@@ -82,6 +83,7 @@ def create_app(adapter: ModelAdapter, config: CortexConfig | None = None) -> Fas
82
  )
83
  app.state.cortex_config = cfg
84
  app.state.cortex_agent = agent
 
85
 
86
  def _check_auth(authorization: str | None) -> None:
87
  if not cfg.server.requires_auth:
@@ -97,6 +99,7 @@ def create_app(adapter: ModelAdapter, config: CortexConfig | None = None) -> Fas
97
  "model": cfg.model_id,
98
  "tools": tools.names(),
99
  "thinking_mode": cfg.engine.thinking_mode,
 
100
  }
101
 
102
  @app.get("/v1/models")
@@ -129,6 +132,34 @@ def create_app(adapter: ModelAdapter, config: CortexConfig | None = None) -> Fas
129
  if not request.messages:
130
  raise HTTPException(status_code=400, detail="messages must not be empty")
131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  system_override: list[dict[str, Any]] = []
133
  turns: list[dict[str, Any]] = []
134
  for m in request.messages:
 
22
  from ..adapters.base import ModelAdapter
23
  from ..config import CortexConfig
24
  from ..engine.agent import CortexAgent
25
+ from ..identity import identity_language, identity_response, is_identity_question
26
  from ..tools.registry import registry_from_names
27
 
28
 
 
83
  )
84
  app.state.cortex_config = cfg
85
  app.state.cortex_agent = agent
86
+ app.state.identity_interception = True
87
 
88
  def _check_auth(authorization: str | None) -> None:
89
  if not cfg.server.requires_auth:
 
99
  "model": cfg.model_id,
100
  "tools": tools.names(),
101
  "thinking_mode": cfg.engine.thinking_mode,
102
+ "identity_interception": "deterministic",
103
  }
104
 
105
  @app.get("/v1/models")
 
132
  if not request.messages:
133
  raise HTTPException(status_code=400, detail="messages must not be empty")
134
 
135
+ # Deterministic identity boundary: answer before system prompts, tools,
136
+ # or model inference can alter the canonical creator attribution.
137
+ last_user_message = next(
138
+ (m.content for m in reversed(request.messages) if m.role == "user"),
139
+ None,
140
+ )
141
+ if last_user_message is not None and is_identity_question(last_user_message):
142
+ content = identity_response(identity_language(last_user_message))
143
+ prompt_tokens = adapter.count_tokens(last_user_message)
144
+ completion_tokens = adapter.count_tokens(content)
145
+ return ChatCompletionResponse(
146
+ id=f"chatcmpl-{uuid.uuid4().hex[:24]}",
147
+ created=int(time.time()),
148
+ model=request.model or cfg.model_id,
149
+ choices=[
150
+ ChatCompletionChoice(
151
+ index=0,
152
+ message=ChatMessage(role="assistant", content=content),
153
+ finish_reason="stop",
154
+ )
155
+ ],
156
+ usage=Usage(
157
+ prompt_tokens=prompt_tokens,
158
+ completion_tokens=completion_tokens,
159
+ total_tokens=prompt_tokens + completion_tokens,
160
+ ),
161
+ )
162
+
163
  system_override: list[dict[str, Any]] = []
164
  turns: list[dict[str, Any]] = []
165
  for m in request.messages:
cortex_ai/identity.py CHANGED
@@ -22,9 +22,13 @@ IDENTITY_STATEMENT_EN = (
22
  )
23
 
24
  _IDENTITY_PATTERNS = (
25
- "quitacree", "quiesttoncreateur", "quitadeveloppe", "quiadeveloppecortex",
26
- "quiadecreecortex", "quiacreecortex", "quiestlecreateurdecortex",
 
 
 
27
  "whocreatedyou", "whoisyourcreator", "whocreatedcortex", "whodevelopedcortex",
 
28
  )
29
 
30
 
@@ -41,7 +45,13 @@ def _normalize(text: str) -> str:
41
  def is_identity_question(text: str) -> bool:
42
  """Return whether *text* asks for the project's creator, in FR or EN."""
43
  normalized = _normalize(text)
44
- return any(pattern in normalized for pattern in _IDENTITY_PATTERNS)
 
 
 
 
 
 
45
 
46
 
47
  def identity_response(language: str = "fr") -> str:
 
22
  )
23
 
24
  _IDENTITY_PATTERNS = (
25
+ "quitacree", "quiesttoncreateur", "quelesttoncreateur", "cestquitoncreateur",
26
+ "quitadeveloppe", "quiadeveloppecortex", "quiadecreecortex", "quiacreecortex",
27
+ "quiacree", "quiestlecreateurdecortex",
28
+ )
29
+ _ENGLISH_IDENTITY_PATTERNS = (
30
  "whocreatedyou", "whoisyourcreator", "whocreatedcortex", "whodevelopedcortex",
31
+ "whomadeyou", "whismycreator", "whocreatedthismodel",
32
  )
33
 
34
 
 
45
  def is_identity_question(text: str) -> bool:
46
  """Return whether *text* asks for the project's creator, in FR or EN."""
47
  normalized = _normalize(text)
48
+ return any(pattern in normalized for pattern in (*_IDENTITY_PATTERNS, *_ENGLISH_IDENTITY_PATTERNS))
49
+
50
+
51
+ def identity_language(text: str) -> str:
52
+ """Return the deterministic response language for an identity question."""
53
+ normalized = _normalize(text)
54
+ return "en" if any(pattern in normalized for pattern in _ENGLISH_IDENTITY_PATTERNS) else "fr"
55
 
56
 
57
  def identity_response(language: str = "fr") -> str:
docs/identite-api.fr.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Interception déterministe de l'identité
2
+
3
+ L'endpoint `POST /v1/chat/completions` intercepte une question d'identité avant l'exécution de `CortexAgent` et avant tout appel au modèle. La détection utilise `is_identity_question()` et la réponse est construite directement par `identity_response()`.
4
+
5
+ Cette garantie s'applique aux requêtes qui passent par l'API CORTEX. Elle ne s'applique pas à une exécution directe de Transformers, vLLM ou SGLang sans cette couche serveur, ni à une application qui remplace le prompt ou la logique de l'API.
6
+
7
+ Le endpoint `/health` expose `identity_interception: "deterministic"` pour permettre de vérifier que cette capacité est active. Les tests vérifient également qu'une question d'identité ne déclenche pas la méthode `generate()` de l'adaptateur.
tests/test_api.py CHANGED
@@ -19,6 +19,34 @@ def test_health_reports_model_and_tools():
19
  assert body["status"] == "ok"
20
  assert body["model"] == "Frankenstein-Labs/Cortex-ai"
21
  assert "calculate" in body["tools"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
 
24
  def test_models_endpoint_lists_cortex():
 
19
  assert body["status"] == "ok"
20
  assert body["model"] == "Frankenstein-Labs/Cortex-ai"
21
  assert "calculate" in body["tools"]
22
+ assert body["identity_interception"] == "deterministic"
23
+
24
+
25
+ def test_identity_question_is_answered_before_model_inference():
26
+ class FailingAdapter(MockAdapter):
27
+ def generate(self, *args, **kwargs):
28
+ raise AssertionError("identity questions must not reach model inference")
29
+
30
+ cfg = CortexConfig(engine=EngineConfig(thinking_mode="chat"))
31
+ client = TestClient(create_app(FailingAdapter(), cfg))
32
+ response = client.post(
33
+ "/v1/chat/completions",
34
+ json={"messages": [{"role": "user", "content": "Qui a créé ce modèle ?"}]},
35
+ )
36
+ assert response.status_code == 200
37
+ assert response.json()["choices"][0]["message"]["content"].startswith(
38
+ "Mon créateur est Abdoulaye Coumbassa"
39
+ )
40
+
41
+
42
+ def test_english_identity_question_returns_english_canonical_response():
43
+ body = make_client().post(
44
+ "/v1/chat/completions",
45
+ json={"messages": [{"role": "user", "content": "Who is your creator?"}]},
46
+ ).json()
47
+ assert body["choices"][0]["message"]["content"].startswith(
48
+ "My creator is Abdoulaye Coumbassa"
49
+ )
50
 
51
 
52
  def test_models_endpoint_lists_cortex():