Skip to content

feat: add RAG search tool with Weaviate backend - #73

Merged
pavelanni merged 14 commits into
mainfrom
feature/rag-weaviate
May 16, 2026
Merged

pavelanni merged 14 commits into
mainfrom
feature/rag-weaviate

Conversation

@pavelanni

@pavelanni pavelanni commented May 16, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Add a rag_search tool that retrieves semantically similar document chunks from a Weaviate vector database
  • Uses raw HTTP/GraphQL (net/http) instead of the Weaviate SDK — zero new dependencies, keeping the binary lean
  • One rag.Client interface with a Search method, making future backend connectors (Milvus, pgvector) drop-in additions
  • Optional rag: block in agent-config.yaml — if absent, no tool is registered; if present, the tool is auto-available

Design

Component Location Description
Interface pkg/rag/rag.go Client interface + Chunk type
Config pkg/rag/config.go Config struct, defaults, factory
Weaviate client pkg/rag/weaviate.go HTTP/GraphQL implementation
Tool internal/ragsearch/ rag_search tool (implements tools.Tool)
Wiring internal/cmd/serve.go 14 lines, RegisterAlwaysAllowed
Test infra testdata/rag/ Docker Compose, curl-based seeder, testing guide

Config example

rag:
  backend: weaviate
  url: http://localhost:8080
  collection: Docs
  text_field: content
  default_limit: 5
  max_limit: 20

Test plan

  • 17 unit tests (10 in pkg/rag/, 7 in internal/ragsearch/)
  • End-to-end tested locally: Weaviate + Ollama via Docker Compose, 8 sample docs ingested, agent correctly calls rag_search and synthesizes answers from retrieved chunks
  • go test ./... passes, golangci-lint clean on changed packages
  • Kubernetes/OpenShift deployment (deferred — covered in design doc docs/dev/2026-05-15-rag-feature.md)

Design doc

docs/dev/2026-05-15-rag-feature.md — includes Kubernetes manifests, Helm chart options, and OpenShift-specific notes for future deployment.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added RAG (Retrieval-Augmented Generation) search functionality for semantic document retrieval
    • New rag_search tool available when configured with Weaviate backend support
    • Optional RAG configuration block in agent-config.yaml
  • Documentation

    • Comprehensive integration guides for local Docker Compose deployment and Kubernetes/OpenShift environments
    • Local testing guide with sample setup and verification steps

pavelanni added 11 commits May 15, 2026 18:46
Adds rag_search tool that wraps rag.Client for use in agentic loops.
The tool accepts query and optional limit, returns formatted chunks
with scores. Follows the existing tool pattern (readfile, exec).

Tests:
- Tool name and parameters schema
- Execute with mock RAG client
- Missing query validation
- Default/max limit enforcement
- Client error propagation
- No results case

All 7 tests pass.

Signed-off-by: Pavel Anni <[email protected]>
Makes seed.sh container-runtime agnostic (works with Docker,
Podman, or any setup where Ollama is reachable via HTTP).

Signed-off-by: Pavel Anni <[email protected]>
@coderabbitai

coderabbitai Bot commented May 16, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@pavelanni has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 40 minutes and 55 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Enterprise

Run ID: d6cdf735-2672-457b-a3ba-46681ff60ffc

📥 Commits

Reviewing files that changed from the base of the PR and between 82ee461 and 50f35fb.

📒 Files selected for processing (8)
  • README.md
  • docs/dev/2026-05-15-rag-feature.md
  • internal/ragsearch/ragsearch.go
  • internal/ragsearch/ragsearch_test.go
  • pkg/rag/config.go
  • pkg/rag/config_test.go
  • pkg/rag/weaviate.go
  • testdata/rag/README.md
📝 Walkthrough

Walkthrough

This PR adds RAG (Retrieval-Augmented Generation) support to DocsClaw using Weaviate as the vector database backend. The changes introduce a new rag package with a client interface and Weaviate implementation, a rag_search tool for agents, optional RAG configuration in the agent config YAML, conditional tool registration during bootstrap, and comprehensive deployment documentation with local Docker Compose testing infrastructure.

Changes

Weaviate RAG Integration for DocsClaw

Layer / File(s) Summary
RAG Core Interface and Config
pkg/rag/rag.go, pkg/rag/config.go, pkg/rag/config_test.go
Defines the public Client interface with Search(ctx, query, limit) returning []Chunk, and a Chunk struct with ID, Text, Score, and Metadata. The Config struct models backend selection, URL, collection name, text field, and limit settings. ApplyDefaults populates missing TextField and clamps limit values; NewClient validates the backend and constructs a Weaviate client. Config tests verify default application and client creation for supported/unsupported backends.
Weaviate GraphQL Client
pkg/rag/weaviate.go, pkg/rag/weaviate_test.go
Implements WeaviateClient that builds and executes GraphQL nearText queries, POSTs to /v1/graphql, validates HTTP status and response structure, parses chunks by extracting text, ID, and _additional.distance from the response, computes Score as 1 - distance, and handles GraphQL/HTTP errors. Tests cover successful retrieval with score parsing, GraphQL error responses, HTTP non-200 responses, empty results, client validation, and query string escaping.
RAG Search Tool
internal/ragsearch/ragsearch.go, internal/ragsearch/ragsearch_test.go
Creates the rag_search tool with Name, Description, and Parameters metadata. Execute validates query as non-empty, applies default/max limit clamping, calls the RAG client, and formats results as numbered blocks with rank, score, and chunk text. Tests verify metadata, successful formatting, required input validation, limit handling, error propagation, and empty result messages.
Agent Bootstrap Integration
internal/cmd/agentconfig.go, internal/cmd/serve.go
Adds optional RAG *rag.Config field to AgentConfig mapped from the YAML rag key. During phase 2 startup, when agentCfg.RAG is configured, the serve command creates a RAG client, registers the rag_search tool as always-allowed, and logs the backend and collection; startup fails if client creation errors.
Feature Documentation
docs/dev/2026-05-15-rag-feature.md
Comprehensive guide covering design (single Client interface, WeaviateClient implementation, optional config-gated registration), YAML schema fields, Go implementation details (GraphQL query construction, chunk parsing, score conversion), client factory dispatch, tool input schema and execution logic, and backend extension guidance.
Local Testing Guide and Deployment Infrastructure
testdata/rag/README.md, testdata/rag/docker-compose.yaml, testdata/rag/seed.sh, testdata/standalone/agent-config.yaml
Provides step-by-step local testing with Docker Compose (Weaviate + Ollama), a seed script that pulls the embedding model, creates a Docs collection, ingests sample documents, and verifies search. Includes example agent config with RAG enabled, instructions for testing via chat and curl, Kubernetes/OpenShift deployment notes, cleanup and troubleshooting guidance.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the primary change: adding a RAG search tool with a Weaviate backend, matching the main objectives of the pull request.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/rag-weaviate

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

- Use jq for JSON construction in seed.sh to prevent escaping bugs
- Return error on unexpected Weaviate response shape instead of silent nil
- Add explicit validation for empty backend config
- Document cosine distance assumption on Chunk.Score
- Assert default limit value in test
- Update design doc to match actual seed.sh implementation
- Replace python3 dependency with jq in seed.sh

Signed-off-by: Pavel Anni <[email protected]>
@pavelanni
pavelanni marked this pull request as ready for review May 16, 2026 00:19

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/dev/2026-05-15-rag-feature.md`:
- Around line 224-228: The two unlabeled fenced code blocks (the explanatory
paragraph block and the example result block referenced at lines 224 and 249)
are triggering markdownlint MD040; update each opening fence from ``` to ```text
so both blocks are explicitly labeled as text (i.e., change the fence before
"Search the document store..." and the fence before "[1] (score: 0.91)..." to
use ```text).
- Around line 67-84: Update the docs to reflect the shipped RAG implementation:
remove the go get instruction for github.com/weaviate/weaviate-go-client/v5 and
replace the SDK-based example (pkg/rag/weaviate.go and pkg/tools/rag_search.go)
with guidance that the project uses raw HTTP/GraphQL requests implemented in
internal/ragsearch/ragsearch.go; describe the HTTP/GraphQL approach and
reference the internal/ragsearch/ragsearch.go tool and its exposed
functions/methods when explaining how to perform searches instead of referencing
weaviate-go-client types like weaviate.Client or graphql.Query.

In `@internal/ragsearch/ragsearch.go`:
- Around line 47-55: Trim and validate the query string (use strings.TrimSpace
on args["query"] and treat whitespace-only as empty) and return
tools.Errorf("query is required") if it's empty; for limit, normalize multiple
numeric types instead of only float64 by handling int, int64, float32, float64
and json.Number (or string) via a type switch on args["limit"], convert to int,
enforce >0 and fall back to t.config.DefaultLimit if missing/invalid, and ensure
fractional float64 values are converted with int(...) only after validating
positivity.

In `@pkg/rag/config.go`:
- Around line 26-30: The constructor NewClient currently dereferences
cfg.Backend before checking cfg for nil; add an explicit nil check at the start
of NewClient to return a typed error (e.g., fmt.Errorf("rag: config is
required")) when cfg == nil, then proceed to validate cfg.Backend and call
cfg.ApplyDefaults(); reference the NewClient function and the
Config.ApplyDefaults method when making this change so callers get a clear,
non-panic error for nil configs.

In `@pkg/rag/weaviate.go`:
- Around line 105-116: The code currently coerces a missing/invalid
_additional["distance"] to 0 causing Score=1; in the weaviate query parsing
(where you read obj[w.textField], additional := obj["_additional"], id,
distance) explicitly check that additional["distance"] exists and type-asserts
to float64 (or convertible numeric) before computing Score; if the distance is
missing/invalid, do not set Score to 1 — instead skip that result (or omit
appending the Chunk) or handle it via a clear fallback (e.g., continue) so bad
records aren’t ranked as top hits; update the Chunk creation logic around
distance, id, and Score accordingly.
- Around line 21-34: NewWeaviateClient currently allows an empty textField which
later causes silent failures when extracting chunks; update NewWeaviateClient to
validate textField and either return an error if it's empty or assign a sensible
default before constructing WeaviateClient. Specifically, in NewWeaviateClient
check the textField parameter (in addition to baseURL and collection) and if
empty either return fmt.Errorf("weaviate: textField is required") or set
textField = "<default_field_name>" (pick a canonical field used elsewhere)
before returning the &WeaviateClient{...}; ensure the unique symbol
NewWeaviateClient and struct fields textField, baseURL, collection are updated
accordingly.

In `@testdata/rag/README.md`:
- Around line 49-63: The fenced code blocks in the README sample outputs are
missing a language token which triggers markdownlint MD040; update each
triple-backtick fence for the example output blocks (the large CLI/output
snippets shown in the README) to include a language token such as text (i.e.
change ``` to ```text) so all code fences (including the CLI pull/ingest/verify
blocks and similar examples) are labeled; ensure you update every occurrence
noted in the review (the large sample output blocks) so MD040 warnings are
resolved.

In `@testdata/rag/seed.sh`:
- Around line 4-5: The script defines OLLAMA_URL but later hard-codes
"http://ollama:11434" when calling Ollama; update those occurrences to use the
configured variable (e.g., replace the literal URL with "${OLLAMA_URL}" or
"$OLLAMA_URL") so all uses in seed.sh (including the section around the Ollama
calls referenced) honor the environment override; ensure quoting is preserved
when interpolating into curl/HTTP calls and remove any remaining hard-coded
"http://ollama:11434" strings.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Enterprise

Run ID: f9ca9251-a4ac-4011-97b7-25693859a77e

📥 Commits

Reviewing files that changed from the base of the PR and between 62b6d1c and 82ee461.

📒 Files selected for processing (14)
  • docs/dev/2026-05-15-rag-feature.md
  • internal/cmd/agentconfig.go
  • internal/cmd/serve.go
  • internal/ragsearch/ragsearch.go
  • internal/ragsearch/ragsearch_test.go
  • pkg/rag/config.go
  • pkg/rag/config_test.go
  • pkg/rag/rag.go
  • pkg/rag/weaviate.go
  • pkg/rag/weaviate_test.go
  • testdata/rag/README.md
  • testdata/rag/docker-compose.yaml
  • testdata/rag/seed.sh
  • testdata/standalone/agent-config.yaml

Comment thread docs/dev/2026-05-15-rag-feature.md Resolved
Comment thread docs/dev/2026-05-15-rag-feature.md Resolved
Comment thread internal/ragsearch/ragsearch.go Resolved
Comment thread pkg/rag/config.go Resolved
Comment thread pkg/rag/weaviate.go
Comment on lines +21 to +34
func NewWeaviateClient(baseURL, collection, textField string) (*WeaviateClient, error) {
baseURL = strings.TrimRight(baseURL, "/")
if baseURL == "" {
return nil, fmt.Errorf("weaviate: base URL is required")
}
if collection == "" {
return nil, fmt.Errorf("weaviate: collection is required")
}
return &WeaviateClient{
baseURL: baseURL,
collection: collection,
textField: textField,
httpClient: &http.Client{Timeout: 30 * time.Second},
}, nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Reject or default empty textField in constructor.

Line 32 accepts an empty textField, which later makes chunk extraction silently fail (obj[""]) and returns blank texts.

Proposed fix
 func NewWeaviateClient(baseURL, collection, textField string) (*WeaviateClient, error) {
 	baseURL = strings.TrimRight(baseURL, "/")
@@
 	if collection == "" {
 		return nil, fmt.Errorf("weaviate: collection is required")
 	}
+	if strings.TrimSpace(textField) == "" {
+		textField = "content"
+	}
 	return &WeaviateClient{
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/rag/weaviate.go` around lines 21 - 34, NewWeaviateClient currently allows
an empty textField which later causes silent failures when extracting chunks;
update NewWeaviateClient to validate textField and either return an error if
it's empty or assign a sensible default before constructing WeaviateClient.
Specifically, in NewWeaviateClient check the textField parameter (in addition to
baseURL and collection) and if empty either return fmt.Errorf("weaviate:
textField is required") or set textField = "<default_field_name>" (pick a
canonical field used elsewhere) before returning the &WeaviateClient{...};
ensure the unique symbol NewWeaviateClient and struct fields textField, baseURL,
collection are updated accordingly.

Comment thread pkg/rag/weaviate.go Resolved
Comment thread testdata/rag/README.md Outdated
Comment on lines +49 to +63
```
==> Pulling embedding model (first run only, ~274 MB)...
pulling manifest... pulling sha256:... success
==> Creating Docs collection...
Collection created.
==> Ingesting sample documents...
[1/8] ingested
...
==> Ingested 8 documents into Docs collection
==> Verifying search...
{
"data": { ... ranked results ... }
}
==> Done. Weaviate is ready for DocsClaw.
```

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Label fenced code blocks with a language to satisfy markdownlint.

At Line 49, Line 107, and Line 132, add fence languages (for example text) to clear MD040 warnings.

Also applies to: 107-119, 132-134

🧰 Tools
🪛 markdownlint-cli2 (0.22.1)

[warning] 49-49: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@testdata/rag/README.md` around lines 49 - 63, The fenced code blocks in the
README sample outputs are missing a language token which triggers markdownlint
MD040; update each triple-backtick fence for the example output blocks (the
large CLI/output snippets shown in the README) to include a language token such
as text (i.e. change ``` to ```text) so all code fences (including the CLI
pull/ingest/verify blocks and similar examples) are labeled; ensure you update
every occurrence noted in the review (the large sample output blocks) so MD040
warnings are resolved.

Comment thread testdata/rag/seed.sh
Comment on lines +4 to +5
WEAVIATE_URL="${WEAVIATE_URL:-http://localhost:8080}"
OLLAMA_URL="${OLLAMA_URL:-http://localhost:11434}"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Schema creation ignores configurable Ollama endpoint.

OLLAMA_URL is configurable, but Line 31 hard-codes http://ollama:11434. This can break seeding outside the default compose network.

Suggested fix
 WEAVIATE_URL="${WEAVIATE_URL:-http://localhost:8080}"
 OLLAMA_URL="${OLLAMA_URL:-http://localhost:11434}"
+WEAVIATE_OLLAMA_API_ENDPOINT="${WEAVIATE_OLLAMA_API_ENDPOINT:-http://ollama:11434}"

@@
-  -d '{
+  -d "{
     \"class\": \"Docs\",
     \"vectorizer\": \"text2vec-ollama\",
     \"moduleConfig\": {
       \"text2vec-ollama\": {
-        \"apiEndpoint\": \"http://ollama:11434\",
+        \"apiEndpoint\": \"${WEAVIATE_OLLAMA_API_ENDPOINT}\",
         \"model\": \"nomic-embed-text\"
       }
     },
@@
-  }')
+  }")

Also applies to: 29-33

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@testdata/rag/seed.sh` around lines 4 - 5, The script defines OLLAMA_URL but
later hard-codes "http://ollama:11434" when calling Ollama; update those
occurrences to use the configured variable (e.g., replace the literal URL with
"${OLLAMA_URL}" or "$OLLAMA_URL") so all uses in seed.sh (including the section
around the Ollama calls referenced) honor the environment override; ensure
quoting is preserved when interpolating into curl/HTTP calls and remove any
remaining hard-coded "http://ollama:11434" strings.

pavelanni added 2 commits May 15, 2026 20:35
- Trim whitespace-only queries in rag_search tool
- Add nil config guard in NewClient
- Skip chunks with missing distance instead of ranking as score=1
- Replace SDK code in design doc with HTTP/GraphQL implementation note
- Add text labels to unlabeled markdown code fences (MD040)

Signed-off-by: Pavel Anni <[email protected]>
@pavelanni
pavelanni merged commit 482adeb into main May 16, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant