1. Introduction
The AI Search module integrates Drupal's Search API results with OpenAI-powered contextual responses and optional summaries. It enhances traditional keyword search by providing concise, AI-generated answers derived strictly from indexed site content.
The module is designed to be safe and deterministic: AI prompts instruct the model not to hallucinate or introduce information not found in the provided context.
2. Key Features
- Search API integration with configurable index.
- AI answer generation referencing top search results.
- Optional multi-document AI summary (first 20 results).
- Configurable model selection (GPT families) and response tuning (temperature, token limits).
- Analytics logging: queries, empty-result detection.
- Markdown → HTML conversion for AI responses.
- Clear administrative error logging (missing API key / index).
3. Requirements
| Component | Minimum | Notes |
|---|---|---|
| Drupal Core | 10.0+ | Tested with Drupal 10.x. |
| PHP | 8.1+ | Consistent with Drupal 10 core requirements. |
| Search API | Latest stable | Provide an index; database backend acceptable. |
| Search API Backend | Database OR Solr/Elastic | Database backend sufficient for small & mid sites. |
| OpenAI Account | Valid API key | Generated at OpenAI. |
| HTTP Client | Guzzle (core) | Used via Drupal's service container. |
4. Installation
4.1 Download / Place Module
Place the module directory ai-search inside web/modules/custom.
4.2 Enable Module
drush en airagsearch -y
Or via the Drupal UI: Extend > Search > AI Search.
4.3 Create or Select Search API Index
- Navigate to
/admin/config/search/search-api. - Create a new index (e.g., Site Content).
- Select "Database" server or existing search server.
- Add fields: title, body, and optional taxonomy or metadata.
- Index the content (queue or immediate).
4.4 Rebuild Index (If Needed)
drush search-api:reindex <index_id>
# Example:
# drush search-api:reindex site_content_index
5. Configuration (Admin UI)
Path: /admin/config/search/airagsearch
The settings form is organized into logical sections (all collapsed by default):
5.1 Core Setup
| Setting | Description | Notes |
|---|---|---|
| OpenAI API Key | Your secret key (begins sk-). | Mandatory. Missing key logs error & disables AI features. |
| Search API Index | Index used for content retrieval. | Must exist and be populated. |
| ChatGPT Model | Select from GPT-4o, GPT-4 Turbo, GPT-3.5 etc. | Recommended: gpt-4o-mini for balance. |
5.2 Search Behavior
| Setting | Description | Notes |
|---|---|---|
| Results Per Page | Pagination size for search listing. | Default: 10. Range: 1-100. |
5.3 AI Context Settings
Important: These settings directly impact OpenAI token usage and costs.
| Setting | Description | Notes |
|---|---|---|
| AI Response Context Count | Number of search results used for AI responses. | Default: 3. Range: 1-50. More results = better context but higher costs. |
| Summary Context Count | Number of results for AI summaries. | Default: 20. Range: 5-50. Used on summary page. |
| Content Length Per Result | Character limit per search result sent to AI. | Default: 1200 chars. Range: 200-5000. Each char ≈ 0.25 tokens. |
5.4 Analytics & Logging
| Setting | Description | Notes |
|---|---|---|
| Max Analytics Records | Retention cap for search logs. | Default: 1000. Range: 100-100000. Older records pruned automatically. |
5.5 Advanced AI Parameters
| Setting | Description | Notes |
|---|---|---|
| Temperature | Controls creativity (0–2). | Lower = deterministic answers; default: 0.7. |
| Max Response Tokens | Upper bound for answer length. | Default: 500 tokens (~2000 chars). Range: 50-4000. |
6. Performing Searches
6.1 Search Page
URL: /airagsearch. Users enter keywords; module stores the last query in session for summary generation.
6.2 Relevance
The controller attempts to sort by search_api_relevance if the field is available. Ensure your index back-end supports relevance scoring.
6.3 Context Documents
Top results (currently first 3 for answers) are converted into concise context objects (title, body snippet, URL) passed to OpenAI for answer synthesis.
7. AI Responses & Summaries
7.1 Answer Generation
The module constructs a prompt instructing the model to reply only using provided context. If insufficient, it returns a fallback message.
7.2 Context Building
Context sent to OpenAI is configurable via AI Context Settings:
- AI Response Context Count: Number of top search results used for generating answers (default: 3)
- Content Length Per Result: Character limit per result sent to AI (default: 1200)
- Field Priority: Content extracted in order: body → field_body → search_api_fulltext → rendered_item
- Processing: HTML tags stripped, content trimmed, truncated if over character limit
7.3 Summary Page
URL: /airagsearch/summary (available after a successful search). Uses configurable number of results (default: 20) for comprehensive summaries.
7.4 Markdown Processing
AI output is converted to HTML via the module's MarkdownProcessor service.
7.5 Token & Cost Management
- Context Count: More results = better context but exponentially higher costs
- Content Length: Longer content = more detailed context but higher token usage
- Max Response Tokens: Reduce for shorter answers; raise for thorough summaries
- Temperature: Lower (0–0.5) for strict factual; higher for narrative summaries
8. Analytics Dashboard
Path: /admin/reports/airagsearch-analytics. Displays logged queries, counts, and whether a query returned results.
8.1 Data Retention
Older records are pruned automatically once the configured cap is exceeded.
8.2 Privacy Considerations
Avoid logging personally identifiable information (PII) as part of queries. The module does not store user IDs by default for analytics.
9. Security & Privacy
- API Key Storage: Stored in Drupal config; restrict export if sharing code.
- Sanitization: Output from AI is treated as content; Markdown conversion strips scripts.
- Context Scope: Only indexed site content is sent to OpenAI; sensitive content should not be indexed.
- Logging: Errors include high-level details; avoid logging full sensitive body content.
10. Performance Considerations
- Search query performance depends on backend; database backend is adequate for moderate volumes.
- AI calls introduce latency (network + model processing). Typical range: 400ms–2s for short prompts.
- Consider caching AI responses for identical queries if cost becomes a concern (custom extension recommended).
- Limit context documents (currently 3 for answers) to balance relevance and token usage.
11. Troubleshooting
11.1 Missing API Key
Error log: Missing OpenAI API key: set it at /admin/config/search/airagsearch.... Add key under settings.
11.2 Missing Search API Index
Response: { error: 'Search API index is not configured...' }. Select index in settings and re-run search.
11.3 No Results Returned
Log entry indicates empty result; AI answer replaced by fallback message.
11.4 Invalid Key Format
Settings validation flags suspicious keys not starting with sk-.
11.5 Timeouts
OpenAI requests default to 30–40s timeout. Reduce response size (tokens) or check network if frequently exceeded.
11.6 Token Errors
Adjust Max Tokens downward; ensure model supports requested length.
11.7 Drush Cache Clear
drush cr
12. Uninstallation
- Disable module:
drush pm:uninstall airagsearch -y - Remove directory:
rm -rf web/modules/custom/airagsearch - Optionally delete related analytics tables (if created) and configuration in the database.
13. FAQ
Q: Can I use another AI provider?
A: Not in core module version; you can swap the OpenAIClient service with a custom implementation via service overrides.
Q: How do I change the number of context documents?
A: Modify the controller logic limiting $ai_context_docs (currently first 3 results).
Q: Does the module cache AI responses?
A: No built-in caching. Add a custom layer (e.g., key-value store keyed by normalized query string).
Q: Are user roles considered?
A: Access checks rely on Search API index entity visibility. Ensure indexed data respects permissions.
14. Change Log (Overview)
- Initial Release: Core search + AI integration, settings form, analytics logging.
- Enhancement: Explicit error logging for missing API key / index.
- Docs: Added
help.htmlmanual.