Repository navigation
es API CHEATSHEET
Esta hoja de referencia rápida recopila las clases, métodos, parámetros y firmas más utilizadas de AI RAG Common Framework para desarrollo a máxima velocidad.
from common_framework import (
LLMFactory,
FallbackLLMClient,
FallbackCandidate,
ChatMessage,
Role,
SemanticCache,
CachedLLMClient,
)| Clase / Función | Métodos / Parámetros Clave | Ejemplo de Uso |
| : | : | : |
| LLMFactory.create() | provider: str, model: str, api_key: Optional[str], temperature: float = 0.7 | llm = LLMFactory.create("gemini", model="gemini-2.5-flash") |
| FallbackLLMClient | candidates: list[BaseLLMClient], max_retries: int = 2 | client = FallbackLLMClient([c1, c2, c3]) |
| ChatMessage | role: Role (USER, ASSISTANT, SYSTEM), content: str | msg = ChatMessage(role=Role.USER, content="Hola") |
| client.complete() | messages: list[ChatMessage], temperature: float, stream: bool = False ChatResponse | res = await client.complete(messages) |
| client.complete_stream() | messages: list[ChatMessage] AsyncIterator[ChatStreamChunk] | async for chunk in client.complete_stream(msg): ... |
| client.structured_complete() | messages: list[ChatMessage], response_model: Type[BaseModel] T (alias: complete_structured) | data = await client.structured_complete(msg, response_model=User) |
| SemanticCache | embedding_provider, similarity_threshold: float = 0.92, ttl_seconds: int = 3600 | cache = SemanticCache(embedder, similarity_threshold=0.92) |
| CachedLLMClient | client: BaseLLMClient, cache: SemanticCache | cached_client = CachedLLMClient(client=llm, cache=cache) |
from common_framework import (
RAGEngine,
Document,
SQLiteVectorStore,
InMemoryVectorStore,
RecursiveTextSplitter,
EmbeddingFactory,
MultiQueryStrategy,
HyDEStrategy,
LocalCrossEncoderReranker,
)| Clase / Función | Métodos / Parámetros Clave | Ejemplo de Uso |
| : | : | : |
| Document | id: Optional[str], content: str, metadata: dict = {}, embedding: list[float] = None | doc = Document(content="Texto", metadata={"tag": "v1"}) |
| EmbeddingFactory.create()| provider: str ("gemini", "openai", "mock") | embedder = EmbeddingFactory.create("gemini") |
| SQLiteVectorStore | db_path: str, embedding_provider: BaseEmbeddingProvider | store = SQLiteVectorStore("data.db", embedding_provider=emb) |
| store.add_documents() | documents: list[Document], collection: str = "default" | await store.add_documents(docs, collection="legal") |
| store.similarity_search()| query_embedding: list[float], top_k: int = 4, collection: str | results = await store.similarity_search(vec, top_k=5) |
| store.hybrid_search() | query_text: str, query_embedding: list[float], top_k: int = 4 | results = await store.hybrid_search("texto", vec, top_k=4) |
| RecursiveTextSplitter | chunk_size: int = 500, chunk_overlap: int = 80, separators: list[str] | chunks = splitter.split_text(texto_largo) |
| RAGEngine | vector_store, llm_client, retrieval_strategy, reranker, hybrid_search=True | rag = RAGEngine(vector_store=store, llm_client=llm) |
| rag.query() | query: str, top_k: int = 4, collection: str = "default" RAGResponse | res = await rag.query("¿Cómo configuro SSL?") |
| rag.as_tool() | name: str, description: str Tool (Listo para MCP o ReAct) | tool_rag = rag.as_tool("buscar_docs", "Busca manuales") |
from common_framework import (
ReActAgent,
AgentSupervisor,
AgentBus,
StateGraph,
START,
END,
ConversationBufferMemory,
VectorMemory,
CallableApprovalHook,
ApprovalDecision,
)| Clase / Función | Métodos / Parámetros Clave | Ejemplo de Uso |
| : | : | : |
| @tool | @tool(name="...", description="...") (decorador de funciones) | @tool def sumar(a: int, b: int) -> int: return a + b |
| ReActAgent | llm_client, tools: list[Tool], max_iterations: int = 5, memory: BaseMemory | agent = ReActAgent(llm_client=llm, tools=[sumar]) |
| AgentSupervisor | llm_client, workers: list[ReActAgent], bus: AgentBus | sup = AgentSupervisor(llm, workers=[w1, w2], bus=bus) |
| StateGraph | state_schema: Type[TypedDict / BaseModel] | g = StateGraph(state_schema=MiEstado) |
| g.add_node() | node_name: str, action: Callable[[State], Awaitable[delta]] | g.add_node("redactor", funcion_asincrona) |
| g.add_edge() | source: str, target: str | g.add_edge(START, "redactor") |
| g.add_conditional_edges()| source: str, path: Callable[[State], str], path_map: dict[str, str] | g.add_conditional_edges("evaluar", decidir, {"ok": END}) |
| ConversationBufferMemory | max_messages: Optional[int] = 10 | mem = ConversationBufferMemory(max_messages=10) |
| VectorMemory | vector_store, embedding_provider, collection: str = "agent_memory" | mem = VectorMemory(store, embedder, max_messages=10) |
from common_framework import (
create_mcp_server,
create_mcp_client,
FrameworkMCPServer,
FrameworkMCPClient,
)| Clase / Función | Métodos / Parámetros Clave | Ejemplo de Uso |
| : | : | : |
| create_mcp_server() | name: str, transport: Literal["stdio", "sse"] = "stdio", port: int = 8080 | srv = create_mcp_server("MiServer", transport="stdio") |
| srv.register_tool() | tool: Tool (o función decorada con @tool) | srv.register_tool(mi_herramienta) |
| create_mcp_client() | endpoint_url: str (vía SSE) FrameworkMCPClient | client = await create_mcp_client("http://localhost:8080/sse") |
| client.discover_tools() | Descubre herramientas remotas list[MCPRemoteTool] | tools = await client.discover_tools() |
from common_framework import (
PromptGuardrail,
PIISanitizer,
RedactionStrategy,
CodeInterpreter,
)| Clase / Función | Métodos / Parámetros Clave | Ejemplo de Uso |
| : | : | : |
| PromptGuardrail | .check_prompt(text: str) GuardrailResult(is_safe, threat_level) | res = guardrail.check_prompt(prompt_usuario) |
| PIISanitizer | default_strategy: RedactionStrategy (REPLACE, MASK) | san = PIISanitizer(default_strategy=RedactionStrategy.REPLACE) |
| san.sanitize() | text: str SanitizationResult(sanitized_text, entities) | clean_text = san.sanitize(texto_sensible).sanitized_text |
| CodeInterpreter | timeout_seconds: float = 5.0, scrub_environment: bool = True | sandbox = CodeInterpreter(timeout_seconds=5.0) |
| sandbox.run() | code: str ExecutionResult(success, stdout, stderr) | res = await sandbox.run("print(1 + 1)") |
from common_framework import (
get_global_cost_tracker,
global_prometheus_registry,
trace_span,
)| Clase / Función | Métodos / Parámetros Clave | Ejemplo de Uso |
| : | : | : |
| get_global_cost_tracker()| .get_summary() total_cost_usd, total_prompt_tokens | resumen = get_global_cost_tracker().get_summary() |
| trace_span() | name: str, traceparent: Optional[str] = None (Context Manager W3C) | async with trace_span("rag.retrieval") as span: ... |
| create_metrics_router() | Genera un APIRouter FastAPI para /metrics en formato Prometheus | app.include_router(create_metrics_router()) |
from common_framework import create_app, create_rag_router, mount_mcp_to_fastapi| Clase / Función | Métodos / Parámetros Clave | Ejemplo de Uso |
| : | : | : |
| create_app() | title: str, rag_engine: Optional[RAGEngine], enable_rag_routes: bool = True | app = create_app(title="AI API", enable_rag_routes=True) |
| create_rag_router() | engine: Optional[RAGEngine], prefix: str = "/rag" | app.include_router(create_rag_router(rag)) |
| mount_mcp_to_fastapi() | app: FastAPI, mcp_server: FrameworkMCPServer, api_key: Optional[str] | mount_mcp_to_fastapi(app, srv, api_key="secret") |
| CLI: ai-rag doctor | Diagnóstico del entorno, dependencias y credenciales de red | ai-rag doctor |
| CLI: ai-rag repl | Consola interactiva para probar prompts, RAG y tokens en tiempo real | ai-rag repl |
| CLI: ai-rag init | Generador de microservicios con estructura estandarizada para producción | ai-rag init mi-microservicio |
English Documentation | Documentación en Español
- Overview
- 01. Architecture & Concepts
- 02. Getting Started
- 03. Implementation & Components
- 04. Patterns & Recipes
- 05. Staff Guide & Production
- General
- 01. Arquitectura y Conceptos
- 02. Primeros Pasos
- 03. Implementación y Componentes
- 04. Patrones y Recetas
- 05. Guía Staff y Producción