ragfly 0.1.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,7 @@
1
+ __pycache__/
2
+ *.pyc
3
+ *.egg-info/
4
+ dist/
5
+ build/
6
+ .venv/
7
+ .env
ragfly-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,59 @@
1
+ Metadata-Version: 2.4
2
+ Name: ragfly
3
+ Version: 0.1.0
4
+ Summary: RAGfly Python SDK — retrieval infrastructure for your AI agents
5
+ Project-URL: Homepage, https://ragfly.ai
6
+ Project-URL: Documentation, https://api.ragfly.ai/docs
7
+ Project-URL: Repository, https://github.com/rufinocabreragaillard/ragfly-python
8
+ License: MIT
9
+ Requires-Python: >=3.10
10
+ Requires-Dist: httpx>=0.27
11
+ Description-Content-Type: text/markdown
12
+
13
+ # RAGfly Python SDK
14
+
15
+ Official Python client for [RAGfly](https://ragfly.ai) — retrieval infrastructure for your AI agents.
16
+
17
+ ## Install
18
+
19
+ ```bash
20
+ pip install ragfly
21
+ ```
22
+
23
+ ## Quick start
24
+
25
+ ```python
26
+ from ragfly import RAGfly
27
+
28
+ client = RAGfly(api_key="rfly_...")
29
+
30
+ # Ask a question (RAG end-to-end)
31
+ resp = client.ask("What are the Q1 sales figures?")
32
+ print(resp.answer)
33
+
34
+ # Streaming
35
+ for chunk in client.ask("Summarize active contracts", stream=True):
36
+ print(chunk.delta, end="", flush=True)
37
+
38
+ # Semantic search (retrieval only)
39
+ results = client.search("maintenance contracts", limit=5)
40
+ for doc in results.documents:
41
+ print(doc.nombre, doc.similitud_max)
42
+ ```
43
+
44
+ ## API Keys
45
+
46
+ Generate an API key from [app.ragfly.ai](https://app.ragfly.ai) → Settings → API Keys.
47
+
48
+ ## Methods
49
+
50
+ | Method | Description |
51
+ |--------|-------------|
52
+ | `client.ask(question, *, stream=False, conversation_id=None)` | RAG end-to-end: retrieve + generate |
53
+ | `client.search(query, *, limit=10, min_similitud=0.0)` | Hybrid retrieval (vector + lexical + rerank) |
54
+ | `client.list_documents(*, page=1, page_size=20)` | List corpus documents |
55
+
56
+ ## Links
57
+
58
+ - Docs: https://api.ragfly.ai/docs
59
+ - Site: https://ragfly.ai
ragfly-0.1.0/README.md ADDED
@@ -0,0 +1,47 @@
1
+ # RAGfly Python SDK
2
+
3
+ Official Python client for [RAGfly](https://ragfly.ai) — retrieval infrastructure for your AI agents.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pip install ragfly
9
+ ```
10
+
11
+ ## Quick start
12
+
13
+ ```python
14
+ from ragfly import RAGfly
15
+
16
+ client = RAGfly(api_key="rfly_...")
17
+
18
+ # Ask a question (RAG end-to-end)
19
+ resp = client.ask("What are the Q1 sales figures?")
20
+ print(resp.answer)
21
+
22
+ # Streaming
23
+ for chunk in client.ask("Summarize active contracts", stream=True):
24
+ print(chunk.delta, end="", flush=True)
25
+
26
+ # Semantic search (retrieval only)
27
+ results = client.search("maintenance contracts", limit=5)
28
+ for doc in results.documents:
29
+ print(doc.nombre, doc.similitud_max)
30
+ ```
31
+
32
+ ## API Keys
33
+
34
+ Generate an API key from [app.ragfly.ai](https://app.ragfly.ai) → Settings → API Keys.
35
+
36
+ ## Methods
37
+
38
+ | Method | Description |
39
+ |--------|-------------|
40
+ | `client.ask(question, *, stream=False, conversation_id=None)` | RAG end-to-end: retrieve + generate |
41
+ | `client.search(query, *, limit=10, min_similitud=0.0)` | Hybrid retrieval (vector + lexical + rerank) |
42
+ | `client.list_documents(*, page=1, page_size=20)` | List corpus documents |
43
+
44
+ ## Links
45
+
46
+ - Docs: https://api.ragfly.ai/docs
47
+ - Site: https://ragfly.ai
@@ -0,0 +1,22 @@
1
+ """Ejemplo básico del SDK de RAGfly."""
2
+ from ragfly import RAGfly
3
+
4
+ client = RAGfly(api_key="rfly_tu_api_key")
5
+
6
+ # Pregunta simple (respuesta completa)
7
+ resp = client.ask("¿Cuáles son las ventas del Q1?")
8
+ print(resp.answer)
9
+
10
+ # Pregunta con streaming
11
+ print("\n--- Streaming ---")
12
+ for chunk in client.ask("Resumí los contratos vigentes", stream=True):
13
+ print(chunk.delta, end="", flush=True)
14
+ print()
15
+
16
+ # Búsqueda semántica (solo retrieval, sin generación)
17
+ results = client.search("contratos de mantenimiento", limit=5)
18
+ print(f"\n{results.total_documentos} documentos encontrados")
19
+ for doc in results.documents:
20
+ print(f" · {doc.nombre} (score: {doc.rrf_score:.3f})")
21
+ for chunk in doc.chunks[:1]:
22
+ print(f" "{chunk.texto[:120]}…"")
@@ -0,0 +1,22 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "ragfly"
7
+ version = "0.1.0"
8
+ description = "RAGfly Python SDK — retrieval infrastructure for your AI agents"
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.10"
12
+ dependencies = [
13
+ "httpx>=0.27",
14
+ ]
15
+
16
+ [project.urls]
17
+ Homepage = "https://ragfly.ai"
18
+ Documentation = "https://api.ragfly.ai/docs"
19
+ Repository = "https://github.com/rufinocabreragaillard/ragfly-python"
20
+
21
+ [tool.hatch.build.targets.wheel]
22
+ packages = ["ragfly"]
@@ -0,0 +1,5 @@
1
+ from .client import RAGfly
2
+ from .models import SearchResult, AskResponse, AskChunk, Document, Chunk
3
+
4
+ __all__ = ["RAGfly", "SearchResult", "AskResponse", "AskChunk", "Document", "Chunk"]
5
+ __version__ = "0.1.0"
@@ -0,0 +1,210 @@
1
+ """RAGfly Python SDK — cliente oficial."""
2
+
3
+ import json
4
+ from typing import Generator, Iterator, Optional, Union
5
+ from urllib.parse import urljoin
6
+
7
+ import httpx
8
+
9
+ from .models import AskChunk, AskResponse, Chunk, Document, SearchResult
10
+
11
+ DEFAULT_BASE_URL = "https://api.ragfly.ai"
12
+ _TIMEOUT = httpx.Timeout(60.0, connect=10.0)
13
+
14
+
15
+ class RAGflyError(Exception):
16
+ def __init__(self, message: str, status_code: Optional[int] = None):
17
+ super().__init__(message)
18
+ self.status_code = status_code
19
+
20
+
21
+ class RAGfly:
22
+ """Cliente oficial de RAGfly.
23
+
24
+ Uso básico::
25
+
26
+ from ragfly import RAGfly
27
+
28
+ client = RAGfly(api_key="rfly_...")
29
+ resp = client.ask("¿Cuáles son las ventas de Q1?")
30
+ print(resp.answer)
31
+
32
+ Streaming::
33
+
34
+ for chunk in client.ask("¿Cuáles son las ventas de Q1?", stream=True):
35
+ print(chunk.delta, end="", flush=True)
36
+ """
37
+
38
+ def __init__(
39
+ self,
40
+ api_key: str,
41
+ base_url: str = DEFAULT_BASE_URL,
42
+ timeout: float = 60.0,
43
+ ):
44
+ self._api_key = api_key
45
+ self._base_url = base_url.rstrip("/")
46
+ self._http = httpx.Client(
47
+ timeout=httpx.Timeout(timeout, connect=10.0),
48
+ headers={"Authorization": f"Bearer {api_key}"},
49
+ )
50
+ self._async_http: Optional[httpx.AsyncClient] = None
51
+
52
+ # ── Internos ─────────────────────────────────────────────────────────────
53
+
54
+ def _url(self, path: str) -> str:
55
+ return f"{self._base_url}/{path.lstrip('/')}"
56
+
57
+ def _raise_for_status(self, resp: httpx.Response) -> None:
58
+ if resp.status_code >= 400:
59
+ try:
60
+ detail = resp.json().get("detail", resp.text)
61
+ except Exception:
62
+ detail = resp.text
63
+ raise RAGflyError(detail, status_code=resp.status_code)
64
+
65
+ def _get_or_create_conversation(self) -> int:
66
+ """Crea una conversación temporal y devuelve su id."""
67
+ resp = self._http.post(self._url("/interfaz/conversaciones"), json={
68
+ "titulo": "SDK",
69
+ "temporal": True,
70
+ })
71
+ self._raise_for_status(resp)
72
+ return resp.json()["id"]
73
+
74
+ # ── API pública ──────────────────────────────────────────────────────────
75
+
76
+ def search(
77
+ self,
78
+ query: str,
79
+ *,
80
+ limit: int = 10,
81
+ min_similitud: float = 0.0,
82
+ codigo_entidad: Optional[str] = None,
83
+ id_espacio: Optional[int] = None,
84
+ ) -> SearchResult:
85
+ """Búsqueda semántica híbrida (vector + léxico + rerank).
86
+
87
+ Returns:
88
+ :class:`SearchResult` con lista de documentos y sus chunks relevantes.
89
+ """
90
+ payload = {
91
+ "q": query,
92
+ "limit": limit,
93
+ "min_similitud": min_similitud,
94
+ }
95
+ if codigo_entidad:
96
+ payload["codigo_entidad"] = codigo_entidad
97
+ if id_espacio:
98
+ payload["id_espacio"] = id_espacio
99
+
100
+ resp = self._http.post(self._url("/documentos/buscar-semantico"), json=payload)
101
+ self._raise_for_status(resp)
102
+ data = resp.json()
103
+
104
+ docs = []
105
+ for d in data.get("resultados", []):
106
+ chunks = [
107
+ Chunk(
108
+ texto=c.get("texto", ""),
109
+ similitud=c.get("similitud"),
110
+ score_rerank=c.get("score_rerank"),
111
+ pagina=c.get("pagina"),
112
+ extra={k: v for k, v in c.items() if k not in {"texto", "similitud", "score_rerank", "pagina"}},
113
+ )
114
+ for c in d.get("chunks", [])
115
+ ]
116
+ docs.append(Document(
117
+ codigo=d["codigo_documento"],
118
+ nombre=d["nombre_documento"],
119
+ resumen=d.get("resumen_documento"),
120
+ url=d.get("url"),
121
+ rrf_score=d.get("rrf_score"),
122
+ similitud_max=d.get("similitud_max"),
123
+ chunks=chunks,
124
+ ))
125
+
126
+ return SearchResult(
127
+ query=data["q"],
128
+ total_documentos=data["total_documentos"],
129
+ total_chunks=data["total_chunks"],
130
+ duracion_ms=data.get("duracion_ms"),
131
+ documents=docs,
132
+ )
133
+
134
+ def ask(
135
+ self,
136
+ question: str,
137
+ *,
138
+ conversation_id: Optional[int] = None,
139
+ stream: bool = False,
140
+ ) -> Union[AskResponse, Iterator[AskChunk]]:
141
+ """Pregunta al RAG con respuesta completa o streaming.
142
+
143
+ Args:
144
+ question: La pregunta en lenguaje natural.
145
+ conversation_id: Reusar conversación existente. Si es None, crea una temporal.
146
+ stream: Si True, devuelve un iterador de :class:`AskChunk`.
147
+
148
+ Returns:
149
+ :class:`AskResponse` (stream=False) o ``Iterator[AskChunk]`` (stream=True).
150
+ """
151
+ conv_id = conversation_id or self._get_or_create_conversation()
152
+
153
+ if stream:
154
+ return self._ask_stream(question, conv_id)
155
+ return self._ask_sync(question, conv_id)
156
+
157
+ def _ask_stream(self, question: str, conv_id: int) -> Iterator[AskChunk]:
158
+ url = self._url(f"/interfaz/conversaciones/{conv_id}/mensajes/stream")
159
+ with self._http.stream("POST", url, json={"contenido": question}) as resp:
160
+ self._raise_for_status(resp)
161
+ for line in resp.iter_lines():
162
+ if not line.startswith("data: "):
163
+ continue
164
+ try:
165
+ payload = json.loads(line[6:])
166
+ except json.JSONDecodeError:
167
+ continue
168
+ if "error" in payload:
169
+ raise RAGflyError(payload["error"])
170
+ if payload.get("done"):
171
+ return
172
+ if "text" in payload:
173
+ yield AskChunk(delta=payload["text"])
174
+
175
+ def _ask_sync(self, question: str, conv_id: int) -> AskResponse:
176
+ buffer = []
177
+ msg_id = None
178
+ for chunk in self._ask_stream(question, conv_id):
179
+ buffer.append(chunk.delta)
180
+ # El done payload lleva id_mensaje_assistant pero lo emitimos antes de salir
181
+ # del generator — capturamos el último evento done fuera del yield.
182
+ return AskResponse(
183
+ answer="".join(buffer),
184
+ conversation_id=conv_id,
185
+ message_id=msg_id,
186
+ )
187
+
188
+ def list_documents(
189
+ self,
190
+ *,
191
+ page: int = 1,
192
+ page_size: int = 20,
193
+ estado: Optional[str] = None,
194
+ ) -> dict:
195
+ """Lista documentos del corpus con paginación."""
196
+ params: dict = {"pagina": page, "limite": page_size}
197
+ if estado:
198
+ params["estado"] = estado
199
+ resp = self._http.get(self._url("/documentos/paginado"), params=params)
200
+ self._raise_for_status(resp)
201
+ return resp.json()
202
+
203
+ def close(self) -> None:
204
+ self._http.close()
205
+
206
+ def __enter__(self):
207
+ return self
208
+
209
+ def __exit__(self, *_):
210
+ self.close()
@@ -0,0 +1,45 @@
1
+ from dataclasses import dataclass, field
2
+ from typing import Optional
3
+
4
+
5
+ @dataclass
6
+ class Chunk:
7
+ texto: str
8
+ similitud: Optional[float] = None
9
+ score_rerank: Optional[float] = None
10
+ pagina: Optional[int] = None
11
+ extra: dict = field(default_factory=dict)
12
+
13
+
14
+ @dataclass
15
+ class Document:
16
+ codigo: str
17
+ nombre: str
18
+ resumen: Optional[str] = None
19
+ url: Optional[str] = None
20
+ rrf_score: Optional[float] = None
21
+ similitud_max: Optional[float] = None
22
+ chunks: list[Chunk] = field(default_factory=list)
23
+
24
+
25
+ @dataclass
26
+ class SearchResult:
27
+ query: str
28
+ total_documentos: int
29
+ total_chunks: int
30
+ duracion_ms: Optional[float]
31
+ documents: list[Document]
32
+
33
+
34
+ @dataclass
35
+ class AskChunk:
36
+ """Un token/fragmento del stream de respuesta."""
37
+ delta: str
38
+
39
+
40
+ @dataclass
41
+ class AskResponse:
42
+ """Respuesta completa (no-streaming)."""
43
+ answer: str
44
+ conversation_id: int
45
+ message_id: Optional[int] = None