Skip to content
Edit this page

AI

Titancore composes OpenAI and Anthropic model adapters, LangGraph agents and workflows, and application-owned framework services. Provider SDKs own HTTP protocols, tools use native schema validation, and LangGraph owns scheduling and checkpoint serialization.

Application composition

Register CacheServiceProvider, ConcurrencyServiceProvider, ParallelServiceProvider, and AIServiceProvider explicitly. Bootstrap the application before resolving services. The application lifecycle closes AI adapters before their borrowed framework resources.

Configure config/ai.yaml with the provider models your application uses:

default: openai
concurrency: 16
providers:
  openai:
    model: your-openai-model
  anthropic:
    model: your-anthropic-model

Provider keys come from the loaded OPENAI_API_KEY and ANTHROPIC_API_KEY environment values unless explicitly configured. Keep credentials out of source files. Model calls use your provider account.

Embeddings

await AI.embed(texts) returns vectors aligned with the input texts using LangChain's OpenAI embedding adapter. Configure embeddings.model and, when supported by that model, embeddings.dimensions in config/ai.yaml. Embedding calls use the OpenAI credential even when chat uses Anthropic. Anthropic embeddings are not supported.

embeddings:
  model: your-openai-embedding-model
  dimensions: 1536

The adapter borrows the same bounded HTTP pool as chat models. The provider SDK owns tokenization and batching; Titancore returns vectors without storing them. Applications own vector dimensions, indexing, and source authorization. Empty input returns an empty list. Provider failures become AIError without logging source text or provider response details.

Agents and conversation history

Inside an application lifecycle, the facade returns independent fluent builders:

from titancore.facades import AI

agent = (await AI.agent("support")).instructions("Answer clearly.")
agent = agent.for_thread("conversation-id")
response = await agent.prompt("Hello")

history = await AI.conversation("support", "conversation-id")
messages = await history.messages()
await history.forget()

using(provider, model), tools(callbacks), and schema(PydanticModel) return new configurations. stream(text) yields assistant text. map(prompts) accepts sync or async iterables and processes bounded batches. batch(prompts) collects ordered results. Turns in a single threaded map run sequentially. Applications must serialize other concurrent turns that target the same conversation.

Tools can be annotated functions, callable objects, or classes with handle. Names must be unique within one agent. Class constructors use the application container. Pass request-scoped tool instances from their request context. Blocking tools use the existing thread driver. Application authorization and validation errors retain their framework handling.

Conversation readers expose user and assistant text through contracts. They omit tool internals and provider metadata. Session ownership, listings, citations, and retained business records belong to application models.

Workflows

await AI.workflow(name, StateSchema) builds a typed workflow. Use step for a linear sequence, or node, start_at, connect, branch, and finish_at for an explicit graph. These modes cannot be mixed. run starts an execution; state reads its checkpoint, and resume continues pending work. pause_before selects interruption points. stream yields node updates; events yields explicit application events emitted by workflow steps.

map accepts lazy sync or async inputs paired with thread identifiers. batch retains named results. parallel_step delegates blocking or CPU work to the framework thread or process driver. Process callbacks and their data must be picklable; live containers, sessions, and clients stay in their owner.

Persistence and capacity

Durable workflows and persistent conversations require RedisJSON and RediSearch on Redis database zero. The existing Redis cache repository owns the connection. Checkpoint keys survive ordinary cache flushes. Configure Redis persistence and eviction policy for the deployment's durability needs. Tests verify checkpoint recovery across application restarts, not host loss.

The AI concurrency setting bounds each batch and its shared HTTP pool. It does not establish a deployment traffic guarantee or a distributed worker queue. Measure application throughput and set ingress limits for the actual workload. RAG and MCP tool integrations are not implemented.

Typed embeddings and retrieval composition

AIServiceProvider also supplies titancore.contracts.ai.Embeddings. Its profile identifies the OpenAI model and configured dimensions; embed(texts) validates count, finite values and dimensions over the same AI manager. Applications choose how to persist profiles and can supply an explicit demo adapter through their existing service provider. Product demo data is not a built-in model provider.

titancore.ai.tools.rag.reciprocal_rank_fusion combines independently ranked sequences using an application identity callback. Duplicate identities contribute once per sequence. It returns original objects and fused scores; source filtering, citation rules, retrieval strategy and index ownership stay with the application. This helper is not a vector database or a search engine.

BM25(items, text=projection) in the same retrieval package delegates lexical statistics and scoring to rank-bm25. Applications pass already authorized candidates and their own text projection. The adapter uses BM25Plus with a zero baseline, so sources without query terms are not lexical matches. It returns original objects with native scores; combine independent ranks with the fusion helper rather than comparing unrelated score scales. Run index construction and ranking through the framework parallel service when called from asynchronous request or workflow code.

Checkpoint retention

Set ai.checkpoints.ttl_minutes to a positive number to delegate expiry to the native Redis saver. Optional refresh_on_read refreshes that retention on access. Omit retention to keep the existing persistent behavior. Cache flush does not remove checkpoints. await workflow.forget(thread_id=...) deletes the selected workflow thread through the native saver; stop active runs before deletion. Applications own authorization for thread identifiers.

Workflow restart and explicit resume remain native LangGraph behavior. Application jobs can rebuild their registered workflow and resume it through the durable queue module. An abandoned HTTP response does not automatically create a recovery job or replay its SSE events.