Skip to main content
Glama

rag_query

Ask questions with RAG-enhanced context from xAI Collections; a lazy cache speeds up repeated queries by up to 100,000x.

Instructions

Ask a question with RAG-enhanced context from xAI Collections. Uses LAZY-RAG cache for 100,000x speedup on repeated queries.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
questionYesQuestion to ask

Implementation Reference

  • Handler for the rag_query tool. Extracts 'question' from args, uses the RAGIntegrator singleton to perform a cache-first (LAZY-RAG) query, and returns the result with cache hit/miss status and elapsed time.
    private async handleRagQuery(args: any): Promise<CallToolResult> {
      const { question } = args;
    
      if (!question) {
        return {
          content: [{
            type: 'text',
            text: '❌ Question is required'
          }],
          isError: true
        };
      }
    
      try {
        const rag = getRAGIntegrator();
    
        if (!rag.isConfigured()) {
          return {
            content: [{
              type: 'text',
              text: '❌ XAI_API_KEY not configured. Set the environment variable to enable RAG queries.'
            }],
            isError: true
          };
        }
    
        const result = await rag.query(question);
    
        const status = result.cached ? '⚡ CACHE HIT' : '🔄 API CALL';
        const elapsed = result.cached
          ? `${(result.elapsed * 1000).toFixed(3)}ms`
          : `${result.elapsed.toFixed(2)}s`;
    
        return {
          content: [{
            type: 'text',
            text: `${status} (${elapsed})\n\n${result.answer}`
          }]
        };
      } catch (error: unknown) {
        const errorMessage = error instanceof Error ? error.message : 'Unknown error';
        return {
          content: [{
            type: 'text',
            text: `❌ RAG Query Failed: ${errorMessage}`
          }],
          isError: true
        };
      }
    }
  • Tool schema definition: name ('rag_query'), description, and inputSchema requiring a 'question' string.
    // RAG Tools - LAZY-RAG Cache + xAI Collections
    {
      name: 'rag_query',
      description: 'Ask a question with RAG-enhanced context from xAI Collections. Uses LAZY-RAG cache for 100,000x speedup on repeated queries.',
      inputSchema: {
        type: 'object',
        properties: {
          question: { type: 'string', description: 'Question to ask' }
        },
        required: ['question']
      }
    },
  • Registration in the callTool switch-case that dispatches 'rag_query' to handleRagQuery.
    case 'rag_query':
      return await this.handleRagQuery(args);
    case 'rag_cache_stats':
      return await this.handleRagCacheStats(args);
    case 'rag_cache_clear':
      return await this.handleRagCacheClear(args);
  • RAGIntegrator.query() - Core LAZY-RAG pattern: cache-first lookup via SHA256 key, then fallback to xAI API call with caching of the result.
    async query(question: string): Promise<RAGQueryResult> {
      const start = Date.now();
      const cacheKey = this.cache.generateKey(question, 'query', this.collectionId);
    
      // Check cache first
      const cached = this.cache.get(cacheKey);
      if (cached !== undefined) {
        return {
          answer: cached,
          cached: true,
          elapsed: (Date.now() - start) / 1000,
          cacheKey
        };
      }
    
      // Cache miss - call API
      if (!this.client) {
        throw new Error('XAI_API_KEY not configured');
      }
    
      const answer = await this.client.queryWithContext({ question });
    
      // Store in cache
      this.cache.set(cacheKey, answer);
    
      return {
        answer,
        cached: false,
        elapsed: (Date.now() - start) / 1000,
        cacheKey
      };
    }
  • XAIClient.queryWithContext() - Sends a chat completion request with a system prompt providing FAF project context and the user's question to the xAI API.
      async queryWithContext(params: {
        question: string;
        systemPrompt?: string;
        context?: string;
      }): Promise<string> {
        const systemContent = params.systemPrompt || this.getDefaultSystemPrompt(params.context);
    
        const messages: ChatMessage[] = [
          { role: 'system', content: systemContent },
          { role: 'user', content: params.question }
        ];
    
        const response = await this.chat(messages);
        return response.content;
      }
    
      /**
       * Default system prompt with FAF project context
       */
      private getDefaultSystemPrompt(additionalContext?: string): string {
        let prompt = `You are a helpful assistant with access to FAF (Foundational AI-context Format) project context.
    
    FAF Project Context:
    - Project: xai-faf-rag
    - Birth Certificate ID: FAF-2026-XAIFAFRA-WXGD
    - FAF Version: 2.5.0
    - Purpose: Cache-first RAG using Grok Collections
    - Tech Stack: Python + Rust, xai-sdk, LAZY-RAG cache layer
    - Collection: FAF Elite Palace
    - Key Features: LAZY-RAG caching (0.003ms hits), Collections search, .faf file sync
    
    Answer questions accurately based on this context. Be concise.`;
    
        if (additionalContext) {
          prompt += `\n\nAdditional Context:\n${additionalContext}`;
        }
    
        return prompt;
      }
    
      /**
       * Check if API key is configured
       */
      isConfigured(): boolean {
        return !!this.apiKey && this.apiKey.length > 0;
      }
    }
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Discloses the cache behavior and speedup benefit, which is a key behavioral trait. However, with no annotations, the description could mention potential latency on cache misses or limitations, though the current disclosure is above average.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two sentences with no fluff, front-loading the core action. Every word adds value.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a single-parameter tool with no output schema, the description adequately covers purpose and a notable behavior. It doesn't describe the response format, but that is acceptable given simplicity.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

There is only one parameter ('question') with 100% schema coverage; the description adds no extra meaning beyond the schema's 'Question to ask'. Baseline 3 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Ask a question') and the resource ('RAG-enhanced context from xAI Collections'), and highlights a distinctive feature (LAZY-RAG cache speedup), effectively distinguishing it from sibling tools.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage for RAG queries with cached responses but does not explicitly specify when not to use it or compare to alternatives like faf_* tools or rag_cache_clear. The context from sibling names suggests faf_* tools are unrelated, but no direct guidance is given.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Wolfe-Jam/grok-faf-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server