cloxy 5.2__tar.gz → 5.3__tar.gz

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.
Files changed (36) hide show
  1. {cloxy-5.2 → cloxy-5.3}/PKG-INFO +22 -2
  2. {cloxy-5.2 → cloxy-5.3}/README.md +21 -1
  3. {cloxy-5.2 → cloxy-5.3}/cloxy/__init__.py +1 -1
  4. {cloxy-5.2 → cloxy-5.3}/cloxy/config.py +8 -0
  5. {cloxy-5.2 → cloxy-5.3}/cloxy/server.py +157 -18
  6. {cloxy-5.2 → cloxy-5.3}/cloxy.egg-info/PKG-INFO +22 -2
  7. {cloxy-5.2 → cloxy-5.3}/tests/test_endpoints.py +77 -0
  8. {cloxy-5.2 → cloxy-5.3}/LICENSE +0 -0
  9. {cloxy-5.2 → cloxy-5.3}/cloxy/__main__.py +0 -0
  10. {cloxy-5.2 → cloxy-5.3}/cloxy/backends/__init__.py +0 -0
  11. {cloxy-5.2 → cloxy-5.3}/cloxy/backends/mlx_backend.py +0 -0
  12. {cloxy-5.2 → cloxy-5.3}/cloxy/backends/openai_backend.py +0 -0
  13. {cloxy-5.2 → cloxy-5.3}/cloxy/catalog.py +0 -0
  14. {cloxy-5.2 → cloxy-5.3}/cloxy/cli.py +0 -0
  15. {cloxy-5.2 → cloxy-5.3}/cloxy/cluster.py +0 -0
  16. {cloxy-5.2 → cloxy-5.3}/cloxy/convos.py +0 -0
  17. {cloxy-5.2 → cloxy-5.3}/cloxy/hardware.py +0 -0
  18. {cloxy-5.2 → cloxy-5.3}/cloxy/mcp_server.py +0 -0
  19. {cloxy-5.2 → cloxy-5.3}/cloxy/memory.py +0 -0
  20. {cloxy-5.2 → cloxy-5.3}/cloxy/proxy.py +0 -0
  21. {cloxy-5.2 → cloxy-5.3}/cloxy/push.py +0 -0
  22. {cloxy-5.2 → cloxy-5.3}/cloxy.egg-info/SOURCES.txt +0 -0
  23. {cloxy-5.2 → cloxy-5.3}/cloxy.egg-info/dependency_links.txt +0 -0
  24. {cloxy-5.2 → cloxy-5.3}/cloxy.egg-info/entry_points.txt +0 -0
  25. {cloxy-5.2 → cloxy-5.3}/cloxy.egg-info/requires.txt +0 -0
  26. {cloxy-5.2 → cloxy-5.3}/cloxy.egg-info/top_level.txt +0 -0
  27. {cloxy-5.2 → cloxy-5.3}/pyproject.toml +0 -0
  28. {cloxy-5.2 → cloxy-5.3}/setup.cfg +0 -0
  29. {cloxy-5.2 → cloxy-5.3}/tests/test_cli.py +0 -0
  30. {cloxy-5.2 → cloxy-5.3}/tests/test_cluster.py +0 -0
  31. {cloxy-5.2 → cloxy-5.3}/tests/test_config.py +0 -0
  32. {cloxy-5.2 → cloxy-5.3}/tests/test_convos.py +0 -0
  33. {cloxy-5.2 → cloxy-5.3}/tests/test_mcp.py +0 -0
  34. {cloxy-5.2 → cloxy-5.3}/tests/test_memory.py +0 -0
  35. {cloxy-5.2 → cloxy-5.3}/tests/test_proxy.py +0 -0
  36. {cloxy-5.2 → cloxy-5.3}/tests/test_push.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cloxy
3
- Version: 5.2
3
+ Version: 5.3
4
4
  Summary: Give your local AI eyes and memory — web proxy, self-maintaining conversation memory, MCP server, and an Apple Silicon LLM in one process.
5
5
  License: MIT
6
6
  Project-URL: Homepage, https://github.com/roygurner-gif/cloxy
@@ -152,7 +152,7 @@ Existing v3/v4 databases migrate in place on first start.
152
152
  | `POST` | `/fetch` | Fetch a URL. `{url, mode: clean\|raw\|markdown\|extract, selector?, headers?}` |
153
153
  | `POST` | `/search` | Fetch a URL, return lines containing a pattern |
154
154
  | `POST` | `/verify` | Fetch a URL, rank passages by semantic match to a claim |
155
- | `POST` | `/v1/chat/completions` | OpenAI-compatible chat (streaming or not). Extra: `memory`, `memory_top_k`, `memory_project` |
155
+ | `POST` | `/v1/chat/completions` | OpenAI-compatible chat (streaming or not). Extra: `memory`, `memory_top_k`, `memory_project`, `citations` |
156
156
  | `GET` | `/v1/models` | The currently loaded model |
157
157
  | `GET` | `/health` | Health + watcher summary |
158
158
 
@@ -199,6 +199,23 @@ resp = client.chat.completions.create(
199
199
  print(resp.choices[0].message.content)
200
200
  ```
201
201
 
202
+ #### Citations
203
+
204
+ Ask for `"citations": true` (it implies `memory`) and the model is told to cite the injected memories inline as `[1]`, `[2]`. The response gains a `cloxy_citations` object (on the final chunk when streaming):
205
+
206
+ ```json
207
+ {
208
+ "sources": [{"n": 1, "id": 412, "source": "fleischner-2017", "date": "2026-11-01",
209
+ "snippet": "Solid nodule <6 mm, low-risk: no routine follow-up…", "cited": true}],
210
+ "unknown": [],
211
+ "checks": [{"claim": "A 4 mm solid nodule needs no routine follow-up.", "cited": [1],
212
+ "support": {"1": 0.86}, "best_match": 1, "verdict": "ok"}],
213
+ "flagged": 0
214
+ }
215
+ ```
216
+
217
+ `checks` embeds each cited sentence against every injected source and flags it as `better_match_elsewhere` when a different source fits it better, or `unknown_source` when it cites a number that wasn't given. It catches mis-attributed citations; it does not prove a claim is true — a sentence that misstates its own source can still pass. Load reference material with `POST /ingest_text` (with a descriptive `source`) to make it citable.
218
+
202
219
  Continue.dev / Cursor: add an OpenAI-compatible model with base URL `http://localhost:9055/v1` and any API key (or your `CLOXY_API_KEY`).
203
220
 
204
221
  > Claude Code speaks the Anthropic Messages API, not the OpenAI one, so it can't use Cloxy as its *model* — but it uses Cloxy's memory and eyes through MCP (above).
@@ -269,6 +286,9 @@ Everything is an environment variable.
269
286
  | `CLOXY_RERANK_MODEL` | `Xenova/ms-marco-MiniLM-L-6-v2` | Reranker |
270
287
  | `CLOXY_CHAT_MEMORY` | *(unset)* | `1` to inject memory into every chat completion by default |
271
288
  | `CLOXY_CHAT_MEMORY_TOP_K` | `5` | How many memories to inject |
289
+ | `CLOXY_CHAT_CITATIONS` | *(unset)* | `1` to ask for inline `[n]` citations + `cloxy_citations` by default |
290
+ | `CLOXY_CITE_MARGIN` | `0.02` | How much better another source must match before a citation is flagged |
291
+ | `CLOXY_CITE_WINDOW` | `300` | Source window size (chars) for the citation check |
272
292
  | `CLOXY_ALLOW_PRIVATE_URLS` | *(unset)* | `1` lets the proxy fetch private/loopback addresses (SSRF risk) |
273
293
  | `CLOXY_USER_AGENT` | Chrome UA | User agent for web requests |
274
294
  | `CLOXY_FETCH_TIMEOUT` | `30` | Web fetch timeout, seconds |
@@ -113,7 +113,7 @@ Existing v3/v4 databases migrate in place on first start.
113
113
  | `POST` | `/fetch` | Fetch a URL. `{url, mode: clean\|raw\|markdown\|extract, selector?, headers?}` |
114
114
  | `POST` | `/search` | Fetch a URL, return lines containing a pattern |
115
115
  | `POST` | `/verify` | Fetch a URL, rank passages by semantic match to a claim |
116
- | `POST` | `/v1/chat/completions` | OpenAI-compatible chat (streaming or not). Extra: `memory`, `memory_top_k`, `memory_project` |
116
+ | `POST` | `/v1/chat/completions` | OpenAI-compatible chat (streaming or not). Extra: `memory`, `memory_top_k`, `memory_project`, `citations` |
117
117
  | `GET` | `/v1/models` | The currently loaded model |
118
118
  | `GET` | `/health` | Health + watcher summary |
119
119
 
@@ -160,6 +160,23 @@ resp = client.chat.completions.create(
160
160
  print(resp.choices[0].message.content)
161
161
  ```
162
162
 
163
+ #### Citations
164
+
165
+ Ask for `"citations": true` (it implies `memory`) and the model is told to cite the injected memories inline as `[1]`, `[2]`. The response gains a `cloxy_citations` object (on the final chunk when streaming):
166
+
167
+ ```json
168
+ {
169
+ "sources": [{"n": 1, "id": 412, "source": "fleischner-2017", "date": "2026-11-01",
170
+ "snippet": "Solid nodule <6 mm, low-risk: no routine follow-up…", "cited": true}],
171
+ "unknown": [],
172
+ "checks": [{"claim": "A 4 mm solid nodule needs no routine follow-up.", "cited": [1],
173
+ "support": {"1": 0.86}, "best_match": 1, "verdict": "ok"}],
174
+ "flagged": 0
175
+ }
176
+ ```
177
+
178
+ `checks` embeds each cited sentence against every injected source and flags it as `better_match_elsewhere` when a different source fits it better, or `unknown_source` when it cites a number that wasn't given. It catches mis-attributed citations; it does not prove a claim is true — a sentence that misstates its own source can still pass. Load reference material with `POST /ingest_text` (with a descriptive `source`) to make it citable.
179
+
163
180
  Continue.dev / Cursor: add an OpenAI-compatible model with base URL `http://localhost:9055/v1` and any API key (or your `CLOXY_API_KEY`).
164
181
 
165
182
  > Claude Code speaks the Anthropic Messages API, not the OpenAI one, so it can't use Cloxy as its *model* — but it uses Cloxy's memory and eyes through MCP (above).
@@ -230,6 +247,9 @@ Everything is an environment variable.
230
247
  | `CLOXY_RERANK_MODEL` | `Xenova/ms-marco-MiniLM-L-6-v2` | Reranker |
231
248
  | `CLOXY_CHAT_MEMORY` | *(unset)* | `1` to inject memory into every chat completion by default |
232
249
  | `CLOXY_CHAT_MEMORY_TOP_K` | `5` | How many memories to inject |
250
+ | `CLOXY_CHAT_CITATIONS` | *(unset)* | `1` to ask for inline `[n]` citations + `cloxy_citations` by default |
251
+ | `CLOXY_CITE_MARGIN` | `0.02` | How much better another source must match before a citation is flagged |
252
+ | `CLOXY_CITE_WINDOW` | `300` | Source window size (chars) for the citation check |
233
253
  | `CLOXY_ALLOW_PRIVATE_URLS` | *(unset)* | `1` lets the proxy fetch private/loopback addresses (SSRF risk) |
234
254
  | `CLOXY_USER_AGENT` | Chrome UA | User agent for web requests |
235
255
  | `CLOXY_FETCH_TIMEOUT` | `30` | Web fetch timeout, seconds |
@@ -1,3 +1,3 @@
1
1
  """CLOXY — give your local AI eyes and memory."""
2
2
 
3
- __version__ = "5.2"
3
+ __version__ = "5.3"
@@ -126,6 +126,14 @@ EAGER_LLM = _flag("CLOXY_EAGER_LLM")
126
126
  # Per-request override: {"memory": true|false} in the body.
127
127
  CHAT_MEMORY = _flag("CLOXY_CHAT_MEMORY")
128
128
  CHAT_MEMORY_TOP_K = int(os.environ.get("CLOXY_CHAT_MEMORY_TOP_K", 5))
129
+ # Ask the model to cite injected memory inline as [n] and return the sources
130
+ # behind each number. Per-request override: {"citations": true|false}.
131
+ CHAT_CITATIONS = _flag("CLOXY_CHAT_CITATIONS")
132
+ # Citation check: sources are compared in windows of this many chars, and a
133
+ # citation is flagged when another source matches the sentence better by more
134
+ # than this cosine margin (embedding sims are compressed, so keep it small).
135
+ CITE_WINDOW = int(os.environ.get("CLOXY_CITE_WINDOW", 300))
136
+ CITE_MARGIN = float(os.environ.get("CLOXY_CITE_MARGIN", 0.02))
129
137
 
130
138
  # --- Upstream / clustered LLM ---
131
139
  # Point chat at an OpenAI-compatible server instead of loading MLX in-process.
@@ -7,11 +7,12 @@ Run with `cloxy start` (or `python -m cloxy start`).
7
7
  import json
8
8
  import logging
9
9
  import os
10
+ import re
10
11
  import secrets
11
12
  import time
12
13
  from contextlib import asynccontextmanager
13
14
  from datetime import datetime, timezone
14
- from typing import List, Optional, Union
15
+ from typing import List, Optional, Tuple, Union
15
16
 
16
17
  from fastapi import Depends, FastAPI, HTTPException
17
18
  from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse
@@ -459,6 +460,8 @@ class ChatCompletionRequest(BaseModel):
459
460
  memory: Optional[bool] = None # default: CLOXY_CHAT_MEMORY
460
461
  memory_top_k: int = Field(config.CHAT_MEMORY_TOP_K, ge=1, le=20)
461
462
  memory_project: Optional[str] = None
463
+ # Cite recalled memory inline as [n]; response carries `cloxy_citations`.
464
+ citations: Optional[bool] = None # default: CLOXY_CHAT_CITATIONS
462
465
 
463
466
  def effective_max_tokens(self) -> int:
464
467
  return self.max_completion_tokens or self.max_tokens or DEFAULT_MAX_TOKENS
@@ -491,34 +494,160 @@ async def _ensure_llm_loaded():
491
494
  await backend.load_model(hf_id)
492
495
 
493
496
 
494
- def _memory_block(hits: List[dict]) -> str:
495
- lines = ["Relevant memory from past conversations (most relevant first). "
496
- "Use it when it helps; ignore it when it doesn't."]
497
+ CITE_INSTRUCTIONS = (
498
+ "Numbered sources from memory (most relevant first). When a statement relies on "
499
+ "a source, cite it inline right after the statement as [n], e.g. [2] or [1][3]. "
500
+ "Only cite numbers listed below. If the sources don't support an answer, say so "
501
+ "plainly instead of guessing, and don't cite anything for general knowledge.")
502
+
503
+
504
+ def _hit_tag(h: dict, with_source: bool = False) -> str:
505
+ parts = [(h.get("ts_start") or "")[:10],
506
+ os.path.basename((h.get("project") or "").rstrip("/"))]
507
+ if with_source:
508
+ parts.append(h.get("source") or "")
509
+ return " · ".join(b for b in parts if b)
510
+
511
+
512
+ def _memory_block(hits: List[dict], cite: bool = False) -> str:
513
+ head = CITE_INSTRUCTIONS if cite else (
514
+ "Relevant memory from past conversations (most relevant first). "
515
+ "Use it when it helps; ignore it when it doesn't.")
516
+ lines = [head]
497
517
  for i, h in enumerate(hits, 1):
498
- tag = " · ".join(b for b in (
499
- (h.get("ts_start") or "")[:10],
500
- os.path.basename((h.get("project") or "").rstrip("/")),
501
- ) if b)
518
+ tag = _hit_tag(h, with_source=cite)
502
519
  body = h["content"] if len(h["content"]) <= 1200 else h["content"][:1200] + " …"
503
520
  lines.append(f"{i}. [{tag}] {body}" if tag else f"{i}. {body}")
504
521
  return "\n\n".join(lines)
505
522
 
506
523
 
507
- async def _with_memory(req: ChatCompletionRequest, messages: List[dict]) -> List[dict]:
508
- """Prepend a system block of recalled memory keyed on the last user message."""
524
+ _CITE_RE = re.compile(r"\[(\d{1,2})\]")
525
+
526
+
527
+ def _citations(hits: List[dict], answer: str) -> dict:
528
+ """Map each [n] in the answer back to the memory it points at.
529
+
530
+ `sources` lists every injected memory with `cited` set when the answer used
531
+ it; `unknown` lists numbers the model cited that don't exist (a red flag
532
+ worth surfacing to the reader).
533
+ """
534
+ used = {int(n) for n in _CITE_RE.findall(answer or "")}
535
+ sources = []
536
+ for i, h in enumerate(hits, 1):
537
+ snippet = " ".join(h["content"].split())
538
+ sources.append({
539
+ "n": i,
540
+ "id": h.get("id"),
541
+ "source": h.get("source"),
542
+ "project": h.get("project"),
543
+ "session_id": h.get("session_id"),
544
+ "date": (h.get("ts_start") or "")[:10] or None,
545
+ "snippet": snippet if len(snippet) <= 280 else snippet[:280] + " …",
546
+ "cited": i in used,
547
+ })
548
+ return {"sources": sources,
549
+ "unknown": sorted(n for n in used if not 1 <= n <= len(hits))}
550
+
551
+
552
+ _SENTENCE_RE = re.compile(r"(?<=[.!?])\s+|\n+")
553
+
554
+
555
+ def _cited_claims(answer: str) -> List[Tuple[str, List[int]]]:
556
+ """Split the answer into sentences and keep the ones carrying [n] markers."""
557
+ out = []
558
+ for sent in _SENTENCE_RE.split(answer or ""):
559
+ nums = [int(n) for n in _CITE_RE.findall(sent)]
560
+ text = " ".join(_CITE_RE.sub("", sent).split())
561
+ if nums and text:
562
+ out.append((text, sorted(set(nums))))
563
+ return out
564
+
565
+
566
+ async def _check_citations(hits: List[dict], answer: str) -> List[dict]:
567
+ """Does each cited sentence actually match the source it cites?
568
+
569
+ Embeds every cited sentence and small windows of every injected source, then
570
+ asks which source matches the sentence best. A citation is flagged when the
571
+ best-matching source isn't one of the cited ones (beyond a small margin), or
572
+ when it points at a number that doesn't exist. Heuristic, not proof: it
573
+ catches mis-attributed citations, not every wrong claim.
574
+ """
575
+ import numpy as np
576
+ claims = _cited_claims(answer)
577
+ if not claims or not hits:
578
+ return []
579
+ windows, owner = [], []
580
+ for i, h in enumerate(hits, 1):
581
+ for w in memory.chunk_text(h["content"], size=config.CITE_WINDOW,
582
+ overlap=config.CITE_WINDOW // 5) or [h["content"]]:
583
+ windows.append(config.EMBED_PASSAGE_PREFIX + w)
584
+ owner.append(i)
585
+ embs = await memory.aembed_batch(
586
+ windows + [config.EMBED_QUERY_PREFIX + c for c, _ in claims])
587
+ mat = np.vstack(embs).astype(np.float32)
588
+ mat /= np.maximum(np.linalg.norm(mat, axis=1, keepdims=True), 1e-9)
589
+ win, qs = mat[:len(windows)], mat[len(windows):]
590
+ sims = qs @ win.T # (claims, windows)
591
+ owner_arr = np.array(owner)
592
+
593
+ report = []
594
+ for (text, cited), row in zip(claims, sims):
595
+ per_src = {n: round(float(row[owner_arr == n].max()), 4) for n in range(1, len(hits) + 1)}
596
+ best_n = max(per_src, key=per_src.get)
597
+ valid = [n for n in cited if n in per_src]
598
+ cited_best = max((per_src[n] for n in valid), default=None)
599
+ if len(valid) < len(cited):
600
+ verdict = "unknown_source"
601
+ elif cited_best is not None and per_src[best_n] - cited_best > config.CITE_MARGIN:
602
+ verdict = "better_match_elsewhere"
603
+ else:
604
+ verdict = "ok"
605
+ report.append({
606
+ "claim": text if len(text) <= 300 else text[:300] + " …",
607
+ "cited": cited,
608
+ "support": {n: per_src[n] for n in valid},
609
+ "best_match": best_n,
610
+ "verdict": verdict,
611
+ })
612
+ return report
613
+
614
+
615
+ async def _citation_payload(hits: List[dict], answer: str) -> dict:
616
+ out = _citations(hits, answer)
617
+ try:
618
+ out["checks"] = await _check_citations(hits, answer)
619
+ except Exception as e: # never fail the chat over the check
620
+ logger.warning(f"citation check failed: {e}")
621
+ out["checks"], out["check_error"] = [], str(e)
622
+ out["flagged"] = sum(c["verdict"] != "ok" for c in out["checks"])
623
+ return out
624
+
625
+
626
+ async def _with_memory(req: ChatCompletionRequest,
627
+ messages: List[dict]) -> Tuple[List[dict], List[dict], bool]:
628
+ """Prepend a system block of recalled memory keyed on the last user message.
629
+
630
+ Returns (messages, hits, cite). `cite` is True only when citations were asked
631
+ for and there was memory to cite.
632
+ """
509
633
  use = config.CHAT_MEMORY if req.memory is None else req.memory
634
+ cite = config.CHAT_CITATIONS if req.citations is None else req.citations
635
+ if req.citations and req.memory is None:
636
+ use = True # asking for citations implies memory
510
637
  if not use:
511
- return messages
638
+ return messages, [], False
512
639
  last_user = next((m["content"] for m in reversed(messages) if m["role"] == "user"), "")
513
640
  if not last_user.strip():
514
- return messages
641
+ return messages, [], False
515
642
  hits = await memory.search(last_user, top_k=req.memory_top_k, project=req.memory_project)
516
643
  if not hits:
517
- return messages
518
- block = _memory_block(hits)
644
+ return messages, [], False
645
+ block = _memory_block(hits, cite=cite)
519
646
  if messages and messages[0]["role"] == "system":
520
- return [{"role": "system", "content": messages[0]["content"] + "\n\n" + block}] + messages[1:]
521
- return [{"role": "system", "content": block}] + messages
647
+ merged = [{"role": "system", "content": messages[0]["content"] + "\n\n" + block}] + messages[1:]
648
+ else:
649
+ merged = [{"role": "system", "content": block}] + messages
650
+ return merged, hits, cite
522
651
 
523
652
 
524
653
  @app.get("/v1/models", dependencies=[Depends(check_auth)])
@@ -541,16 +670,21 @@ async def chat_completions(req: ChatCompletionRequest):
541
670
 
542
671
  role_map = {"developer": "system"}
543
672
  messages = [{"role": role_map.get(m.role, m.role), "content": m.text()} for m in req.messages]
544
- messages = await _with_memory(req, messages)
673
+ messages, hits, cite = await _with_memory(req, messages)
545
674
  max_tokens = req.effective_max_tokens()
546
675
 
547
676
  if not req.stream:
548
677
  try:
549
- return await backend.generate_chat(
678
+ out = await backend.generate_chat(
550
679
  messages=messages, max_tokens=max_tokens,
551
680
  temperature=req.temperature, top_p=req.top_p)
552
681
  except UpstreamError as e:
553
682
  raise HTTPException(status_code=e.status, detail=str(e))
683
+ if cite:
684
+ choices = out.get("choices") or [{}]
685
+ answer = (choices[0].get("message") or {}).get("content") or ""
686
+ out["cloxy_citations"] = await _citation_payload(hits, answer)
687
+ return out
554
688
 
555
689
  # Pull the first piece before answering, so an unreachable upstream is an
556
690
  # HTTP error and not a 200 that dies mid-stream.
@@ -578,6 +712,7 @@ async def chat_completions(req: ChatCompletionRequest):
578
712
  completion_id = f"cloxy-{int(time.time() * 1000)}"
579
713
  model_id = backend.current_model() or "unknown"
580
714
  finish_reason, usage = "stop", None
715
+ answer = []
581
716
 
582
717
  # If the client disconnects, Starlette closes this generator, which
583
718
  # closes stream_chat, which signals the MLX producer thread to stop.
@@ -586,6 +721,7 @@ async def chat_completions(req: ChatCompletionRequest):
586
721
  finish_reason, usage = piece.finish_reason, piece.usage
587
722
  if not piece.text:
588
723
  continue
724
+ answer.append(piece.text)
589
725
  chunk = {
590
726
  "id": completion_id, "object": "chat.completion.chunk",
591
727
  "created": int(time.time()), "model": model_id,
@@ -600,6 +736,9 @@ async def chat_completions(req: ChatCompletionRequest):
600
736
  }
601
737
  if usage:
602
738
  final["usage"] = usage
739
+ if cite:
740
+ # Citations need the whole answer, so they ride on the last chunk.
741
+ final["cloxy_citations"] = await _citation_payload(hits, "".join(answer))
603
742
  yield f"data: {json.dumps(final)}\n\n"
604
743
  yield "data: [DONE]\n\n"
605
744
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cloxy
3
- Version: 5.2
3
+ Version: 5.3
4
4
  Summary: Give your local AI eyes and memory — web proxy, self-maintaining conversation memory, MCP server, and an Apple Silicon LLM in one process.
5
5
  License: MIT
6
6
  Project-URL: Homepage, https://github.com/roygurner-gif/cloxy
@@ -152,7 +152,7 @@ Existing v3/v4 databases migrate in place on first start.
152
152
  | `POST` | `/fetch` | Fetch a URL. `{url, mode: clean\|raw\|markdown\|extract, selector?, headers?}` |
153
153
  | `POST` | `/search` | Fetch a URL, return lines containing a pattern |
154
154
  | `POST` | `/verify` | Fetch a URL, rank passages by semantic match to a claim |
155
- | `POST` | `/v1/chat/completions` | OpenAI-compatible chat (streaming or not). Extra: `memory`, `memory_top_k`, `memory_project` |
155
+ | `POST` | `/v1/chat/completions` | OpenAI-compatible chat (streaming or not). Extra: `memory`, `memory_top_k`, `memory_project`, `citations` |
156
156
  | `GET` | `/v1/models` | The currently loaded model |
157
157
  | `GET` | `/health` | Health + watcher summary |
158
158
 
@@ -199,6 +199,23 @@ resp = client.chat.completions.create(
199
199
  print(resp.choices[0].message.content)
200
200
  ```
201
201
 
202
+ #### Citations
203
+
204
+ Ask for `"citations": true` (it implies `memory`) and the model is told to cite the injected memories inline as `[1]`, `[2]`. The response gains a `cloxy_citations` object (on the final chunk when streaming):
205
+
206
+ ```json
207
+ {
208
+ "sources": [{"n": 1, "id": 412, "source": "fleischner-2017", "date": "2026-11-01",
209
+ "snippet": "Solid nodule <6 mm, low-risk: no routine follow-up…", "cited": true}],
210
+ "unknown": [],
211
+ "checks": [{"claim": "A 4 mm solid nodule needs no routine follow-up.", "cited": [1],
212
+ "support": {"1": 0.86}, "best_match": 1, "verdict": "ok"}],
213
+ "flagged": 0
214
+ }
215
+ ```
216
+
217
+ `checks` embeds each cited sentence against every injected source and flags it as `better_match_elsewhere` when a different source fits it better, or `unknown_source` when it cites a number that wasn't given. It catches mis-attributed citations; it does not prove a claim is true — a sentence that misstates its own source can still pass. Load reference material with `POST /ingest_text` (with a descriptive `source`) to make it citable.
218
+
202
219
  Continue.dev / Cursor: add an OpenAI-compatible model with base URL `http://localhost:9055/v1` and any API key (or your `CLOXY_API_KEY`).
203
220
 
204
221
  > Claude Code speaks the Anthropic Messages API, not the OpenAI one, so it can't use Cloxy as its *model* — but it uses Cloxy's memory and eyes through MCP (above).
@@ -269,6 +286,9 @@ Everything is an environment variable.
269
286
  | `CLOXY_RERANK_MODEL` | `Xenova/ms-marco-MiniLM-L-6-v2` | Reranker |
270
287
  | `CLOXY_CHAT_MEMORY` | *(unset)* | `1` to inject memory into every chat completion by default |
271
288
  | `CLOXY_CHAT_MEMORY_TOP_K` | `5` | How many memories to inject |
289
+ | `CLOXY_CHAT_CITATIONS` | *(unset)* | `1` to ask for inline `[n]` citations + `cloxy_citations` by default |
290
+ | `CLOXY_CITE_MARGIN` | `0.02` | How much better another source must match before a citation is flagged |
291
+ | `CLOXY_CITE_WINDOW` | `300` | Source window size (chars) for the citation check |
272
292
  | `CLOXY_ALLOW_PRIVATE_URLS` | *(unset)* | `1` lets the proxy fetch private/loopback addresses (SSRF risk) |
273
293
  | `CLOXY_USER_AGENT` | Chrome UA | User agent for web requests |
274
294
  | `CLOXY_FETCH_TIMEOUT` | `30` | Web fetch timeout, seconds |
@@ -1,4 +1,5 @@
1
1
  """Endpoint tests through the TestClient fixture in conftest.py."""
2
+ import json
2
3
  from cloxy import config, memory, proxy, server
3
4
 
4
5
 
@@ -215,3 +216,79 @@ def test_ingest_and_recall_use_passage_and_query_prefixes(client, monkeypatch):
215
216
  assert r.status_code == 200
216
217
  assert seen[0].startswith("passage: ") and "prefix probe alpha" in seen[0]
217
218
  assert seen[-1] == "query: prefix probe"
219
+
220
+
221
+ # ---------------------------------------------------------------------------
222
+ # citations: [n] markers → sources, plus the mis-attribution check
223
+ # ---------------------------------------------------------------------------
224
+
225
+ GUIDE = "Fleischner guideline: solid nodule under 6 mm in a low risk patient needs no routine follow up."
226
+ TACO = "Lunch plan: birria tacos from the truck on Thursday near the office."
227
+
228
+
229
+ def _fake_backend(answer, seen):
230
+ from types import SimpleNamespace
231
+ from cloxy.backends.mlx_backend import StreamPiece
232
+
233
+ async def generate_chat(messages, **kw):
234
+ seen.append(messages)
235
+ return {"id": "x", "object": "chat.completion",
236
+ "choices": [{"index": 0, "message": {"role": "assistant", "content": answer},
237
+ "finish_reason": "stop"}]}
238
+
239
+ async def stream_chat(messages, **kw):
240
+ seen.append(messages)
241
+ for word in answer.split(" "):
242
+ yield StreamPiece(text=word + " ")
243
+ yield StreamPiece(text="", finish_reason="stop")
244
+
245
+ return SimpleNamespace(is_loaded=lambda: True, current_model=lambda: "fake",
246
+ generate_chat=generate_chat, stream_chat=stream_chat)
247
+
248
+
249
+ def test_citations_map_numbers_to_sources():
250
+ hits = [{"id": 7, "content": GUIDE, "source": "fleischner-2017", "project": None,
251
+ "session_id": None, "ts_start": "2026-11-01T00:00:00Z"},
252
+ {"id": 8, "content": TACO, "source": "notes", "project": None,
253
+ "session_id": None, "ts_start": None}]
254
+ out = server._citations(hits, "No follow up needed [1]. Also see [4].")
255
+ assert [s["cited"] for s in out["sources"]] == [True, False]
256
+ assert out["sources"][0]["source"] == "fleischner-2017" and out["sources"][0]["date"] == "2026-11-01"
257
+ assert out["unknown"] == [4]
258
+ assert server._cited_claims("A thing [1]. Plain sentence. B [2][1].") == [
259
+ ("A thing .", [1]), ("B .", [1, 2])]
260
+ block = server._memory_block(hits, cite=True)
261
+ assert "cite it inline" in block and "fleischner-2017" in block
262
+
263
+
264
+ def test_chat_citations_end_to_end(client, monkeypatch):
265
+ client.post("/ingest_text", json={"text": GUIDE, "source": "cite-fleischner"})
266
+ client.post("/ingest_text", json={"text": TACO, "source": "cite-notes"})
267
+ hits = client.post("/recall", json={"query": "solid nodule follow up tacos", "top_k": 2}).json()["results"]
268
+ n_guide = 1 + [h["content"] for h in hits].index(GUIDE)
269
+ n_taco = 3 - n_guide
270
+ answer = (f"A solid nodule under 6 mm in a low risk patient needs no routine follow up [{n_guide}]. "
271
+ f"Solid nodule follow up is not needed under 6 mm [{n_taco}]. Bogus [9].")
272
+ seen = []
273
+ monkeypatch.setattr(server.backends, "get", lambda: _fake_backend(answer, seen))
274
+ body = {"messages": [{"role": "user", "content": "solid nodule follow up tacos"}],
275
+ "citations": True, "memory_top_k": 2}
276
+
277
+ out = client.post("/v1/chat/completions", json=body).json()
278
+ assert "cite it inline" in seen[-1][0]["content"] # citations imply memory
279
+ cit = out["cloxy_citations"]
280
+ assert cit["unknown"] == [9]
281
+ verdicts = [c["verdict"] for c in cit["checks"]]
282
+ assert verdicts == ["ok", "better_match_elsewhere", "unknown_source"]
283
+ assert cit["checks"][1]["best_match"] == n_guide and cit["flagged"] == 2
284
+
285
+ # streaming: same payload rides on the final chunk
286
+ r = client.post("/v1/chat/completions", json={**body, "stream": True})
287
+ events = [json.loads(l[6:]) for l in r.text.splitlines()
288
+ if l.startswith("data: {")]
289
+ assert events[-1]["cloxy_citations"]["flagged"] == 2
290
+
291
+ # off by default: no payload, old memory wording
292
+ out = client.post("/v1/chat/completions", json={**body, "citations": None, "memory": True}).json()
293
+ assert "cloxy_citations" not in out and "cite it inline" not in seen[-1][0]["content"]
294
+ client.post("/forget", json={"source_prefix": "cite-"})
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes