Skip to content

Services

The AI Context module registers the following services in ai_context.services.yml.

Core services

ai_context.request_factory

Class: Drupal\ai_context\Service\AiContextRequestFactory

Builds AiContextRequest value objects from agent config or raw parameters, and provides convenience methods for non-agent modules that just need rendered context.

Request-building methods:

  • fromAgent(string $agentId, string $task, ...) -- builds a request from a saved agent config entry.
  • fromParameters(AiContextRequestParamsData $params) -- builds a request from a strongly-typed DTO (used by function call plugins and advanced consumers).

Convenience methods (build + select in one call):

// One-liner: returns the rendered context string (empty if nothing matches).
public function getRenderedContext(
  array $scopes = [],
  ?int $maxTokens = NULL,
  ?EntityInterface $targetEntity = NULL,
  ?string $consumerId = NULL,
): string

// Full result with cache metadata, selected IDs, token usage.
public function getResult(
  array $scopes = [],
  ?int $maxTokens = NULL,
  ?EntityInterface $targetEntity = NULL,
  ?string $consumerId = NULL,
): AiContextResult

Usage examples:

/** @var \Drupal\ai_context\Service\AiContextRequestFactory $factory */
$factory = \Drupal::service('ai_context.request_factory');

// Get rendered context text (returns empty string if nothing matches).
$text = $factory->getRenderedContext(
  scopes: ['use_case' => ['empathy_evaluation']],
  maxTokens: 2000,
  targetEntity: $node,
  consumerId: 'my_module',
);

// Or get the full result object with cache metadata and selected item IDs.
$result = $factory->getResult(
  scopes: ['use_case' => ['empathy_evaluation']],
  maxTokens: 2000,
  targetEntity: $node,
  consumerId: 'my_module',
);
$text = $result->getRenderedText();
$cacheMetadata = $result->getCacheableMetadata();
$selectedIds = $result->getSelectedItemIds();

Parameters:

  • scopes: Scope subscriptions keyed by scope plugin ID. Pass an empty array to match all published context (subject to token/item limits).
  • maxTokens: Maximum tokens for rendered output. NULL defers to module settings.
  • targetEntity: An entity object for target-entity scope matching.
  • consumerId: Identifier for logging/debugging (e.g., your module name).

These methods use match_all selection mode by default, so all published candidates that pass context filters are considered.

ai_context.selector

Class: Drupal\ai_context\Service\AiContextSelector

Interface: Drupal\ai_context\Service\AiContextSelectorInterface

Orchestrates context selection: filtering, scope scoring, subcontext resolution, and rendering. Has zero knowledge of agents or event APIs.

Key method:

public function select(AiContextRequest $request): AiContextResult

The AiContextResult contains the rendered text, selected item metadata, token usage, and CacheableMetadata.

ai_context.scope_resolver

Class: Drupal\ai_context\Service\AiContextScopeResolver

Scores context items against scope subscriptions and applies hard context filters (e.g., language, site section). Replaces the former AiContextScopeMatcher.

ai_context.renderer

Class: Drupal\ai_context\Service\AiContextRenderer

Renders selected context items into a token-limited text block for prompt injection. Receives pre-translated entities from the selector.

ai_context.subcontext_resolver

Class: Drupal\ai_context\Service\AiContextSubcontextResolver

Resolves child (subcontext) items for selected parent items. Supports AI-based conditional inclusion when a provider/model is configured. Conditional children are skipped when no provider/model is configured or when provider selection fails. This service assumes saved parent-child relationships already satisfy the entity integrity rules.

ai_context.entity_target_resolver

Class: Drupal\ai_context\Service\AiContextEntityTargetResolver

Resolves the current entity from the route or request context. Used to match context items that target specific entities.

ai_context.usage_tracker

Class: Drupal\ai_context\Service\AiContextUsageTracker

Records usage data when context items are selected. Tracks which items were used, by which agent, on which route, and which entities were involved.

ai_context.children_service

Class: Drupal\ai_context\Service\AiContextChildrenService

Provides parent/child hierarchy queries for context items and supports cleanup of child references when a parent item is deleted.

ai_context.item_validator

Class: Drupal\ai_context\Service\AiContextItemValidator

Validates persistence-level invariants for context items. For subcontexts, it prevents self-parenting, nested subcontexts, and converting an item with children into a subcontext. It also requires subcontext_type when a parent is selected.

Plugin managers

plugin.manager.ai_context_scope

Class: Drupal\ai_context\AiContextScopeManager

Plugin manager for scope plugins. Handles discovery, instantiation, and weight-based sorting of AiContextScope plugins.

Support services

ai_context.markdown_renderer

Class: Drupal\ai_context\Markdown\MarkdownRenderer

Converts markdown content to HTML for display.

logger.channel.ai_context

Standard Drupal logger channel for ai_context log messages.

Event subscribers (registered as services)

ai_context.system_prompt_subscriber

Class: Drupal\ai_context\EventSubscriber\AiContextSystemPromptSubscriber

Listens for BuildSystemPromptEvent and AgentStartedExecutionEvent. See Events.

ai_context.agent_tool_subscriber

Class: Drupal\ai_context\EventSubscriber\AiContextAgentToolSubscriber

Listens for AgentToolFinishedExecutionEvent. See Events.

Route subscribers

ai_context.route_subscriber

Class: Drupal\ai_context\Routing\AiContextRouteSubscriber

Alters routes for the module.

ai_context.scope_route_subscriber

Class: Drupal\ai_context\Routing\AiContextScopeRouteSubscriber

Dynamically generates routes for per-scope settings forms based on discovered scope plugins.

Access checks

ai_context.access_check.overview_page

Class: Drupal\ai_context\Access\AiContextOverviewAccessCheck

Controls access to the overview page based on the show_overview_page setting.

ai_context.access_check.usage_page

Class: Drupal\ai_context\Access\AiContextUsageAccessCheck

Controls access to the usage tracking page based on whether tracking is enabled.

Other services

ai_context.uninstall_validator

Class: Drupal\ai_context\AiContextUninstallValidator

Prevents uninstalling the module when context items exist.

Drupal\ai_context\Hook\DiffHooks

Class: Drupal\ai_context\Hook\DiffHooks

Autowired service for Diff module integration hooks.

Drupal\ai_context\Hook\DynamicEntityReferenceHooks

Class: Drupal\ai_context\Hook\DynamicEntityReferenceHooks

Autowired service for Dynamic Entity Reference module integration hooks.