ragfly 0.2.0__tar.gz → 0.4.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,16 @@
1
+ # Changelog
2
+
3
+ ## 0.4.0 — 2026-10-07
4
+
5
+ - `ask(..., mode="help")` answers questions about RAGfly itself (how to use or integrate it), without links to web screens. `mode` is only sent when given.
6
+ - `search(..., space_id=...)` limits a search to one working space.
7
+ - New `search_filtered(query, filter=...)`, `list_document_types()` and `list_characteristics()` for the structured `filter` of `/v1/documents/search`.
8
+
9
+ ## 0.3.0
10
+
11
+ - Talks only to the English REST `/v1` contract. An API key no longer reaches internal routes, so 0.2.0 stops working with API keys.
12
+ - One method per `/v1` route, plus `list_operations`, `get_operation` and `run_operation` for every operation of the RAGfly application.
13
+ - English models: `Document(code, name, summary, …)`, `Chunk(text, page, extra)`, `SearchResult(total_documents, …)`, `AskResponse(answer, conversation_id, extra)`.
14
+ - `RAGflyError` carries the public `code` and `details`.
15
+ - Removed: `ask(stream=True)` (`/v1/ask` returns the full answer), the client-side code translator and the Spanish `estado` alias.
16
+ - Every request sends `X-RAGfly-Client: sdk-python`.
ragfly-0.4.0/PKG-INFO ADDED
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.5
2
+ Name: ragfly
3
+ Version: 0.4.0
4
+ Summary: RAGfly Python SDK — RAG service 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/RAGfly/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). It speaks the English REST `/v1` contract.
16
+
17
+ > Using TypeScript/JavaScript? See the [TypeScript SDK](https://github.com/RAGfly/ragfly-typescript) (`npm install @ragfly/sdk`) — same surface.
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ pip install ragfly
23
+ ```
24
+
25
+ ## Quick start
26
+
27
+ ```python
28
+ from ragfly import RAGfly
29
+
30
+ client = RAGfly(api_key="rf_...")
31
+
32
+ # RAG end to end
33
+ print(client.ask("What are the Q1 sales figures?").answer)
34
+
35
+ # Retrieval only
36
+ results = client.search("maintenance contracts", limit=5)
37
+ for doc in results.documents:
38
+ print(doc.name, doc.max_similarity)
39
+ ```
40
+
41
+ ## Operations
42
+
43
+ Everything the RAGfly application lets your user do is available as an operation, with the same permissions and audit as the web app.
44
+
45
+ ```python
46
+ ops = client.list_operations()["operations"] # what this key can run
47
+ schema = client.get_operation("document_types.update") # input_schema / output_schema
48
+
49
+ client.run_operation("document_types.update", {"code": "TDOC_...", "name": "Invoices"})
50
+
51
+ # write_confirm operations (deletes, reverts, resets) need confirm=True
52
+ preview = client.run_operation("document_types.delete", {"code": "TDOC_..."})
53
+ assert preview["executed"] is False
54
+ client.run_operation("document_types.delete", {"code": "TDOC_..."}, confirm=True)
55
+ ```
56
+
57
+ Errors raise `RAGflyError` with `status_code`, the public `code` (`NOT_FOUND`, `VALIDATION_ERROR`, …) and `details`.
58
+
59
+ ## API keys
60
+
61
+ Create an API key from [app.ragfly.ai](https://app.ragfly.ai) → API Keys. A key only works on `/v1`; creating or revoking keys needs a signed-in person.
62
+
63
+ ## Methods
64
+
65
+ | Area | Methods |
66
+ |------|---------|
67
+ | Session and documents | `session`, `list_documents`, `get_document`, `document_edges`, `search`, `search_filtered` |
68
+ | Working spaces | `list_spaces`, `get_space`, `refresh_space`, `promote_space`, `compose_spaces`, `read_space` |
69
+ | Queue, catalog, skills | `queue`, `list_runs`, `catalog`, `list_document_types`, `list_characteristics`, `get_function`, `list_skills`, `get_skill`, `run_skill` |
70
+ | Answers and agents | `ask`, `agent_context`, `run_agent_tool` |
71
+ | Organization | `get_organization`, `update_organization`, `draft_organization` |
72
+ | Usage, conversations, processes | `get_usage`, `list_conversations`, `delete_conversation`, `list_processes`, `get_process`, `update_process` |
73
+ | Operations | `list_operations`, `get_operation`, `run_operation` |
74
+
75
+ ## Links
76
+
77
+ - Docs: https://api.ragfly.ai/docs
78
+ - Site: https://ragfly.ai
ragfly-0.4.0/README.md ADDED
@@ -0,0 +1,66 @@
1
+ # RAGfly Python SDK
2
+
3
+ Official Python client for [RAGfly](https://ragfly.ai). It speaks the English REST `/v1` contract.
4
+
5
+ > Using TypeScript/JavaScript? See the [TypeScript SDK](https://github.com/RAGfly/ragfly-typescript) (`npm install @ragfly/sdk`) — same surface.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pip install ragfly
11
+ ```
12
+
13
+ ## Quick start
14
+
15
+ ```python
16
+ from ragfly import RAGfly
17
+
18
+ client = RAGfly(api_key="rf_...")
19
+
20
+ # RAG end to end
21
+ print(client.ask("What are the Q1 sales figures?").answer)
22
+
23
+ # Retrieval only
24
+ results = client.search("maintenance contracts", limit=5)
25
+ for doc in results.documents:
26
+ print(doc.name, doc.max_similarity)
27
+ ```
28
+
29
+ ## Operations
30
+
31
+ Everything the RAGfly application lets your user do is available as an operation, with the same permissions and audit as the web app.
32
+
33
+ ```python
34
+ ops = client.list_operations()["operations"] # what this key can run
35
+ schema = client.get_operation("document_types.update") # input_schema / output_schema
36
+
37
+ client.run_operation("document_types.update", {"code": "TDOC_...", "name": "Invoices"})
38
+
39
+ # write_confirm operations (deletes, reverts, resets) need confirm=True
40
+ preview = client.run_operation("document_types.delete", {"code": "TDOC_..."})
41
+ assert preview["executed"] is False
42
+ client.run_operation("document_types.delete", {"code": "TDOC_..."}, confirm=True)
43
+ ```
44
+
45
+ Errors raise `RAGflyError` with `status_code`, the public `code` (`NOT_FOUND`, `VALIDATION_ERROR`, …) and `details`.
46
+
47
+ ## API keys
48
+
49
+ Create an API key from [app.ragfly.ai](https://app.ragfly.ai) → API Keys. A key only works on `/v1`; creating or revoking keys needs a signed-in person.
50
+
51
+ ## Methods
52
+
53
+ | Area | Methods |
54
+ |------|---------|
55
+ | Session and documents | `session`, `list_documents`, `get_document`, `document_edges`, `search`, `search_filtered` |
56
+ | Working spaces | `list_spaces`, `get_space`, `refresh_space`, `promote_space`, `compose_spaces`, `read_space` |
57
+ | Queue, catalog, skills | `queue`, `list_runs`, `catalog`, `list_document_types`, `list_characteristics`, `get_function`, `list_skills`, `get_skill`, `run_skill` |
58
+ | Answers and agents | `ask`, `agent_context`, `run_agent_tool` |
59
+ | Organization | `get_organization`, `update_organization`, `draft_organization` |
60
+ | Usage, conversations, processes | `get_usage`, `list_conversations`, `delete_conversation`, `list_processes`, `get_process`, `update_process` |
61
+ | Operations | `list_operations`, `get_operation`, `run_operation` |
62
+
63
+ ## Links
64
+
65
+ - Docs: https://api.ragfly.ai/docs
66
+ - Site: https://ragfly.ai
@@ -0,0 +1,16 @@
1
+ """Basic RAGfly SDK example."""
2
+ from ragfly import RAGfly
3
+
4
+ client = RAGfly(api_key="rf_your_api_key")
5
+
6
+ print(client.ask("What are the Q1 sales figures?").answer)
7
+
8
+ results = client.search("maintenance contracts", limit=5)
9
+ print(f"\n{results.total_documents} documents found")
10
+ for doc in results.documents:
11
+ print(f" · {doc.name} (score: {doc.rrf_score or 0:.3f})")
12
+ for chunk in doc.chunks[:1]:
13
+ print(f' "{chunk.text[:120]}…"')
14
+
15
+ for op in client.list_operations()["operations"][:5]:
16
+ print(op["code"], op["kind"])
@@ -4,8 +4,8 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "ragfly"
7
- version = "0.2.0"
8
- description = "RAGfly Python SDK — retrieval infrastructure for your AI agents"
7
+ version = "0.4.0"
8
+ description = "RAGfly Python SDK — RAG service for your AI agents"
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
11
11
  requires-python = ">=3.10"
@@ -16,7 +16,7 @@ dependencies = [
16
16
  [project.urls]
17
17
  Homepage = "https://ragfly.ai"
18
18
  Documentation = "https://api.ragfly.ai/docs"
19
- Repository = "https://github.com/rufinocabreragaillard/ragfly-python"
19
+ Repository = "https://github.com/RAGfly/ragfly-python"
20
20
 
21
21
  [tool.hatch.build.targets.wheel]
22
22
  packages = ["ragfly"]
@@ -0,0 +1,21 @@
1
+ from .client import RAGfly, RAGflyError
2
+ from .models import (
3
+ AgentContext,
4
+ AgentLayer,
5
+ AskResponse,
6
+ Chunk,
7
+ Document,
8
+ SearchResult,
9
+ )
10
+
11
+ __all__ = [
12
+ "RAGfly",
13
+ "RAGflyError",
14
+ "SearchResult",
15
+ "AskResponse",
16
+ "Document",
17
+ "Chunk",
18
+ "AgentContext",
19
+ "AgentLayer",
20
+ ]
21
+ __version__ = "0.4.0"
@@ -0,0 +1,418 @@
1
+ """RAGfly Python SDK — official client for the English REST ``/v1`` contract."""
2
+
3
+ from typing import Any, Optional
4
+ from urllib.parse import quote
5
+
6
+ import httpx
7
+
8
+ from .models import AgentContext, AgentLayer, AskResponse, Chunk, Document, SearchResult
9
+
10
+ DEFAULT_BASE_URL = "https://api.ragfly.ai"
11
+ #: Default interface function for ``ask()`` (sets the conversation's LLM model).
12
+ DEFAULT_FUNCTION = "CHAT-USER"
13
+ CLIENT_HEADER = {"X-RAGfly-Client": "sdk-python"}
14
+
15
+
16
+ class RAGflyError(Exception):
17
+ """A ``/v1`` error: ``status_code``, public ``code`` (e.g. ``NOT_FOUND``) and ``details``."""
18
+
19
+ def __init__(
20
+ self,
21
+ message: str,
22
+ status_code: Optional[int] = None,
23
+ code: Optional[str] = None,
24
+ details: Optional[dict] = None,
25
+ ):
26
+ super().__init__(message)
27
+ self.status_code = status_code
28
+ self.code = code
29
+ self.details = details or {}
30
+
31
+
32
+ def _segment(value: Any) -> str:
33
+ return quote(str(value), safe="")
34
+
35
+
36
+ def _compact(values: dict) -> dict:
37
+ return {key: value for key, value in values.items() if value is not None}
38
+
39
+
40
+ def _query(values: dict) -> dict:
41
+ return {key: ("true" if value is True else "false" if value is False else value) for key, value in _compact(values).items()}
42
+
43
+
44
+ class RAGfly:
45
+ """Official RAGfly client.
46
+
47
+ Basic usage::
48
+
49
+ from ragfly import RAGfly
50
+
51
+ client = RAGfly(api_key="rf_...")
52
+ print(client.ask("What were Q1 sales?").answer)
53
+
54
+ Every method maps to one ``/v1`` route. Operations of the RAGfly
55
+ application that have no named route run through :meth:`list_operations`,
56
+ :meth:`get_operation` and :meth:`run_operation`.
57
+ """
58
+
59
+ def __init__(
60
+ self,
61
+ api_key: str,
62
+ base_url: str = DEFAULT_BASE_URL,
63
+ timeout: float = 60.0,
64
+ *,
65
+ transport: Optional[httpx.BaseTransport] = None,
66
+ ):
67
+ self._base_url = base_url.rstrip("/")
68
+ self._http = httpx.Client(
69
+ timeout=httpx.Timeout(timeout, connect=10.0),
70
+ headers={"Authorization": f"Bearer {api_key}", **CLIENT_HEADER},
71
+ transport=transport,
72
+ )
73
+
74
+ # ── Transport ────────────────────────────────────────────────────────────
75
+
76
+ def _request(self, method: str, path: str, *, params: Optional[dict] = None, body: Any = None) -> Any:
77
+ resp = self._http.request(
78
+ method,
79
+ f"{self._base_url}{path}",
80
+ params=_query(params or {}) or None,
81
+ json=body,
82
+ )
83
+ if resp.status_code >= 400:
84
+ try:
85
+ payload = resp.json()
86
+ except ValueError:
87
+ payload = {}
88
+ payload = payload if isinstance(payload, dict) else {}
89
+ raise RAGflyError(
90
+ payload.get("message") or resp.text or f"HTTP {resp.status_code}",
91
+ status_code=resp.status_code,
92
+ code=payload.get("code"),
93
+ details=payload.get("details"),
94
+ )
95
+ if not resp.content:
96
+ return None
97
+ return resp.json()
98
+
99
+ # ── Session and documents ────────────────────────────────────────────────
100
+
101
+ def session(self) -> dict:
102
+ """Identity, group and entity of the credential."""
103
+ return self._request("GET", "/v1/session")
104
+
105
+ def set_active_entity(self, entity_code: Optional[str]) -> dict:
106
+ """Set an authorized entity focus; pass ``None`` to release it."""
107
+ return self._request(
108
+ "POST", "/v1/session/active-entity", body={"entity_code": entity_code}
109
+ )
110
+
111
+ def list_documents(self, *, status: Optional[str] = None, limit: int = 20, page: int = 1) -> dict:
112
+ """List documents. ``status`` in English, e.g. ``VECTORIZED``."""
113
+ return self._request("GET", "/v1/documents", params={"status": status, "limit": limit, "page": page})
114
+
115
+ def get_document(self, document_code: str) -> dict:
116
+ return self._request("GET", f"/v1/documents/{_segment(document_code)}")
117
+
118
+ def document_edges(self, document_code: str, *, neighbor_limit: int = 50) -> dict:
119
+ return self._request(
120
+ "GET", f"/v1/documents/{_segment(document_code)}/edges", params={"neighbor_limit": neighbor_limit}
121
+ )
122
+
123
+ def search(
124
+ self,
125
+ query: str,
126
+ *,
127
+ limit: int = 10,
128
+ min_similarity: float = 0.0,
129
+ entity_code: Optional[str] = None,
130
+ space_id: Optional[int] = None,
131
+ ) -> SearchResult:
132
+ """Hybrid semantic search (vector + lexical). ``space_id`` limits it to one working space."""
133
+ return self._search({
134
+ "query": query, "limit": limit, "min_similarity": min_similarity,
135
+ "entity_code": entity_code, "space_id": space_id,
136
+ }, query)
137
+
138
+ def search_filtered(
139
+ self,
140
+ query: str,
141
+ *,
142
+ filter: dict,
143
+ limit: Optional[int] = None,
144
+ min_similarity: Optional[float] = None,
145
+ entity_code: Optional[str] = None,
146
+ space_id: Optional[int] = None,
147
+ ) -> SearchResult:
148
+ """Search with a structured ``filter`` (``document_types``, ``attributes``, ``characteristics``).
149
+
150
+ The catalog codes the filter accepts come from :meth:`list_document_types` and
151
+ :meth:`list_characteristics`.
152
+ """
153
+ if not isinstance(filter, dict):
154
+ raise TypeError("filter must be a dict")
155
+ return self._search({
156
+ "query": query, "filter": filter, "limit": limit, "min_similarity": min_similarity,
157
+ "entity_code": entity_code, "space_id": space_id,
158
+ }, query)
159
+
160
+ def _search(self, body: dict, query: str) -> SearchResult:
161
+ data = self._request("POST", "/v1/documents/search", body=_compact(body)) or {}
162
+ documents = [
163
+ Document(
164
+ code=d.get("code"),
165
+ name=d.get("name"),
166
+ summary=d.get("summary"),
167
+ location=d.get("location"),
168
+ url=d.get("url"),
169
+ rrf_score=d.get("rrf_score"),
170
+ max_similarity=d.get("max_similarity"),
171
+ rerank_score=d.get("rerank_score"),
172
+ fs=d.get("fs"),
173
+ chunks=[
174
+ Chunk(text=c.get("text", ""), page=c.get("page"), extra=c.get("extra") or {})
175
+ for c in d.get("chunks") or []
176
+ ],
177
+ )
178
+ for d in data.get("documents") or []
179
+ ]
180
+ return SearchResult(
181
+ query=query,
182
+ total_documents=data.get("total_documents", len(documents)),
183
+ total_chunks=data.get("total_chunks", 0),
184
+ duration_ms=data.get("duration_ms"),
185
+ documents=documents,
186
+ )
187
+
188
+ # ── Working spaces ───────────────────────────────────────────────────────
189
+
190
+ def list_spaces(self, *, limit: int = 20) -> dict:
191
+ return self._request("GET", "/v1/spaces", params={"limit": limit})
192
+
193
+ def get_space(self, space_id: int, *, document_limit: int = 20) -> dict:
194
+ return self._request("GET", f"/v1/spaces/{_segment(space_id)}", params={"document_limit": document_limit})
195
+
196
+ def refresh_space(self, space_id: int) -> dict:
197
+ return self._request("POST", f"/v1/spaces/{_segment(space_id)}/refresh")
198
+
199
+ def promote_space(self, space_id: int) -> dict:
200
+ return self._request("POST", f"/v1/spaces/{_segment(space_id)}/promote")
201
+
202
+ def compose_spaces(
203
+ self, operation: str, space_id_a: int, space_id_b: int, *, name: str = "", space_type: str = "AREA"
204
+ ) -> dict:
205
+ """``operation``: union, intersection, difference or symmetric_difference."""
206
+ return self._request("POST", "/v1/spaces/compose", body={
207
+ "operation": operation, "space_id_a": space_id_a, "space_id_b": space_id_b,
208
+ "name": name, "space_type": space_type,
209
+ })
210
+
211
+ def read_space(self, space_id: int, *, resolution: str = "manifest", query: str = "", limit: int = 50) -> dict:
212
+ """``resolution``: count, manifest, chunks or text."""
213
+ return self._request(
214
+ "POST", f"/v1/spaces/{_segment(space_id)}/read",
215
+ body={"resolution": resolution, "query": query, "limit": limit},
216
+ )
217
+
218
+ # ── Queue, catalog and skills ────────────────────────────────────────────
219
+
220
+ def queue(self, *, process: Optional[str] = None, status: Optional[str] = None, limit: int = 20) -> dict:
221
+ return self._request("GET", "/v1/queue", params={"process": process, "status": status, "limit": limit})
222
+
223
+ def list_runs(self, *, limit: int = 10) -> dict:
224
+ return self._request("GET", "/v1/runs", params={"limit": limit})
225
+
226
+ def catalog(self, *, type: str = "ALL") -> dict:
227
+ """``type``: ALL, FUNCTIONS or SKILLS."""
228
+ return self._request("GET", "/v1/catalog", params={"type": type})
229
+
230
+ def list_document_types(self, *, entity_code: Optional[str] = None) -> dict:
231
+ """Document types of the entity as a tree. Their codes go in ``filter.document_types``."""
232
+ return self._request("GET", "/v1/catalog/document-types", params=_query({"entity_code": entity_code}))
233
+
234
+ def list_characteristics(
235
+ self, *, document_types: Optional[list] = None, entity_code: Optional[str] = None
236
+ ) -> dict:
237
+ """Characteristics available for those types (each includes its more specific types)."""
238
+ return self._request("GET", "/v1/catalog/characteristics", params=_query({
239
+ "document_types": ",".join(document_types) if document_types else None, "entity_code": entity_code,
240
+ }))
241
+
242
+ def get_function(self, function_code: str) -> dict:
243
+ """A function (screen) with its behaviors and the operations it allows."""
244
+ return self._request("GET", f"/v1/functions/{_segment(function_code)}")
245
+
246
+ def list_skills(self) -> dict:
247
+ return self._request("GET", "/v1/skills")
248
+
249
+ def get_skill(self, skill_code: str) -> dict:
250
+ return self._request("GET", f"/v1/skills/{_segment(skill_code)}")
251
+
252
+ def run_skill(self, skill_code: str, *, space_id: Optional[int] = None, document_code: Optional[str] = None) -> dict:
253
+ return self._request(
254
+ "POST", f"/v1/skills/{_segment(skill_code)}/run",
255
+ body=_compact({"space_id": space_id, "document_code": document_code}),
256
+ )
257
+
258
+ # ── Answers and agents ───────────────────────────────────────────────────
259
+
260
+ def ask(
261
+ self,
262
+ question: str,
263
+ *,
264
+ conversation_id: Optional[int] = None,
265
+ function_code: str = DEFAULT_FUNCTION,
266
+ mode: Optional[str] = None,
267
+ ) -> AskResponse:
268
+ """RAG end to end: retrieve and generate. Reuse ``conversation_id`` to continue.
269
+
270
+ ``mode="help"`` answers questions about RAGfly itself (how to use or integrate it)
271
+ instead of searching your documents, without links to web screens. Left as ``None``
272
+ the call is the usual document answer.
273
+ """
274
+ if mode not in (None, "default", "help"):
275
+ raise ValueError("mode must be 'default' or 'help'")
276
+ data = self._request("POST", "/v1/ask", body=_compact({
277
+ "question": question, "conversation_id": conversation_id, "function_code": function_code, "mode": mode,
278
+ })) or {}
279
+ return AskResponse(
280
+ answer=data.get("answer", ""),
281
+ conversation_id=data.get("conversation_id"),
282
+ extra={k: v for k, v in data.items() if k not in {"answer", "conversation_id"}},
283
+ )
284
+
285
+ def agent_context(self, *, function_profile: str = "user_chat") -> AgentContext:
286
+ """The authenticated prompt, identity and tools for an agent."""
287
+ data = self._request("GET", "/v1/agent/context", params={"function_profile": function_profile})
288
+ return AgentContext(
289
+ function_profile=data["function_profile"],
290
+ system_prompt=data["system_prompt"],
291
+ system_prompt_hash=data["system_prompt_hash"],
292
+ # Only the model's fields: a field the server adds later must not break the client.
293
+ layers=[
294
+ AgentLayer(code=item.get("code", ""), name=item.get("name", ""), sha256=item.get("sha256", ""))
295
+ for item in data.get("layers", [])
296
+ if isinstance(item, dict)
297
+ ],
298
+ identity=data.get("identity") or {},
299
+ tools=data.get("tools") or [],
300
+ limits=data.get("limits") or {},
301
+ )
302
+
303
+ def run_agent_tool(self, public_name: str, arguments: dict, *, function_profile: str = "user_chat") -> Any:
304
+ """Run one tool authorized by :meth:`agent_context`."""
305
+ if not isinstance(arguments, dict):
306
+ raise TypeError("arguments must be a dict")
307
+ return self._request(
308
+ "POST", f"/v1/agent/tools/{_segment(public_name)}",
309
+ body={"arguments": arguments, "function_profile": function_profile},
310
+ )
311
+
312
+ # ── Organization profile ─────────────────────────────────────────────────
313
+
314
+ def get_organization(self, *, entity_code: Optional[str] = None) -> dict:
315
+ return self._request("GET", "/v1/organization", params={"entity_code": entity_code})
316
+
317
+ def update_organization(
318
+ self,
319
+ *,
320
+ group_description: Optional[str] = None,
321
+ group_system_prompt: Optional[str] = None,
322
+ entity_description: Optional[str] = None,
323
+ entity_system_prompt: Optional[str] = None,
324
+ entity_code: Optional[str] = None,
325
+ ) -> dict:
326
+ """Only the fields you pass are written."""
327
+ return self._request("PUT", "/v1/organization", body=_compact({
328
+ "group_description": group_description,
329
+ "group_system_prompt": group_system_prompt,
330
+ "entity_description": entity_description,
331
+ "entity_system_prompt": entity_system_prompt,
332
+ "entity_code": entity_code,
333
+ }))
334
+
335
+ def draft_organization(self, *, source_text: str = "", entity_code: Optional[str] = None) -> dict:
336
+ return self._request(
337
+ "POST", "/v1/organization/draft", body=_compact({"source_text": source_text, "entity_code": entity_code})
338
+ )
339
+
340
+ # ── Usage, conversations and processes ───────────────────────────────────
341
+
342
+ def get_usage(self) -> dict:
343
+ return self._request("GET", "/v1/usage")
344
+
345
+ def list_conversations(self, *, function_code: Optional[str] = None, limit: int = 50) -> dict:
346
+ return self._request("GET", "/v1/conversations", params={"function_code": function_code, "limit": limit})
347
+
348
+ def delete_conversation(self, conversation_id: int) -> Any:
349
+ return self._request("DELETE", f"/v1/conversations/{_segment(conversation_id)}")
350
+
351
+ def list_processes(
352
+ self,
353
+ *,
354
+ status: Optional[str] = None,
355
+ process_type: Optional[str] = None,
356
+ category: Optional[str] = None,
357
+ mine: Optional[bool] = None,
358
+ only_open: Optional[bool] = None,
359
+ limit: int = 20,
360
+ page: int = 1,
361
+ ) -> dict:
362
+ return self._request("GET", "/v1/processes", params={
363
+ "status": status, "process_type": process_type, "category": category,
364
+ "mine": mine, "only_open": only_open, "limit": limit, "page": page,
365
+ })
366
+
367
+ def get_process(self, process_code: str) -> dict:
368
+ return self._request("GET", f"/v1/processes/{_segment(process_code)}")
369
+
370
+ def update_process(
371
+ self,
372
+ process_code: str,
373
+ *,
374
+ status: Optional[str] = None,
375
+ priority: Optional[str] = None,
376
+ name: Optional[str] = None,
377
+ description: Optional[str] = None,
378
+ comments: Optional[str] = None,
379
+ assigned_to: Optional[str] = None,
380
+ due_at: Optional[str] = None,
381
+ finished_at: Optional[str] = None,
382
+ cost: Optional[float] = None,
383
+ ) -> dict:
384
+ """Only the fields you pass are written."""
385
+ return self._request("PATCH", f"/v1/processes/{_segment(process_code)}", body=_compact({
386
+ "status": status, "priority": priority, "name": name, "description": description,
387
+ "comments": comments, "assigned_to": assigned_to, "due_at": due_at,
388
+ "finished_at": finished_at, "cost": cost,
389
+ }))
390
+
391
+ # ── Generic operations ───────────────────────────────────────────────────
392
+
393
+ def list_operations(self) -> dict:
394
+ """Operations this credential can run: code, kind and confirm_required."""
395
+ return self._request("GET", "/v1/operations")
396
+
397
+ def get_operation(self, code: str) -> dict:
398
+ """One operation with its ``input_schema`` and ``output_schema``."""
399
+ return self._request("GET", f"/v1/operations/{_segment(code)}")
400
+
401
+ def run_operation(self, code: str, input: Optional[dict] = None, *, confirm: bool = False) -> dict:
402
+ """Run an operation. A ``write_confirm`` operation only runs with ``confirm=True``;
403
+ without it the result is ``{"executed": False, "preview": ...}``."""
404
+ return self._request(
405
+ "POST", f"/v1/operations/{_segment(code)}:execute",
406
+ body={"input": input or {}, "confirm": bool(confirm)},
407
+ )
408
+
409
+ # ── Lifecycle ────────────────────────────────────────────────────────────
410
+
411
+ def close(self) -> None:
412
+ self._http.close()
413
+
414
+ def __enter__(self):
415
+ return self
416
+
417
+ def __exit__(self, *_):
418
+ self.close()