Skip to main content

106 docs tagged with "concept"

View all tags

Agent Approval / Permission Policy

AgentPermissionPolicy performs permission checks before tool execution: ALLOW / DENY / REQUIRE_APPROVAL. It can be reused by regular Agents, Blueprints, the CLI approval UI, and the later Sandbox SPI.

Agent Architecture

Breaks down the three-layer boundaries of ai4j-agent (Builder, Runtime, ModelClient), the dual faces of tool declaration and execution, memory as the state source, and the architectural positioning of the event stream and trace.

Agent Concept Map

The navigation map for every core agent concept in ai4j: 20 concepts organized into 7 capability clusters — the capability triangle (Function Call/MCP/Skill), the memory and context chain, the execution core layers, the security boundary, observability, external protocols, and engineering. Each cluster marks the relationships between concepts, with a one-sentence positioning and a deep link to the detail page.

Agent Overview

ai4j-agent overview: built on the Core SDK, it provides multi-step reasoning, tool loop, memory, workflow, trace, and multi-agent collaboration — when to use Agent, the minimal mental model, runtime selection, and module boundaries.

Agent Session Runtime

Walks through the AgentSession long-running state container: sessionId, independent memory, event log, snapshot/restore and AgentSessionStore, plus its boundaries against memory/compact, the Coding Agent/CLI, and production implementation guidance.

Agent Teams

AI4J Agent Teams is a team runtime with a control plane: the planner decomposes the task, the task board maintains dependencies and state, members collaborate via injected team_* tools, and the synthesizer aggregates the final answer.

Agent usage paths and scenario selection

Helps you pick an abstraction layer by system structure: ReAct is the default starting point, CodeAct swaps the intermediate representation, Workflow adds explicit nodes, SubAgent does controlled delegation, Teams introduces a collaboration model; with a decision table and common misjudgements.

Agent, Tool, Knowledge Base, and MCP Integration

Explains the capability wirings FlowGram ships built-in today (LLM/TOOL/KNOWLEDGE) versus those that can only be extended (Agent/MCP have no dedicated built-in nodes), and traces the real wiring behind the TOOL node reusing the tool bus and the KNOWLEDGE node reusing the RAG abstraction.

AI4J Docs

AI4J is a Java 8+ AI SDK entry point — an overview, recommended starting points, and a repository module map for its on-demand building blocks: model calls, tools, RAG, MCP, Spring Boot, Agent, Coding Agent, and FlowGram.

Annotation-based Tools

An in-depth look at how the three annotations @FunctionCall, @FunctionRequest, and @FunctionParameter bind Java types to provider tool schema, with details on the ToolUtil generation pipeline, type mapping rules, and real-world constraints.

Architecture and Module Map

Maps the AI4J repository's Maven module mainline, dependency direction, and code-location entry points onto real engineering, helping you find the right landing point when reading source code or evaluating module boundaries.

Architecture at a Glance

Build a mental model of AI4J with a four-layer diagram: Getting Started, the Core SDK base, upper modules (Spring Boot/Agent/Coding Agent/FlowGram), and recipes — plus the boundaries between the three most easily confused concepts: Function Call, Skill, and MCP.

Audio Service Interface

Introduces the AI4J audio service surface: unified entry points for TTS, transcription, and translation, the OpenAI implementation, request-object validation, and resource and failure semantics.

Built-in Nodes

Distinguishes Flowgram runtime kernel nodes (START/END/LLM/CONDITION/LOOP) from the executor nodes registered by the starter (HTTP/VARIABLE/CODE/TOOL/KNOWLEDGE), and clarifies the shared value-resolution model and the inputs and outputs of each node.

Chat

Breaks down the runtime behavior of the AI4J Chat main line: the request object, the automatic tool loop, passThroughToolCalls, SseListener streaming aggregation, and multimodal wiring.

Chat Memory

A deep dive into the ChatMemory contract: ChatMemoryItem carries multimodal and tool facts, InMemory and Jdbc storage backends, windowing and summary policies, snapshot recovery, and the shared foundation that projects onto both Chat and Responses.

Chat vs Responses

Compare the Chat and Responses main lines across input mental model, provider coverage, tool integration, streaming semantics, and multimodal projection to help you choose.

Choose Your Path

Pick your main entry into AI4J by goal: the default reading order, plus recommended starting points and when to go deeper for model calls, Spring Boot integration, Tool/MCP/Agent/Coding Agent/FlowGram.

Chunking Strategies

Explains the actual behavior and boundaries of AI4J's default RecursiveTextChunker: it only fills documentId/content/chunkIndex, does not auto-generate chunkId, page numbers, or section metadata, and how chunk boundary stability governs downstream retrieval deduplication and citation quality.

Citations and Trace

Distinguishes AI4J's citation and trace chains: citations are generated by DefaultRagContextAssembler from the final hits, while trace records the intermediate state of retrieval and rerank; generation usage and judge scores must be backfilled explicitly by the upper layer.

CLI / TUI Usage Guide

Explains how the code and tui entry points share the same coding runtime, where they diverge (JLINE/legacy/TUI runtime), and the real boundaries of host-layer behavior such as slash commands, /stream, and the session store.

CodeAct Runtime

CodeActRuntime replaces native tool-calling with a code/final JSON protocol, bringing model-generated executable code into the main loop, with CodeExecutor bridging tools and deciding the closing path.

CodeAct: Custom Code Sandbox Executor

Explains CodeAct's code execution boundary and the CodeExecutor extension point: when to replace the default executor, how to handle tool bridging, and the isolation and security constraints production must add.

Coding Agent Architecture

Breaks down the layered architecture of the Coding Agent from the main execution chain: the CodingAgentBuilder assembly point, the WorkspaceContext boundary, the CodingSession container, the delegation runtime, the approval decorator, and the host runtime division of responsibilities.

Coding Agent Overview

Overview of the AI4J Coding Agent module responsibilities, the three host entry points (CLI/TUI/ACP), and core concepts, helping you decide whether local code repository tasks fit the Coding Agent runtime.

Compact and Checkpoint Mechanism

Explains the compact/checkpoint pipeline of ai4j-coding: the responsibility split and tuning entry points for tool-result microcompact, checkpoint summary, aggressive compact, fallback, and the auto-compact circuit breaker.

Comparison and Positioning

Positioning comparison between AI4J and alternatives such as Spring AI, LangChain4j, AgentScope Java, and Pi Agent. Not a takedown, but a clear explanation that AI4J focuses on a Java 8+ multi-module SDK, progressive integration capabilities, and a lighter on-demand adoption path, helping you decide when to choose AI4J.

Context Window Management

Explains ai4j's context window management: ContextBudget sets the budget (maxItems/maxApproxChars/pinnedPrefixItems), DefaultContextProjector projects using a keep head + tail strategy, and ContextReport reports drop diagnostics. This is the first gate before Compaction — it decides what enters the window, while Compaction decides how to compress what is still too large.

Core SDK Overview

Overview of the ai4j foundation capability lines: model access, Tool, Skill, MCP, Memory, RAG, and extensions — helps you choose your first main line and understand how it relates to the upper-layer modules.

DeepSeek Stream Search RAG

A response-chain solution that combines streaming output, web search, and private-domain RAG, covering responsibility layering, citation and evidence strategy, and upgrade criteria.

Embedding

Explains the AI4J embedding layer: a thin interface with strong constraints. It unifies provider calls but only supports OPENAI/OLLAMA, ingest and query must use the same model, and mixing is not auto-prevented by the framework — it is part of the index-level protocol.

Extending ai4j

Brings the four extension lines that let agents and the SDK do more into a single entry point: the plugin package contribution contract (discover/enable/allow/expose), the on-demand Skill methodology, plugin Prompt resources, and the provider/model/service extension for adding new LLM backends, marking each entry point and security boundary.

Extension Overview

Establish the AI4J extension mental model: provider/service goes through the PlatformType+AiService+Registry code main chain, HTTP concurrency and connection governance goes through the underlying SPI, and third-party plugin packages go through ai4j-extension-api+ServiceLoader+ExtensionRegistry; the extension surfaces are not symmetric.

First Tool Call

Explains what the "first tool call" really means in AI4J: the shortest local Function Call example, why Function Call, Skill, and MCP must be kept distinct, and the next-step topic tree to follow.

Flowgram Architecture

Breaks down the four-layer architecture of the Flowgram frontend canvas plus the AI4J backend execution layer: canvas, adaptation, Spring Boot platform wiring, and the execution engine — clarifying the difference between edit-time and run-time schema and the default security posture.

FlowGram Overview

AI4J FlowGram is the Java backend execution layer built around the FlowGram.ai canvas, converting workflow graphs drawn on the frontend into verifiable, runnable, cancellable, and observable asynchronous tasks.

Flowgram Runtime

The Flowgram backend execution truth: FlowGramRuntimeService turns a workflow schema into async tasks, the node graph into a stateful execution chain, and node outputs into report/result/trace read-side structures.

Flowgram Usage Paths and Scenario Selection

Maps five entry paths into Flowgram by task goal, and compares when to choose Flowgram, Agent, Coding Agent, or MCP, with a recommended evolution order, common misjudgments, and the shortest reading path by role.

Frontend Canvas and Backend Runtime Integration

The three contracts that align the Flowgram.ai canvas with the AI4J Java backend execution layer: workflow schema, task lifecycle, and the report/result/trace read side — covering schema normalization, polling, and permission integration points.

Function Calling

Explains the Function Calling execution chain at the AI4J foundation layer: declaring tools with annotations, generating provider tool schemas via ToolUtil against an allowlist, mounting tools onto a request and reading tool call results back, and the boundary between this layer and MCP and Agent.

How a front-end workflow executes on the back end

Breaks the full pipeline of a single workflow from edit state to execution state into six stages: JSON export, normalization, runtime plugin invocation orchestration, controller/facade/runtime layered execution, and read-side projection.

Hybrid Retrieval

Explains that the AI4J HybridRetriever is essentially a multi-retriever result fusion component rather than a fixed Dense+BM25 bundle: default RRF fuses by rank, deduplicates with a stable key, the fusion score semantics change, and there is deliberately no getHybridRagService convenience entry point.

Ingestion Pipeline

How AI4J's IngestionPipeline serves as the RAG ingestion orchestration layer: how source loading, text cleaning, chunking, metadata enrichment, batch embedding, and vector upsert chain into a unified pipeline, plus documentId/contentHash stability and pluggable extension points.

Legal Assistant

RAG solution for a high-evidence legal assistant, emphasizing metadata governance, evidence citations, and human review — distinct from a generic chatbot with a long prompt.

MCP and ACP

Clarify the two completely different boundaries inside the Coding Agent: MCP (bring external capabilities into the model's tool surface) and ACP (expose the coding session as a protocol to hosts), and how both take effect in the same session.

MCP Overview

AI4J builds MCP as a capability-wiring subsystem spanning four planes — client, transport, gateway, and server — rather than a single tool integration option. This page gives the overall map and a recommended reading order.

MCP Usage Paths and Scenario Selection

Splits MCP into three paths by the problem you want to solve: integrating an existing MCP, governing multiple MCPs, and publishing your own Java capabilities as an MCP; gives the key objects and reading order for each path.

Memory and State

Breaks down the state model of AgentMemory in ai4j-agent: how user input, model output, and tool output are uniformly fed back into the next turn's prompt, and the real semantics of writes, compaction, and session isolation in InMemoryAgentMemory and JdbcAgentMemory.

Memory and Tool Boundaries

Clarifies the responsibility boundaries across three layers — ChatMemory, Tool, and MCP. Memory only stores session facts; tool approval and side-effect governance belong to the runtime. Explains why execution control should not be coupled into the memory abstraction.

Memory Compact Context Projector

Introduces the ContextProjector and CompactPolicy in ai4j-agent: how to project a memory snapshot into the current turn's prompt, compress long-horizon context with a structured CompactResult, and keep the compaction process diagnosable and recoverable.

Memory Overview

Overview of the AI4J Core SDK session fact layer: ChatMemory records multi-turn conversations and tool results, with storage and trimming policies kept separate, projectable to both Chat and Responses inputs, with support for snapshot recovery and summary compaction.

Messages (Anthropic native)

Explains the IMessagesService native Anthropic protocol line: native in/out with zero conversion, coding-plan integration, thinking mapping, authentication, and exception handling.

Minimal ReAct Agent

Dissects the minimal but complete ReAct Agent run loop: AgentBuilder default wiring, the relationship between ReActRuntime and BaseAgentRuntime, the boundary between tool declaration and execution, and when an empty-tool Agent is valid.

Model Access Overview

Overview of how model requests are modeled, projected, sent, streamed, and replayed within the AI4J foundation, clarifying the boundaries between the Chat, Responses, and Messages main lines.

Model Client Selection

Compares ChatModelClient vs ResponsesModelClient: protocol mapping of systemPrompt/instructions, top-level field pass-through differences, streaming signals, and memoryItems shapes — to help you pick the right model protocol path for your Agent.

Model Extension

Explains AI4J model extension: how to absorb new model capabilities into existing providers and existing contracts without introducing a new PlatformType. The main battleground is the request objects and the provider adaptation layer, with a strong emphasis on converging provider differences inside the provider service rather than leaking them into the business layer.

Multimodal

Explains how image-text input, carried as a session fact via ChatMemoryItem, projects onto both the Chat and Responses pipelines, and distinguishes native model input from external visual tools.

Online Search

Clarifies the real positioning of AI4J Online Search: it is not a unified retrieval framework, but rather an online search augmentation layer that wraps IChatService, uses the last message as the query to call SearXNG, splices the result JSON directly into the user prompt, and rewrites the request in place.

Package Map

Maps the source layout of the ai4j module using a package-cluster mental model, identifies the responsibilities of primary capability surfaces and supporting-layer packages, and suggests a recommended order for reading the source.

Plugin Packages

Explains the AI4J plugin package: third-party jar + ServiceLoader discovery + ExtensionRegistry three-stage gate of discover/enable/exposeTool, distinguishes how tool/command/Skill/Prompt/Guardrail resources enter the runtime, and tools are not exposed to the model by default.

Programmatic Integration

How to embed ai4j into your application: gathers five scattered integration threads — the AiService programmatic entry point, the ACP host protocol, trace/replay observability, CLI/TUI embedding, and Spring Boot auto-configuration — into a single landing page, with a one-sentence positioning and a deep link for each.

Prompt Assembly and Context Sources

Breaks down the 5 categories of prompt sources fed into the model (base system prompt, workspace prompt, instructions, session memory, current turn) plus the standalone tool schemas, so you know what order to check when tracking down behavior drift.

Protocol Capabilities

Explains the AI4J MCP protocol surface: the server supports three capability types (tools/resources/prompts) plus list_changed notifications, the legacy profile requires an initialize handshake while modern Streamable HTTP is stateless, and the transport affects the capability boundary.

Provider Extension

Explains the AI4J provider extension: integrating a new model platform is an explicit factory-dispatch extension that must simultaneously touch PlatformType, Configuration, AiService, DefaultAiServiceRegistry, and the Spring Boot starter; the provider support matrix is maintained explicitly rather than auto-discovered.

Provider Profiles and Model Switching

Explains the real semantics of a provider profile as a switchable, fallback-capable provider runtime binding, covering activeProfile/effectiveProfile resolution, the /provider and /model commands, and session runtime rebinding.

Query Planning

Explains the AI4J RagQueryPlanner retrieval preprocessing layer: before the Retriever it produces rewrite/multi-query/HyDE/step-back retrieval plans, fuses multi-variant results with RRF, keeps rerank and context assembly on the original query, and falls back automatically when the planner throws.

RAG Evaluation

Clarifies the boundary between AI4J's two evaluators: the offline RagEvaluator computes precision/recall/F1/MRR/NDCG from human-annotated relevant ids to measure retrieval quality, while the online RagOnlineEvaluator scores faithfulness with a judge model after an answer is generated. The two are neither mixed nor interchangeable.

RAG Ingestion Vector Store

AI4J's standard RAG engineering baseline, wiring together document ingestion, embedding, vector store, and the retrieval chain — not bound to any specific vector store brand.

Realtime Interface (WebSocket)

Describes the IRealtimeService long-lived-connection capability surface: currently only supports OpenAI, with a unified entry point, default auth headers, the WebSocket connection flow, and callback caveats.

Request and Response Conventions

A unified walkthrough of request construction and response reading conventions, distinguishing locally registered fields from provider payload fields, the role of extraBody, and common integration pitfalls.

Rerank

Explains the AI4J rerank layer: it sits between retrieval and context assembly to correct ranking, defaults to NoopReranker with no remote reranking, ModelReranker maps results by the provider-returned index, finalTopK trims after reranking, and returnDocuments may rewrite hit content.

Responses

Breaks down the AI4J Responses line: ResponseRequest semantics, the shared tool-resolution foundation, payload construction, streaming event aggregation, and the runtime-friendly execution model.

Runtime Architecture

Breaks down the 5-layer assembly chain of the Coding Agent runtime (factory, builder, session, host, MCP runtime), explaining what state each layer holds, what behavior it decides, and where its boundaries with adjacent layers lie.

Runtime Implementations

Breaks down the three runtimes — ReActRuntime, CodeActRuntime, and DeepResearchRuntime: they share the BaseAgentRuntime main loop, and differ in the intermediate representation of model output, when to switch that representation, and when to write a custom runtime.

Search and RAG Overview

Establish the source-code mental model of AI4J Search & RAG: two parallel boundaries — the offline private-domain route IngestionPipeline→VectorStore→Retriever→Reranker→ContextAssembler and the online public-web route ChatWithWebSearchEnhance — plus the distinction between the default skeleton and optional enhancements.

Security Overview

AI4J's security boundary is composed of multiple layers: secrets, network, Tool, MCP, RAG, Agent, Coding Agent, and FlowGram. Before integration, clarify: which capabilities can be seen, called, or written back to users or logs by the model. No secrets in the repo, minimal Tool exposure, local boundary constraints.

Service Entry and Registry

Clarifies the real responsibilities of the AiService single-instance entry point and the AiServiceRegistry multi-instance registry, their configuration fallback, and extension boundaries.

Service Extension

Clarifies AI4J service extension: adding a new top-level capability contract expands the SDK's entire public API surface, so you must keep AiService, AiServiceRegistry, and the FreeAiService compatibility entry points in sync. AiServiceFactory is not a service plugin bus; a new service is only worth adding when the existing contracts can no longer carry the load.

Sessions, streaming, and processes

Explains how the Coding Agent session runtime turns a local coding task into a sustainable, interruptible, and resumable working session: CodingSession, the outer loop, the event ledger, the process plane, and the headless event stream.

Skill Activation

Explains the three paths by which skill content enters the context (model-selected read_file, host selectedSkills, host providedContents), the security model of the restricted executor, and why AI4J does not provide a dedicated activate_skill tool.

Skill Discovery

A deep look at Skills discovery and loading: scanning the workspace and global root directories, recognizing SKILL.md, extracting the name and description, deduplicating by name, and how allowedReadRoots links the skill directories into the host's read-only security boundary.

Skill vs Tool vs MCP

Distinguish AI4J's three foundation concepts with definitions, a comparison table, and source entry points: Skill governs methodology context, Tool governs in-host execution, and MCP governs external protocol integration. Clarifies common confusions about projection versus ownership.

Skills Overview

Overview of the AI4J Skills methodology and context-governance layer: discover SKILL.md, generate a skill catalog, lazily load bodies on demand, and bring skill roots into a read-only boundary — clarifying the division of responsibilities between Skill, Tool, and MCP.

Solutions Overview

Entry point for AI4J solution compositions: solution paths, module combinations, and guidance on when to return to the main line, organized by common business problems.

SPI HTTP Stack

Explains the AI4J HTTP stack SPI: Dispatcher and ConnectionPool are injected via ServiceLoader into the unified OkHttpClient built by the starter, default implementations are registered through META-INF/services, and losing them causes startup failure — only the starter auto-configuration chain activates it automatically.

Streaming

Explains the aggregation model behind the two main streaming lines, Chat and Responses: the state held by SseListener and ResponseSseListener, tool-call aggregation, and termination-condition differences.

Strengths and Differentiators

What sets AI4J apart as a Java AI foundation: unified capabilities, clear boundaries, asymmetric providers, and an upward evolution path, along with where it fits best.

SubAgent and Handoff Policy

A breakdown of how SubAgent wraps another Agent into a governed tool — StaticSubAgentRegistry exposes the schema, SubAgentToolExecutor intercepts the handoff, and HandoffPolicy defines depth, timeout, deny/fallback, and session-mode semantics.

System Prompt vs Instructions

Clarifies the source-level semantics of systemPrompt vs instructions in ai4j-agent: both are AgentContext configuration that re-enters the model every step, but they map differently on the Chat and Responses paths, and must be layered deliberately under CodeAct.

Tool Execution Model

Breaks the AI4J tool execution model into four stages — discovery and registration, request-level allowlist, provider returning the tool call, and local call routing and execution — and clarifies the built-in/Function/MCP precedence and how results flow back as text.

Tool Exposure Semantics and Security Boundaries

Clarifies the security boundaries of MCP tool exposure: getAllTools explicit allowlist and getLocalMcpTools local enumeration are two distinct semantics, and invocation priority and exposure surface are two separate concerns, with a code review checklist attached.

Tool Whitelist and Security

AI4J's two layers of tool security: a request-level functions/mcpServices allowlist and BuiltInToolContext workspace read/write boundaries, with a look at high-risk built-ins like bash and the still-missing approval/sandbox governance.

Tools and Registry

Breaks down the ai4j-agent tool system: AgentToolRegistry only owns the exposure surface, ToolExecutor owns execution and the permission boundary, how the runtime normalizes, validates, and executes tools and feeds results back into memory, and which layer approval interception belongs on.

Tools and the Approval Mechanism

Breaks down how the Coding Agent's eight built-in tools (bash/read_file/write_file/apply_patch/glob/grep/edit/update_agents_md) are wired together, executor routing, where the approval decorator intercepts, and why approval and workspace boundaries must be understood separately.

Tools Overview

Breaks down the four layers of the AI4J tools subsystem: tool declaration, request-scoped allowlist, provider schema projection, and local execution loopback, clarifying the complete execution chain and capability boundary with ToolUtil as the dispatch center.

Trace and Observability

Explains trace and observability in ai4j-agent: traceExporter is the actual switch, the default records everything and needs masking/truncation, how events collapse into spans, the applicability boundary of each exporter, and the real relationship with OTel/Langfuse/FlowGram.

TUI Customization and Theming

Explains the four TUI customization layers (config, theme, renderer, runtime) - theme lookup order, file-level override semantics of tui.json, the difference between --theme and /theme, and how useAlternateScreen affects the runtime backend.

Using and Organizing Skills

Explains the real position of Skills in the Coding Agent as file-based workflow knowledge: discovery chain, scanning and dedup rules, SKILL.md field parsing, and how skills affect both the prompt and the read-only path boundary.

Vector Store and Backends

How the AI4J VectorStore contract unifies five backends (Pinecone/Qdrant/Milvus/PgVector/Redis): dataset is a hard boundary, capabilities() explicitly exposes returnStoredVector/metadataLookup differences — one call surface, without flattening storage reality.

Why Agent

Answers why AI4J needs a separate Agent layer: multi-step execution sooner or later forces out a runtime, a state source, and tool governance. Agent unifies the main loop, state semantics, governance boundaries, and observability, rather than rebuilding a parallel framework.

Why AI4J

Answers why you might consider AI4J in a Java project: the trade-offs of a progressive AI SDK for Java 8+, module layering you can take on by stage, and how it differs from Spring AI, LangChain4j and the scenarios it fits.

Why Coding Agent

Explains the 5 layers of local-delivery semantics that Coding Agent stacks on top of a generic Agent (workspace, coding tools, multi-turn loop, session/compact/restore, CLI/TUI/ACP hosts), and draws the real boundary between it and an ordinary Agent.

Why Flowgram

The reason Flowgram exists — it supplies the platform-grade backend structure an Agent alone cannot offer (workflow contracts, task lifecycle, node-level execution boundaries, and platform-facing read-side outputs), and clarifies its current boundaries and applicable scenarios.

Workflow and StateGraph

Walks through the Workflow and StateGraph of ai4j-agent: an orchestration layer rather than a runtime, nodes pass only outputText by default, WorkflowContext as a side channel, StateGraph edge-resolution priority, and maxSteps fuse semantics.