¶ciel.runtime — Runtime de agentes y tools
Núcleo del runtime: DTOs de chat (ChatMessage, ChatChoice, ChatRequest,
ChatResponse), contratos de provider/modelo (ChatProvider, ModelProvider),
tool loop y despacho de herramientas (ToolProvider, DefaultToolDispatcher),
resultados de ejecución (ToolLoopResult, AgentRuntimeResult, AgentContext)
y el runtime concreto con trazas (DefaultAgentRuntime, AgentRuntime).
¶ChatMessage.content (multimodal)
ChatMessage.content es str | list[dict[str, Any]]:
str— texto plano (compatibilidad total con versiones previas).list[dict]— partes multimodales (text,image_url,input_audio). Los providers convierten estas partes a su formato nativo automáticamente.
ChatMessage.text() -> str concatena las partes de tipo "text" e ignora
imágenes/audio (ver docs/api-reference/providers.md para los serializers por
proveedor y ejemplos de partes).
¶
ciel.runtime
¶
ContentPart = Dict[str, Any]
module-attribute
¶
_DANGEROUS_TOOL_NAMES = frozenset({'shell', 'terminal', 'exec', 'file_write', 'write_file', 'code_exec', 'eval'})
module-attribute
¶
AgentContext
dataclass
¶
AgentRuntime
Async runtime contract for tool-loop execution and streaming.
Source code in src\ciel\runtime\__init__.py
¶
AgentRuntimeResult
dataclass
¶
AuditEvent
dataclass
Source code in src\ciel\observability\__init__.py
¶
ChatChoice
dataclass
¶
ChatMessage
dataclass
Source code in src\ciel\runtime\tools.py
¶
text() -> str
Extract plain text from content, tolerant to multimodal parts.
strcontent is returned verbatim.listcontent concatenates thetextof every part whose type is"text"but drops images/audio/video, so consumers (CLI, compression,AgentResponse.text) see only readable text.
Source code in src\ciel\runtime\tools.py
¶
ChatProvider
Bases: ABC
Source code in src\ciel\providers\__init__.py
¶
ChatRequest
dataclass
Source code in src\ciel\runtime\tools.py
¶
ChatResponse
dataclass
¶
CielError
¶
Curriculum
dataclass
Plan versionado (curriculum) para un objetivo del agente.
Source code in src\ciel\runtime\curriculum.py
¶
CurriculumRegistry
Registro multitenant de curricula versionados sobre un StateBackend.
Source code in src\ciel\runtime\curriculum.py
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 | |
¶
create(goal: str, plan: Sequence[str], *, tenant_id: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None) -> Curriculum
Crea la versión inicial 0.0.0 de un curriculum (o bumpea si existe).
Source code in src\ciel\runtime\curriculum.py
¶
evolution_tree(goal: str, *, tenant_id: Optional[str] = None) -> Dict[str, Any]
Árbol de linaje, misma forma que prompt_versioning.evolution_tree.
Source code in src\ciel\runtime\curriculum.py
¶
DefaultAgentRuntime
Concrete runtime wiring provider + tool execution with tracing.
Source code in src\ciel\runtime\__init__.py
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 | |
¶
run_agent_loop(*, request: ChatRequest, tenant_id: Optional[str] = None, toolset: Optional[str] = None, limit: int = 32) -> AgentRuntimeResult
async
Run the agentic tool loop (multi-turn ReAct when tools are present).
The loop issues up to limit model completions. After each completion
that requests tool calls, the requested tools are dispatched and their
results are appended as messages; the model is then called again. The
loop stops when (a) the model returns no tool calls (finish_reason
stop), (b) limit turns are exhausted, or (c) there are no tools
registered in the request.
Backward compatibility: when limit <= 1 or request.tools is
empty, exactly one completion is produced and no tool messages are
appended (the historical single-step behaviour). Every tool result from
every turn is preserved in loop_results so the facade can surface
the full tool_results list.
Source code in src\ciel\runtime\__init__.py
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 | |
¶
stream_tokens(*, request: ChatRequest, tenant_id: Optional[str] = None, toolset: Optional[str] = None) -> AsyncIterator[str]
async
Stream incremental assistant tokens from the provider.
Calls provider.stream (real SSE streaming) and re-emits the
partial content of each incremental :class:ChatResponse as it
arrives, so callers see the answer grow token by token.
Source code in src\ciel\runtime\__init__.py
¶
DefaultToolDispatcher
Dispatch tool requests to a configured ToolProvider.
Si se pasa sandbox (un :class:~ciel.sandbox.SandboxExecutor), las
herramientas consideradas peligrosas (shell/exec/file_write/...) se enrutan
por él y el backend real utilizado queda registrado en
ToolResult.metadata["sandbox_backend"] + limits_applied (F-SB-11,
Hueco A Fase 20). Sin sandbox, el dispatch es idéntico al anterior.
Source code in src\ciel\runtime\__init__.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 | |
¶
InMemoryAuditSink
¶
KGEdge
dataclass
¶
KGNode
dataclass
Nodo del knowledge graph (aislado por tenant).
Source code in src\ciel\runtime\knowledge_graph.py
¶
KnowledgeGraph
Knowledge graph con persistencia SQLite + búsqueda semántica offline.
¶Parameters
backend:
StateBackend SQLite existente (se reusa su conn), una ruta a
fichero SQLite (str), o None para SQLite in-memory.
embedding_provider:
Provider de embeddings. Default: DeterministicEmbeddingProvider
(hash-based, offline, sin red).
Source code in src\ciel\runtime\knowledge_graph.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 | |
¶
neighbors(node_id: str, *, tenant_id: Optional[str] = None, direction: str = 'both') -> List[Tuple[KGNode, KGEdge]]
Vecinos por aristas explícitas. direction: out | in | both.
Source code in src\ciel\runtime\knowledge_graph.py
¶
search(query: str, *, tenant_id: Optional[str] = None, top_k: int = 5) -> List[KGNode]
Búsqueda semántica (coseno, offline) filtrada por tenant.
Source code in src\ciel\runtime\knowledge_graph.py
¶
to_networkx(*, tenant_id: Optional[str] = None)
Exporta a networkx.DiGraph si networkx está instalado (opcional).
Source code in src\ciel\runtime\knowledge_graph.py
¶
ModelProvider
Model/provider contract for completions (legacy alias).
Source code in src\ciel\runtime\__init__.py
¶
NullAuditSink
¶
ProviderRegistry
Source code in src\ciel\providers\__init__.py
¶
SkillError
¶
SkillLibrary
Writable, in-memory skill store that wraps a :class:SkillRegistry.
The registry remains the source of truth for disk-loaded skills; the
library layer adds creation, registration, update (with version bump) and
removal of skills that live only in memory. Tenant isolation is supported
via the optional tenant_id key on each stored :class:Skill.
Source code in src\ciel\runtime\skills_lib.py
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 | |
¶
create_from_code(*, name: str, description: str, code: str, category: Optional[str] = None, tenant_id: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, domain: Optional[str] = None) -> Skill
Compile code (syntax check) and store it as a new skill.
Raises :class:SkillError if the code does not compile. The skill is
NOT executed here — execution belongs to :class:SkillVerifier.
Source code in src\ciel\runtime\skills_lib.py
¶
history(name: str) -> List[Skill]
¶
load_from_disk() -> List[Skill]
Discover skills from the registry roots and index them in-memory.
¶
register(skill: Skill) -> Skill
Register an already-built :class:Skill (e.g. disk-loaded).
Source code in src\ciel\runtime\skills_lib.py
¶
update(*, name: str, description: Optional[str] = None, code: Optional[str] = None, category: Optional[str] = None, domain: Optional[str] = None, bump: str = 'patch') -> Skill
Create a new version of an existing skill, preserving history.
bump is one of major/minor/patch (semantic) and is
recorded in metadata.version. The previous version is preserved in
history(name).
Source code in src\ciel\runtime\skills_lib.py
¶
SkillRecommender
Recomendador cross-domain de skills basado en embeddings (offline).
index()vectorizaSkill.contentde la librería (por tenant).recommend()devuelve skills relevantes al contexto. Si se conoce el dominio del contexto (context_domain), solo devuelve skills cuyodomainsea distinto (transfer learning entre dominios). Si no hay dominio, devuelve el top-k por similitud.
Source code in src\ciel\runtime\skill_recommender.py
¶
index(*, tenant_id: Optional[str] = None) -> int
(Re)indexa las skills del tenant. Devuelve cuántas se indexaron.
Source code in src\ciel\runtime\skill_recommender.py
¶
recommend(context: str, *, tenant_id: Optional[str] = None, top_k: int = 3, context_domain: Optional[str] = None) -> List[Skill]
Sugiere hasta top_k skills relevantes a context.
Cross-domain: si context_domain está definido, excluye skills de
ese mismo dominio (solo transferencia desde OTROS dominios). Sin
dominio, devuelve el top-k global por similitud coseno.
Source code in src\ciel\runtime\skill_recommender.py
¶
SkillVerificationError
Bases: SkillError
Raised when a skill fails verification.
¶
SkillVerificationResult
dataclass
Outcome of :meth:SkillVerifier.verify.
Source code in src\ciel\runtime\skills_lib.py
¶
SkillVerifier
Offline verifier: syntax check + executable test cases.
A test case is a dict {"call": {...}, "expect": <value>}. The verifier
executes the skill code in an isolated namespace, looks up a callable named
after the skill (or the first callable defined), invokes it with call
arguments and compares the result to expect.
Source code in src\ciel\runtime\skills_lib.py
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 | |
¶
StaticToolProvider
Bases: ToolProvider
Source code in src\ciel\runtime\__init__.py
¶
TenantRequired
¶
Tool
dataclass
¶
ToolExecutionContext
Source code in src\ciel\runtime\tools.py
¶
ToolLoopResult
dataclass
Source code in src\ciel\runtime\tools.py
¶
ToolProvider
dataclass
Concrete tool provider used by the runtime's tool dispatcher.
Source code in src\ciel\runtime\__init__.py
¶
ToolRegistry
Source code in src\ciel\runtime\tools.py
¶
ToolResult
dataclass
¶
ToolSpec
dataclass
¶
ToolsetSchema
dataclass
Source code in src\ciel\runtime\tools.py
¶
_extract_tool_calls(response: ChatResponse) -> List[Dict[str, Any]]
Source code in src\ciel\runtime\__init__.py
¶
assert_tenant_event(event: AuditEvent) -> None
¶
decompose_goal(goal: str, *, provider: Any = None) -> List[str]
Descompone goal en sub-tareas ordenadas.
Sin provider: heurística determinista offline (split por cláusulas).
Con provider (ChatProvider, p. ej. MockProvider): se le pide el
plan y se parsea; si la respuesta es vacía/inutilizable, fallback a la
heurística offline.
Source code in src\ciel\runtime\curriculum.py
¶
install_curriculum_support(agent_cls: Any) -> Any
Engancha curriculum= / curriculum_config= sin reescribir api.py.
Idempotente (flag _curriculum_installed). Expone
Agent.run_curriculum(goal, *, handler=None, plan=None, tenant_id=None)
que descompone el goal (o usa plan), lo persiste vía
:class:CurriculumRegistry y ejecuta las sub-tareas con
AutonomousAgent.run_goal (EventLoop real de orquestación). Si no se
pasa handler, cada sub-tarea se resuelve con Agent.arun.
Source code in src\ciel\runtime\curriculum.py
¶
propagate(event: AuditEvent, *, tenant_id: Optional[str] = None) -> AuditEvent
Source code in src\ciel\observability\__init__.py
¶
ChatContent = 'str | list[ContentPart]'
module-attribute
¶
ContentPart = Dict[str, Any]
module-attribute
¶
_DANGEROUS_TOOL_NAMES = frozenset({'shell', 'terminal', 'exec', 'file_write', 'write_file', 'code_exec', 'eval'})
module-attribute
¶
__all__ = ['ToolSpec', 'Tool', 'ToolResult', 'ToolProvider', 'StaticToolProvider', 'DefaultToolDispatcher', 'ToolCallContext', 'ToolsetSchema', 'ToolExecutionContext', 'ToolRegistry', 'TenantAwareToolProvider', 'ChatMessage', 'ChatChoice', 'ChatRequest', 'ChatResponse', 'ModelProvider', 'ToolLoopResult', 'AgentRuntimeResult', 'AgentContext', 'AgentRuntime']
module-attribute
¶
AgentContext
dataclass
¶
AgentRuntime
Async runtime contract for tool-loop execution and streaming.
Source code in src\ciel\runtime\tools.py
¶
AgentRuntimeResult
dataclass
¶
ChatChoice
dataclass
¶
ChatMessage
dataclass
Source code in src\ciel\runtime\tools.py
¶
text() -> str
Extract plain text from content, tolerant to multimodal parts.
strcontent is returned verbatim.listcontent concatenates thetextof every part whose type is"text"but drops images/audio/video, so consumers (CLI, compression,AgentResponse.text) see only readable text.
Source code in src\ciel\runtime\tools.py
¶
ChatRequest
dataclass
Source code in src\ciel\runtime\tools.py
¶
ChatResponse
dataclass
¶
DefaultToolDispatcher
Dispatch tool requests to a configured ToolProvider.
Si se pasa sandbox (un :class:~ciel.sandbox.SandboxExecutor), las
herramientas consideradas peligrosas (shell/exec/file_write/...) se enrutan
por él y el backend real utilizado queda registrado en
ToolResult.metadata["sandbox_backend"] + limits_applied (F-SB-11).
Sin sandbox, el dispatch es idéntico al comportamiento anterior.
Source code in src\ciel\runtime\tools.py
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 | |
¶
ModelProvider
Model/provider contract for completions.
Source code in src\ciel\runtime\tools.py
¶
StaticToolProvider
Bases: ToolProvider
Source code in src\ciel\runtime\tools.py
¶
TenantAwareToolProvider
Tenant-aware provider contract.
Source code in src\ciel\runtime\tools.py
¶
Tool
dataclass
¶
ToolCallContext
dataclass
Source code in src\ciel\runtime\tools.py
¶
ToolExecutionContext
Source code in src\ciel\runtime\tools.py
¶
ToolLoopResult
dataclass
Source code in src\ciel\runtime\tools.py
¶
ToolProvider
Contract: discover tools and execute tool calls.
Source code in src\ciel\runtime\tools.py
¶
ToolRegistry
Source code in src\ciel\runtime\tools.py
¶
ToolResult
dataclass
¶
ToolSpec
dataclass
¶
ToolsetSchema
dataclass
Source code in src\ciel\runtime\tools.py
Built-in tools shipped with Ciel.
All tools are defined as ToolSpec + callable and registered into the
builtins toolset by register_builtin_tools. Network/sandbox tools are
safe to import offline; their side effects only happen at execution time and
can be sandboxed via ciel.sandbox.SandboxContext.
¶
BUILTIN_TOOLS: tuple[Tool, ...] = (ECHO_TOOL, DATETIME_TOOL, HTTP_GET_TOOL, FILE_READ_TOOL, SHELL_TOOL)
module-attribute
¶
BUILTIN_TOOLSET = ToolsetSchema(name='builtins', description='Ciel built-in tools (echo, datetime, http_get, file_read, shell).', tools=(tuple((t.spec) for t in BUILTIN_TOOLS)))
module-attribute
¶
DATETIME_TOOL = Tool(spec=(ToolSpec(name='datetime', description='Return current UTC time.', parameters={'format': {'type': 'string'}})), callable_=_datetime)
module-attribute
¶
ECHO_TOOL = Tool(spec=(ToolSpec(name='echo', description='Echo back the provided text.', parameters={'text': {'type': 'string'}})), callable_=_echo)
module-attribute
¶
FILE_READ_TOOL = Tool(spec=(ToolSpec(name='file_read', description='Read a local file (sandboxed).', parameters={'path': {'type': 'string'}})), callable_=_file_read)
module-attribute
¶
HTTP_GET_TOOL = Tool(spec=(ToolSpec(name='http_get', description='GET a URL (requires network).', parameters={'url': {'type': 'string'}, 'timeout': {'type': 'number'}})), callable_=_http_get)
module-attribute
¶
SHELL_TOOL = Tool(spec=(ToolSpec(name='shell', description='Run a shell command (disabled by default policy).', parameters={'command': {'type': 'string'}})), callable_=_shell)
module-attribute
¶
SandboxContext
dataclass
Source code in src\ciel\sandbox\__init__.py
¶
SandboxPolicy
dataclass
Source code in src\ciel\sandbox\__init__.py
¶
Tool
dataclass
¶
ToolResult
dataclass
¶
ToolSpec
dataclass
¶
ToolsetSchema
dataclass
Source code in src\ciel\runtime\tools.py
¶
_datetime(arguments: Dict[str, Any], *, tool_call_id: str = '', tenant_id: Optional[str] = None) -> ToolResult
Source code in src\ciel\runtime\tools_builtins.py
¶
_echo(arguments: Dict[str, Any], *, tool_call_id: str = '', tenant_id: Optional[str] = None) -> ToolResult
¶
_file_read(arguments: Dict[str, Any], *, tool_call_id: str = '', tenant_id: Optional[str] = None) -> ToolResult
Source code in src\ciel\runtime\tools_builtins.py
¶
_http_get(arguments: Dict[str, Any], *, tool_call_id: str = '', tenant_id: Optional[str] = None, client: Optional[httpx.AsyncClient] = None) -> ToolResult
async
Source code in src\ciel\runtime\tools_builtins.py
¶
_shell(arguments: Dict[str, Any], *, tool_call_id: str = '', tenant_id: Optional[str] = None) -> ToolResult
Source code in src\ciel\runtime\tools_builtins.py
¶
register_builtin_tools(registry) -> None
Register all built-in tools into a ToolRegistry instance.
¶
__all__ = ['MemoryStore', 'MemoryEntry', 'init_schema', '_fts5_available']
module-attribute
¶
MemoryEntry
dataclass
¶
MemoryStore
Bases: SqliteStateBackend
Alias retrocompatible a :class:SqliteStateBackend (SQLite en disco).
MemoryStore es SQLite en disco desde F5 — el nombre engaña. Para
F15 se refactorizó para heredar de StateBackend de modo que cualquier
store que hoy recibe un MemoryStore puede recibir también un
PostgresStateBackend compartido sin cambios de API.
Se sigue construyendo con la misma firma: MemoryStore(db_path).
Source code in src\ciel\runtime\memory.py
¶
SqliteStateBackend
Bases: StateBackend
Backend SQLite en disco (default offline). Hereda el esquema de F15-.
Mantiene FTS5 cuando está disponible; si no, search degrada a lista
vacía (comportamiento idéntico al MemoryStore original).
Source code in src\ciel\runtime\state_backend.py
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 | |
¶
_fts5_available(conn) -> bool
¶
init_schema(conn) -> None
Source code in src\ciel\runtime\state_backend.py
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 | |
Fase 19 — Prompt evolution versionado (Autonomía II, v0.13.0).
Este módulo aporta versionado semántico de prompts del agente (instructions
sistemáticas) con persistencia offline en el StateBackend (SQLite en dev /
Postgres en prod) y aislamiento estricto por tenant_id.
Molde: skill_versioning.py (Fase 12). A diferencia de los skills (que viven
en memoria dentro de SkillLibrary), los prompts SÍ se persisten en SQLite a
través del StateBackend para que sobrevivan reinicios y sean auditables.
Todo es network-free y API-key-free (offline-safe).
¶
INITIAL_VERSION = '0.0.0'
module-attribute
¶
__all__ = ['PromptVersioningError', 'PromptVersion', 'PromptRegistry', 'sha256_text', 'INITIAL_VERSION']
module-attribute
¶
PromptRegistry
Registro multitenant de prompts versionados sobre un StateBackend.
El backend es cualquier instancia de ciel.runtime.state_backend.StateBackend
(SqliteStateBackend por defecto, PostgresStateBackend en prod). Todas
las lecturas/escrituras filtran estrictamente por tenant_id.
Source code in src\ciel\runtime\prompt_versioning.py
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 | |
¶
create(name: str, prompt_text: str, *, tenant_id: Optional[str] = None, changelog: str = '', metadata: Optional[Dict[str, Any]] = None) -> PromptVersion
Crea la versión inicial 0.0.0 de un prompt.
Lanza :class:PromptVersioningError si el nombre ya existe para el tenant.
Source code in src\ciel\runtime\prompt_versioning.py
¶
evolution_tree(name: str, *, tenant_id: Optional[str] = None) -> Dict[str, Any]
Devuelve el árbol de linaje de un prompt versionado.
Misma forma que skill_versioning.evolution_tree:
{"name", "root", "lineage": [...], "nodes": {version: {...}}}
con parent / children / sha256 / changelog / released_at.
Source code in src\ciel\runtime\prompt_versioning.py
¶
update(name: str, prompt_text: str, *, tenant_id: Optional[str] = None, bump: str = 'patch', changelog: str = '', metadata: Optional[Dict[str, Any]] = None) -> PromptVersion
Bumpea un prompt existente y guarda la nueva versión.
Source code in src\ciel\runtime\prompt_versioning.py
¶
PromptVersion
dataclass
Versión semántica enriquecida de un prompt del agente.
Lleva major.minor.patch + changelog + released_at (timestamp) +
el hash sha256 del texto, y la trazabilidad de linaje
(previous_version / parent).
Source code in src\ciel\runtime\prompt_versioning.py
¶
PromptVersioningError
¶
_dump(value: Any) -> str
¶
_now_iso() -> str
Integración aditiva de self-reflection + learning-from-failure (Fase 19).
IGUAL que memory_agent_integration: NO reescribe api.py. Se invoca
install_agent_reflection_support(Agent) al final de ciel/api.py y
engancha:
Agent(reflection=...)/Agent(reflection_config=...)— habilita la reflexión post-run (opcional, offline-safe).- Tras cada
arun/run, si el run tuvo fallos de tool, genera una lección determinista (sin red) y la persiste como memoria episódicarole="lesson"(reutiliza elEpisodicStorede F17 → multitenant). - Exponer
AgentResponse.reflection(property aditiva) con el resumen.
Degrada graceful: si no se instala, getattr(self, "_reflection", None) es
None y el run no cambia.
¶
__all__ = ['AgentReflection', 'ReflectionConfig', 'install_agent_reflection_support']
module-attribute
¶
AgentReflection
State holder de reflexión para un Agent (aditivo, no invasivo).
Genera lecciones deterministas a partir de fallos de tool (sin red) y las
persiste vía el EpisodicStore (memoria episódica F17, aislada por
tenant). Si no hay store, opera en modo no-persistente (solo resumen).
Source code in src\ciel\runtime\reflection_agent_integration.py
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | |
¶
lessons(*, tenant_id: Optional[str], session_id: str, limit: int = 5) -> List[dict]
Recupera las lecciones persistidas (memoria episódica role='lesson').
Source code in src\ciel\runtime\reflection_agent_integration.py
¶
reflect(response: Any, *, tenant_id: Optional[str], session_id: str) -> Optional[dict]
Reflexiona sobre un AgentResponse y (opcionalmente) persiste lección.
Devuelve un dict resumen:
{"had_failure", "failed_tools", "lessons_count", "lesson"}
o None si la reflexión está deshabilitada.
Source code in src\ciel\runtime\reflection_agent_integration.py
¶
EpisodicStore
Store de memoria episódica sobre un StateBackend (aislado por tenant).
Operaciones:
* append — persiste un turno.
* get_recent — últimos N episodios de una sesión (orden cronológico).
* get_by_id — recupera un episodio por su ID.
* search — búsqueda por keywords filtrada POR TENANT (no cross-tenant).
* clear_session — borra la memoria de una sesión.
* as_context — serializa episodios recientes como texto para el system.
Source code in src\ciel\runtime\memory_episodic.py
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 | |
¶
as_context(*, tenant_id: Optional[str], session_id: str, recent: int = 8, query: Optional[str] = None, search_limit: int = 5) -> str
Devuelve el texto de memoria para inyectar en el system prompt.
Source code in src\ciel\runtime\memory_episodic.py
¶
ReflectionConfig
dataclass
Configuración de reflexión del agente (degrada a 'sin reflexión').
Source code in src\ciel\runtime\reflection_agent_integration.py
¶
_session_id_of(resp: AgentResponse) -> str
¶
install_agent_reflection_support(agent_cls: Any) -> Any
Engancha reflection= / reflection_config= en Agent sin reescribir api.py.
Idempotente: si ya se instaló, no re-envuelve (evita doble wrapper en tests).
Source code in src\ciel\runtime\reflection_agent_integration.py
Introspección / estado cognitivo explicable (Fase 19, v0.13.0).
Aditivo y offline-safe. Engancha Agent(introspection=...) sin reescribir
api.py y:
- Inyecta un bloque
[Estado cognitivo]en el system prompt (en_build_request) con el último snapshot conocido del agente, para que el modelo sea consciente de su propio estado (vuelve a inyectar el contexto de la introspección). - Registra un
CognitiveSnapshotpost-run encognitive_state_logdelStateBackend(aislado por tenant/session). - Expone
Agent.introspect()para volcar los últimos snapshots.
Reusa EpisodicStore (conteo de turnos) y DeterministicEmbeddingProvider
(embedding del estado, offline). El RAG (retrieved_context_ids) queda como
None cuando el agente no usa RAG; el campo es opcional.
Degrada graceful: si no se instala, _cognitive no existe y el run no cambia.
¶
_DEFAULT_COGNITIVE_BACKEND: Optional[StateBackend] = None
module-attribute
¶
__all__ = ['CognitiveSnapshot', 'IntrospectionReport', 'IntrospectionConfig', 'CognitiveState', 'install_cognitive_state_support']
module-attribute
¶
ChatMessage
dataclass
Source code in src\ciel\runtime\tools.py
¶
text() -> str
Extract plain text from content, tolerant to multimodal parts.
strcontent is returned verbatim.listcontent concatenates thetextof every part whose type is"text"but drops images/audio/video, so consumers (CLI, compression,AgentResponse.text) see only readable text.
Source code in src\ciel\runtime\tools.py
¶
ChatRequest
dataclass
Source code in src\ciel\runtime\tools.py
¶
CognitiveSnapshot
dataclass
Instantánea del estado cognitivo del agente en un run.
Source code in src\ciel\runtime\cognitive_state.py
¶
CognitiveState
State holder de introspección para un Agent (aditivo, offline).
Source code in src\ciel\runtime\cognitive_state.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | |
¶
embed_state(snapshot: CognitiveSnapshot) -> List[float]
Embedding determinista del estado (offline).
Source code in src\ciel\runtime\cognitive_state.py
¶
latest_block(*, tenant_id: Optional[str], session_id: str) -> Optional[str]
Devuelve el bloque [Estado cognitivo] a inyectar, o None.
Source code in src\ciel\runtime\cognitive_state.py
¶
record(snapshot: CognitiveSnapshot) -> None
Persiste el snapshot en cognitive_state_log (tenant-filtered).
Source code in src\ciel\runtime\cognitive_state.py
¶
DeterministicEmbeddingProvider
Bases: EmbeddingProvider
Embedding determinista offline (hash → vector). NO semántico real.
Útil para dev, tests y como fallback cuando no hay API key. Produce el mismo vector para el mismo texto (determinista), permitiendo búsqueda por similitud coseno coherente dentro de una corrida. NO usar en prod como única fuente de verdad semántica; combinar con BM25 (hybrid).
Source code in src\ciel\rag\embeddings.py
¶
EpisodicStore
Store de memoria episódica sobre un StateBackend (aislado por tenant).
Operaciones:
* append — persiste un turno.
* get_recent — últimos N episodios de una sesión (orden cronológico).
* get_by_id — recupera un episodio por su ID.
* search — búsqueda por keywords filtrada POR TENANT (no cross-tenant).
* clear_session — borra la memoria de una sesión.
* as_context — serializa episodios recientes como texto para el system.
Source code in src\ciel\runtime\memory_episodic.py
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 | |
¶
as_context(*, tenant_id: Optional[str], session_id: str, recent: int = 8, query: Optional[str] = None, search_limit: int = 5) -> str
Devuelve el texto de memoria para inyectar en el system prompt.
Source code in src\ciel\runtime\memory_episodic.py
¶
IntrospectionConfig
dataclass
¶
IntrospectionReport
dataclass
Agrega snapshots de una sesión en un reporte introspectivo.
Source code in src\ciel\runtime\cognitive_state.py
¶
StateBackend
Bases: ABC
Interfaz mínima de persistencia compartida (multi-réplica).
Source code in src\ciel\runtime\state_backend.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | |
¶
is_ready() -> bool
Devuelve True si el backend está conectado y migrado.
El default asume listo; los backends remotos sobrescriben esto con una comprobación real de conectividad.
¶
SqliteStateBackend_memory() -> StateBackend
¶
_default_backend() -> StateBackend
¶
_dump(value: Any) -> str
¶
_effective_tenant(agent: Any, tenant_id: Optional[str] = None) -> Optional[str]
Source code in src\ciel\runtime\cognitive_state.py
¶
install_cognitive_state_support(agent_cls: Any) -> Any
Engancha introspection= / introspection_config= sin reescribir api.py.
Idempotente.
Source code in src\ciel\runtime\cognitive_state.py
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 | |
Fase 20 BLOQUE A — Curriculum / autonomous goal setting (v0.13.x).
Un curriculum es la descomposición versionada de un goal en un plan de
sub-tareas ordenadas, persistida en el StateBackend (tabla curricula)
con aislamiento estricto por tenant_id y linaje (previous_version /
parent), calcado del molde de prompt_versioning.py (Fase 19).
Piezas:
- :class:
Curriculum— dataclass con goal + plan + linaje + sha256. - :class:
CurriculumRegistry— CRUD versionado sobre unStateBackend(curriculum_save/curriculum_get/curriculum_get_history). - :func:
decompose_goal— descomposición determinista/offline por defecto (heurística de cláusulas); si se pasa unproviderreal (p. ej.MockProvidero un LLM), se le pide el plan y se parsea su respuesta. - :func:
install_curriculum_support— integración ADITIVA conciel.Agent(kwargscurriculum=/curriculum_config=+Agent.run_curriculum), idempotente, mismo patrón queinstall_cognitive_state_support.
Todo es network-free y API-key-free por defecto (offline-safe).
¶
INITIAL_VERSION = '0.0.0'
module-attribute
¶
_SPLIT_PATTERN = re.compile('(?:;|\\.\\s+|\\.$|,\\s*luego\\s+|\\s+y\\s+luego\\s+|\\s+luego\\s+|\\s+y\\s+después\\s+|\\s+después\\s+|\\s+y\\s+|\\s+then\\s+|\\s+and\\s+then\\s+)', re.IGNORECASE)
module-attribute
¶
__all__ = ['CurriculumError', 'Curriculum', 'CurriculumConfig', 'CurriculumRegistry', 'AgentCurriculum', 'decompose_goal', 'install_curriculum_support', 'sha256_plan', 'INITIAL_VERSION']
module-attribute
¶
AgentCurriculum
Estado de curriculum enganchado a una instancia de Agent.
Source code in src\ciel\runtime\curriculum.py
¶
Curriculum
dataclass
Plan versionado (curriculum) para un objetivo del agente.
Source code in src\ciel\runtime\curriculum.py
¶
CurriculumConfig
dataclass
Configuración del soporte de curriculum en el Agent.
Source code in src\ciel\runtime\curriculum.py
¶
CurriculumError
¶
CurriculumRegistry
Registro multitenant de curricula versionados sobre un StateBackend.
Source code in src\ciel\runtime\curriculum.py
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 | |
¶
create(goal: str, plan: Sequence[str], *, tenant_id: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None) -> Curriculum
Crea la versión inicial 0.0.0 de un curriculum (o bumpea si existe).
Source code in src\ciel\runtime\curriculum.py
¶
evolution_tree(goal: str, *, tenant_id: Optional[str] = None) -> Dict[str, Any]
Árbol de linaje, misma forma que prompt_versioning.evolution_tree.
Source code in src\ciel\runtime\curriculum.py
¶
_default_backend() -> Any
¶
_heuristic_plan(goal: str) -> List[str]
Split determinista por frases/cláusulas ('; ', '.', ' y ', ' luego ', ...).
Source code in src\ciel\runtime\curriculum.py
¶
_now_iso() -> str
¶
_parse_provider_plan(text: str) -> List[str]
Parsea la respuesta de un provider a lista de pasos.
Acepta JSON (lista de strings) o texto con líneas/numeración/viñetas.
Source code in src\ciel\runtime\curriculum.py
¶
decompose_goal(goal: str, *, provider: Any = None) -> List[str]
Descompone goal en sub-tareas ordenadas.
Sin provider: heurística determinista offline (split por cláusulas).
Con provider (ChatProvider, p. ej. MockProvider): se le pide el
plan y se parsea; si la respuesta es vacía/inutilizable, fallback a la
heurística offline.
Source code in src\ciel\runtime\curriculum.py
¶
install_curriculum_support(agent_cls: Any) -> Any
Engancha curriculum= / curriculum_config= sin reescribir api.py.
Idempotente (flag _curriculum_installed). Expone
Agent.run_curriculum(goal, *, handler=None, plan=None, tenant_id=None)
que descompone el goal (o usa plan), lo persiste vía
:class:CurriculumRegistry y ejecuta las sub-tareas con
AutonomousAgent.run_goal (EventLoop real de orquestación). Si no se
pasa handler, cada sub-tarea se resuelve con Agent.arun.
Source code in src\ciel\runtime\curriculum.py
¶
sha256_plan(goal: str, plan: Sequence[str]) -> str
Hash determinista de (goal, plan) — offline.
Source code in src\ciel\runtime\curriculum.py
Knowledge graph persistente y offline-safe (Fase 20 — Bloque B).
Grafo de conocimiento mínimo, ADITIVO (no toca la API existente):
- :class:
KGNode/ :class:KGEdge— dataclasses propias (misma FORMA queGraphNode/GraphEdgedeciel.orchestration.graphpero sin importar de ahí para no colisionar con el grafo de orquestación). - :class:
KnowledgeGraph— nodos + aristas con persistencia SQLite (tablaskg_nodes/kg_edgescon índices, patrón F19 destate_backend) y búsqueda semántica offline víaDeterministicEmbeddingProvider+InMemoryVectorStore(Fase 17).
Decisiones de diseño:
* Offline-safe primero: sin red, sin networkx obligatorio (import
opcional en :meth:KnowledgeGraph.to_networkx).
* Aislamiento estricto por tenant_id en TODAS las lecturas, reutilizando
el sentinel de StateBackend._sentinel (SQLite no trata dos NULL como
iguales en UNIQUE).
* La persistencia acepta un StateBackend SQLite existente (reusa su
conn), una ruta de fichero, o None (SQLite in-memory).
¶
__all__ = ['KGNode', 'KGEdge', 'KnowledgeGraph', 'init_kg_schema']
module-attribute
¶
DeterministicEmbeddingProvider
Bases: EmbeddingProvider
Embedding determinista offline (hash → vector). NO semántico real.
Útil para dev, tests y como fallback cuando no hay API key. Produce el mismo vector para el mismo texto (determinista), permitiendo búsqueda por similitud coseno coherente dentro de una corrida. NO usar en prod como única fuente de verdad semántica; combinar con BM25 (hybrid).
Source code in src\ciel\rag\embeddings.py
¶
EmbeddingProvider
Bases: ABC
Contrato mínimo de embeddings.
Source code in src\ciel\rag\embeddings.py
¶
InMemoryVectorStore
Bases: VectorStore
Índice vectorial en memoria (offline, sin dependencias).
Aísla por tenant_id: query solo devuelve records del tenant pedido.
Source code in src\ciel\rag\vector_store.py
¶
KGEdge
dataclass
¶
KGNode
dataclass
Nodo del knowledge graph (aislado por tenant).
Source code in src\ciel\runtime\knowledge_graph.py
¶
KnowledgeGraph
Knowledge graph con persistencia SQLite + búsqueda semántica offline.
¶Parameters
backend:
StateBackend SQLite existente (se reusa su conn), una ruta a
fichero SQLite (str), o None para SQLite in-memory.
embedding_provider:
Provider de embeddings. Default: DeterministicEmbeddingProvider
(hash-based, offline, sin red).
Source code in src\ciel\runtime\knowledge_graph.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 | |
¶
neighbors(node_id: str, *, tenant_id: Optional[str] = None, direction: str = 'both') -> List[Tuple[KGNode, KGEdge]]
Vecinos por aristas explícitas. direction: out | in | both.
Source code in src\ciel\runtime\knowledge_graph.py
¶
search(query: str, *, tenant_id: Optional[str] = None, top_k: int = 5) -> List[KGNode]
Búsqueda semántica (coseno, offline) filtrada por tenant.
Source code in src\ciel\runtime\knowledge_graph.py
¶
to_networkx(*, tenant_id: Optional[str] = None)
Exporta a networkx.DiGraph si networkx está instalado (opcional).
Source code in src\ciel\runtime\knowledge_graph.py
¶
StateBackend
Bases: ABC
Interfaz mínima de persistencia compartida (multi-réplica).
Source code in src\ciel\runtime\state_backend.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | |
¶
is_ready() -> bool
Devuelve True si el backend está conectado y migrado.
El default asume listo; los backends remotos sobrescriben esto con una comprobación real de conectividad.
¶
init_kg_schema(conn: sqlite3.Connection) -> None
Crea las tablas kg_nodes/kg_edges si no existen (idempotente).
Source code in src\ciel\runtime\knowledge_graph.py
¶
__all__ = ['SkillRecommender']
module-attribute
¶
DeterministicEmbeddingProvider
Bases: EmbeddingProvider
Embedding determinista offline (hash → vector). NO semántico real.
Útil para dev, tests y como fallback cuando no hay API key. Produce el mismo vector para el mismo texto (determinista), permitiendo búsqueda por similitud coseno coherente dentro de una corrida. NO usar en prod como única fuente de verdad semántica; combinar con BM25 (hybrid).
Source code in src\ciel\rag\embeddings.py
¶
EmbeddingProvider
Bases: ABC
Contrato mínimo de embeddings.
Source code in src\ciel\rag\embeddings.py
¶
InMemoryVectorStore
Bases: VectorStore
Índice vectorial en memoria (offline, sin dependencias).
Aísla por tenant_id: query solo devuelve records del tenant pedido.
Source code in src\ciel\rag\vector_store.py
¶
Skill
dataclass
¶
SkillLibrary
Writable, in-memory skill store that wraps a :class:SkillRegistry.
The registry remains the source of truth for disk-loaded skills; the
library layer adds creation, registration, update (with version bump) and
removal of skills that live only in memory. Tenant isolation is supported
via the optional tenant_id key on each stored :class:Skill.
Source code in src\ciel\runtime\skills_lib.py
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 | |
¶
create_from_code(*, name: str, description: str, code: str, category: Optional[str] = None, tenant_id: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, domain: Optional[str] = None) -> Skill
Compile code (syntax check) and store it as a new skill.
Raises :class:SkillError if the code does not compile. The skill is
NOT executed here — execution belongs to :class:SkillVerifier.
Source code in src\ciel\runtime\skills_lib.py
¶
history(name: str) -> List[Skill]
¶
load_from_disk() -> List[Skill]
Discover skills from the registry roots and index them in-memory.
¶
register(skill: Skill) -> Skill
Register an already-built :class:Skill (e.g. disk-loaded).
Source code in src\ciel\runtime\skills_lib.py
¶
update(*, name: str, description: Optional[str] = None, code: Optional[str] = None, category: Optional[str] = None, domain: Optional[str] = None, bump: str = 'patch') -> Skill
Create a new version of an existing skill, preserving history.
bump is one of major/minor/patch (semantic) and is
recorded in metadata.version. The previous version is preserved in
history(name).
Source code in src\ciel\runtime\skills_lib.py
¶
SkillRecommender
Recomendador cross-domain de skills basado en embeddings (offline).
index()vectorizaSkill.contentde la librería (por tenant).recommend()devuelve skills relevantes al contexto. Si se conoce el dominio del contexto (context_domain), solo devuelve skills cuyodomainsea distinto (transfer learning entre dominios). Si no hay dominio, devuelve el top-k por similitud.
Source code in src\ciel\runtime\skill_recommender.py
¶
index(*, tenant_id: Optional[str] = None) -> int
(Re)indexa las skills del tenant. Devuelve cuántas se indexaron.
Source code in src\ciel\runtime\skill_recommender.py
¶
recommend(context: str, *, tenant_id: Optional[str] = None, top_k: int = 3, context_domain: Optional[str] = None) -> List[Skill]
Sugiere hasta top_k skills relevantes a context.
Cross-domain: si context_domain está definido, excluye skills de
ese mismo dominio (solo transferencia desde OTROS dominios). Sin
dominio, devuelve el top-k global por similitud coseno.
Source code in src\ciel\runtime\skill_recommender.py
¶
VectorStore
Bases: ABC
Contrato de índice vectorial (aislado por tenant_id).