ragfly 0.1.2__tar.gz → 0.2.0__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.
@@ -0,0 +1,42 @@
1
+ name: release
2
+
3
+ # Publica ragfly (SDK Python) a PyPI al pushear un tag vX.Y.Z.
4
+ # Forma canónica de release:
5
+ # 1. subir version en pyproject.toml + ragfly/__init__.py
6
+ # 2. commit + push
7
+ # 3. git tag vX.Y.Z && git push origin vX.Y.Z
8
+ on:
9
+ push:
10
+ tags:
11
+ - "v*"
12
+
13
+ jobs:
14
+ build-and-publish:
15
+ runs-on: ubuntu-latest
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+
19
+ - uses: actions/setup-python@v5
20
+ with:
21
+ python-version: "3.12"
22
+
23
+ - name: Verificar que el tag coincide con la versión del paquete
24
+ run: |
25
+ TAG="${GITHUB_REF_NAME#v}"
26
+ PKG=$(python -c "import tomllib; print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])")
27
+ echo "tag=$TAG pyproject=$PKG"
28
+ if [ "$TAG" != "$PKG" ]; then
29
+ echo "::error::El tag v$TAG no coincide con la versión $PKG de pyproject.toml"
30
+ exit 1
31
+ fi
32
+
33
+ - name: Build sdist + wheel
34
+ run: |
35
+ python -m pip install --upgrade build
36
+ python -m build
37
+
38
+ - name: Publish to PyPI
39
+ uses: pypa/gh-action-pypi-publish@release/v1
40
+ with:
41
+ password: ${{ secrets.PYPI_API_TOKEN }}
42
+ skip-existing: true
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ragfly
3
- Version: 0.1.2
3
+ Version: 0.2.0
4
4
  Summary: RAGfly Python SDK — retrieval infrastructure for your AI agents
5
5
  Project-URL: Homepage, https://ragfly.ai
6
6
  Project-URL: Documentation, https://api.ragfly.ai/docs
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "ragfly"
7
- version = "0.1.2"
7
+ version = "0.2.0"
8
8
  description = "RAGfly Python SDK — retrieval infrastructure for your AI agents"
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
@@ -2,4 +2,4 @@ from .client import RAGfly
2
2
  from .models import SearchResult, AskResponse, AskChunk, Document, Chunk
3
3
 
4
4
  __all__ = ["RAGfly", "SearchResult", "AskResponse", "AskChunk", "Document", "Chunk"]
5
- __version__ = "0.1.2"
5
+ __version__ = "0.2.0"
@@ -6,12 +6,19 @@ from urllib.parse import urljoin
6
6
 
7
7
  import httpx
8
8
 
9
+ from .codes import CodeTranslator
9
10
  from .models import AskChunk, AskResponse, Chunk, Document, SearchResult
10
11
 
11
12
  DEFAULT_BASE_URL = "https://api.ragfly.ai"
12
- _TIMEOUT = httpx.Timeout(60.0, connect=10.0)
13
- #: Función de interfaz por defecto para ``ask()`` (define el modelo LLM de la conversación).
14
- DEFAULT_FUNCION = "CHAT-USUARIO"
13
+ # Esquema de timeouts del SDK (h.210):
14
+ # - Requests normales: `timeout` del constructor (default 60s, connect 10s).
15
+ # - Streaming SSE (ask stream=True y ask sync, que lo reusa): SIN read-timeout
16
+ # (Timeout(None, connect=10.0)) porque la generación LLM puede superar
17
+ # cualquier tope entre tokens; el truncamiento se detecta por el evento
18
+ # 'done' y la validación de líneas (no por timeout).
19
+ #: Default interface function for ``ask()`` (sets the conversation's LLM model).
20
+ #: English public code; the SDK translates it to the internal code on the wire.
21
+ DEFAULT_FUNCION = "CHAT-USER"
15
22
 
16
23
 
17
24
  class RAGflyError(Exception):
@@ -21,19 +28,19 @@ class RAGflyError(Exception):
21
28
 
22
29
 
23
30
  class RAGfly:
24
- """Cliente oficial de RAGfly.
31
+ """Official RAGfly client.
25
32
 
26
- Uso básico::
33
+ Basic usage::
27
34
 
28
35
  from ragfly import RAGfly
29
36
 
30
37
  client = RAGfly(api_key="slm_live_...")
31
- resp = client.ask("¿Cuáles son las ventas de Q1?")
38
+ resp = client.ask("What were Q1 sales?")
32
39
  print(resp.answer)
33
40
 
34
41
  Streaming::
35
42
 
36
- for chunk in client.ask("¿Cuáles son las ventas de Q1?", stream=True):
43
+ for chunk in client.ask("What were Q1 sales?", stream=True):
37
44
  print(chunk.delta, end="", flush=True)
38
45
  """
39
46
 
@@ -50,6 +57,8 @@ class RAGfly:
50
57
  headers={"Authorization": f"Bearer {api_key}"},
51
58
  )
52
59
  self._async_http: Optional[httpx.AsyncClient] = None
60
+ # Public-code translator: English on the SDK surface, internal on the wire.
61
+ self._codes = CodeTranslator(self._fetch_code_map)
53
62
 
54
63
  # ── Internos ─────────────────────────────────────────────────────────────
55
64
 
@@ -65,14 +74,24 @@ class RAGfly:
65
74
  raise RAGflyError(detail, status_code=resp.status_code)
66
75
 
67
76
  def _get_or_create_conversation(self, codigo_funcion: str = DEFAULT_FUNCION) -> int:
68
- """Crea una conversación nueva y devuelve su id."""
77
+ """Create a new conversation and return its id."""
69
78
  resp = self._http.post(self._url("/interfaz/conversaciones"), json={
70
79
  "titulo": "SDK",
71
- "codigo_funcion": codigo_funcion,
80
+ "codigo_funcion": self._codes.to_internal("function", codigo_funcion),
72
81
  })
73
82
  self._raise_for_status(resp)
74
83
  return resp.json()["id_conversacion"]
75
84
 
85
+ def _fetch_code_map(self) -> dict:
86
+ """Fetch the public-code map (internal → English) from the backend. Used by
87
+ the code translator; the map is cached after the first call."""
88
+ resp = self._http.get(
89
+ self._url("/catalogo/public-codes"),
90
+ params={"domains": "status,doc_type,function"},
91
+ )
92
+ self._raise_for_status(resp)
93
+ return resp.json().get("domains", {})
94
+
76
95
  # ── API pública ──────────────────────────────────────────────────────────
77
96
 
78
97
  def search(
@@ -84,10 +103,10 @@ class RAGfly:
84
103
  codigo_entidad: Optional[str] = None,
85
104
  id_espacio: Optional[int] = None,
86
105
  ) -> SearchResult:
87
- """Búsqueda semántica híbrida (vector + léxico + rerank).
106
+ """Hybrid semantic search (vector + lexical + rerank).
88
107
 
89
108
  Returns:
90
- :class:`SearchResult` con lista de documentos y sus chunks relevantes.
109
+ :class:`SearchResult` with the matching documents and their relevant chunks.
91
110
  """
92
111
  payload = {
93
112
  "q": query,
@@ -142,18 +161,18 @@ class RAGfly:
142
161
  codigo_funcion: str = DEFAULT_FUNCION,
143
162
  stream: bool = False,
144
163
  ) -> Union[AskResponse, Iterator[AskChunk]]:
145
- """Pregunta al RAG con respuesta completa o streaming.
164
+ """Ask the RAG for a full or streaming answer.
146
165
 
147
166
  Args:
148
- question: La pregunta en lenguaje natural.
149
- conversation_id: Reusar conversación existente. Si es None, crea una nueva.
150
- codigo_funcion: Función de interfaz que define el modelo LLM al crear una
151
- conversación nueva. Default ``CHAT-USUARIO``. Ignorado si se pasa
152
- ``conversation_id``.
153
- stream: Si True, devuelve un iterador de :class:`AskChunk`.
167
+ question: The natural-language question.
168
+ conversation_id: Reuse an existing conversation. If None, a new one is created.
169
+ codigo_funcion: Interface function that sets the LLM model when creating a
170
+ new conversation. Default ``CHAT-USER``. Ignored when ``conversation_id``
171
+ is given.
172
+ stream: If True, returns an iterator of :class:`AskChunk`.
154
173
 
155
174
  Returns:
156
- :class:`AskResponse` (stream=False) o ``Iterator[AskChunk]`` (stream=True).
175
+ :class:`AskResponse` (stream=False) or ``Iterator[AskChunk]`` (stream=True).
157
176
  """
158
177
  conv_id = conversation_id or self._get_or_create_conversation(codigo_funcion)
159
178
 
@@ -172,19 +191,39 @@ class RAGfly:
172
191
  timeout=httpx.Timeout(None, connect=10.0),
173
192
  ) as resp:
174
193
  self._raise_for_status(resp)
194
+ recibio_done = False
195
+ lineas_malformadas = 0
175
196
  for line in resp.iter_lines():
176
197
  if not line.startswith("data: "):
177
- continue
198
+ continue # comentarios SSE (': ping' heartbeat) y líneas vacías
178
199
  try:
179
200
  payload = json.loads(line[6:])
180
201
  except json.JSONDecodeError:
202
+ # El backend solo emite JSON en líneas 'data:' — una línea
203
+ # malformada es un evento perdido (corte intra-evento, h.217).
204
+ lineas_malformadas += 1
181
205
  continue
182
206
  if "error" in payload:
183
207
  raise RAGflyError(payload["error"])
184
208
  if payload.get("done"):
209
+ if lineas_malformadas:
210
+ raise RAGflyError(
211
+ f"El stream llegó al 'done' pero {lineas_malformadas} "
212
+ "evento(s) 'data:' venían malformados — la respuesta "
213
+ "puede tener huecos."
214
+ )
215
+ recibio_done = True
185
216
  return
186
217
  if "text" in payload:
187
218
  yield AskChunk(delta=payload["text"])
219
+ # El stream cerró sin el evento `done` final: respuesta truncada
220
+ # (corte de red, timeout del proxy). No devolver una respuesta
221
+ # parcial como si fuera completa — propagar como error.
222
+ if not recibio_done:
223
+ raise RAGflyError(
224
+ "El stream de respuesta se cortó antes de terminar "
225
+ "(sin evento 'done'); la respuesta puede estar incompleta."
226
+ )
188
227
 
189
228
  def _ask_sync(self, question: str, conv_id: int) -> AskResponse:
190
229
  buffer = []
@@ -204,18 +243,41 @@ class RAGfly:
204
243
  *,
205
244
  page: int = 1,
206
245
  page_size: int = 20,
246
+ status: Optional[str] = None,
207
247
  estado: Optional[str] = None,
208
248
  ) -> dict:
209
- """Lista documentos del corpus con paginación."""
210
- # El backend (GET /documentos/paginado) espera page/limit/codigo_estado_doc.
211
- # FastAPI ignora params desconocidos, así que pagina/limite/estado se
212
- # traducían en "sin filtro, 50 por defecto".
249
+ """List documents in the corpus with pagination.
250
+
251
+ Args:
252
+ status: Filter by processing state, in English — e.g. ``VECTORIZED``,
253
+ ``SCANNED``, ``CHUNKED``, ``LOADED``. Use ``VECTORIZED`` to list only
254
+ documents that are searchable.
255
+ estado: Deprecated Spanish alias of ``status`` (kept for compatibility).
256
+ """
257
+ # The REST API (GET /documentos/paginado) speaks internal codes; translate the
258
+ # English public state on the way in and the returned codes on the way out.
259
+ status = status or estado
213
260
  params: dict = {"page": page, "limit": page_size}
214
- if estado:
215
- params["codigo_estado_doc"] = estado
261
+ if status:
262
+ params["codigo_estado_doc"] = self._codes.to_internal("status", status)
216
263
  resp = self._http.get(self._url("/documentos/paginado"), params=params)
217
264
  self._raise_for_status(resp)
218
- return resp.json()
265
+ return self._translate_documents(resp.json())
266
+
267
+ def _translate_documents(self, data: dict) -> dict:
268
+ """Translate internal catalog codes to their English public alias in a
269
+ documents response (state + document type of every row)."""
270
+ if not isinstance(data, dict):
271
+ return data
272
+ rows = data.get("items") or data.get("documentos") or data.get("resultados") or []
273
+ for doc in rows:
274
+ if not isinstance(doc, dict):
275
+ continue
276
+ if doc.get("codigo_estado_doc"):
277
+ doc["codigo_estado_doc"] = self._codes.to_english("status", doc["codigo_estado_doc"])
278
+ if doc.get("codigo_tipo_documento"):
279
+ doc["codigo_tipo_documento"] = self._codes.to_english("doc_type", doc["codigo_tipo_documento"])
280
+ return data
219
281
 
220
282
  def close(self) -> None:
221
283
  self._http.close()
@@ -0,0 +1,65 @@
1
+ """Public-code translation at the SDK edge (English ↔ internal).
2
+
3
+ RAGfly catalog codes are OPAQUE internal identifiers that historically ended up in
4
+ Spanish (`VECTORIZADO`, `FACTURA`). The agentic frontier — MCP, SDK, CLI — speaks
5
+ ENGLISH: every catalog row has a stable public alias `codigo_*_en` (`VECTORIZED`,
6
+ `INVOICE`) that points to the SAME row.
7
+
8
+ The SDK talks English to the developer but the underlying REST API still speaks the
9
+ internal codes. This module fetches the `{internal: english}` map from
10
+ `GET /catalogo/public-codes` (the same source the MCP server uses) and translates at
11
+ the SDK edge: internal on the wire, English in your code.
12
+
13
+ The map only changes with a catalog migration, so it is fetched once and cached for
14
+ the client's lifetime. Translation is fail-open: an unknown code passes through
15
+ untouched, so the SDK never hides a value it can't map.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from typing import Optional
21
+
22
+
23
+ class CodeTranslator:
24
+ """Lazily fetches and caches the public-code map, and translates both ways."""
25
+
26
+ def __init__(self, fetch_map):
27
+ # fetch_map: () -> dict[str, dict[str, str]] (domain -> {internal: english})
28
+ self._fetch_map = fetch_map
29
+ self._to_english: Optional[dict[str, dict[str, str]]] = None
30
+ self._to_internal: Optional[dict[str, dict[str, str]]] = None
31
+
32
+ def _ensure_loaded(self) -> None:
33
+ if self._to_english is not None:
34
+ return
35
+ try:
36
+ mapa = self._fetch_map() or {}
37
+ except Exception:
38
+ # If the map can't be fetched, degrade to identity (never break calls).
39
+ mapa = {}
40
+ self._to_english = {dom: dict(t) for dom, t in mapa.items()}
41
+ self._to_internal = {
42
+ dom: {en: internal for internal, en in t.items()}
43
+ for dom, t in mapa.items()
44
+ }
45
+
46
+ def to_english(self, domain: str, internal_code: Optional[str]) -> Optional[str]:
47
+ """internal → English. Unknown codes pass through. None → None."""
48
+ if not internal_code:
49
+ return internal_code
50
+ self._ensure_loaded()
51
+ return self._to_english.get(domain, {}).get(internal_code, internal_code)
52
+
53
+ def to_internal(self, domain: str, public_code: Optional[str]) -> Optional[str]:
54
+ """English → internal. Accepts an internal code too (bilingual during the
55
+ transition). Unknown codes pass through. None → None."""
56
+ if not public_code:
57
+ return public_code
58
+ self._ensure_loaded()
59
+ table = self._to_internal.get(domain, {})
60
+ if public_code in table:
61
+ return table[public_code]
62
+ # Already an internal code? (caller passed the internal one out of habit)
63
+ if public_code in self._to_english.get(domain, {}):
64
+ return public_code
65
+ return public_code
File without changes
File without changes
File without changes
File without changes