Skip to main content
Glama

chat_completion

Generate AI responses using Grok models by providing conversation messages and parameters for customized chat interactions.

Instructions

Generate a response using Grok AI chat completion

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
max_tokensNoMaximum number of tokens to generate
messagesYesArray of message objects with role and content
modelNoGrok model to use (e.g., grok-2-latest, grok-3, grok-3-reasoner, grok-3-deepsearch, grok-3-mini-beta)grok-3-mini-beta
temperatureNoSampling temperature (0-2)

Implementation Reference

  • The primary handler function for the 'chat_completion' tool. It validates input arguments, prepares options, calls the Grok API client to generate a chat completion, and returns the formatted response.
    private async handleChatCompletion(args: any) {
      console.error('[Tool] Handling chat_completion tool call');
      
      const { messages, model, temperature, max_tokens, ...otherOptions } = args;
      
      // Validate messages
      if (!Array.isArray(messages) || messages.length === 0) {
        throw new Error('Messages must be a non-empty array');
      }
      
      // Create options object
      const options = {
        model: model || 'grok-2-latest',
        temperature: temperature !== undefined ? temperature : 1,
        max_tokens: max_tokens !== undefined ? max_tokens : 16384,
        ...otherOptions
      };
      
      // Call Grok API
      const response = await this.grokClient.createChatCompletion(messages, options);
      
      return {
        content: [
          {
            type: 'text',
            text: response.choices[0].message.content,
          },
        ],
      };
    }
  • src/index.ts:61-106 (registration)
    Tool registration in the ListToolsRequestHandler, defining the name, description, and input schema for 'chat_completion'.
    {
      name: 'chat_completion',
      description: 'Generate a response using Grok AI chat completion',
      inputSchema: {
        type: 'object',
        properties: {
          messages: {
            type: 'array',
            description: 'Array of message objects with role and content',
            items: {
              type: 'object',
              properties: {
                role: {
                  type: 'string',
                  description: 'Role of the message sender (system, user, assistant)',
                  enum: ['system', 'user', 'assistant']
                },
                content: {
                  type: 'string',
                  description: 'Content of the message'
                }
              },
              required: ['role', 'content']
            }
          },
          model: {
            type: 'string',
            description: 'Grok model to use (e.g., grok-2-latest, grok-3, grok-3-reasoner, grok-3-deepsearch, grok-3-mini-beta)',
            default: 'grok-3-mini-beta'
          },
          temperature: {
            type: 'number',
            description: 'Sampling temperature (0-2)',
            minimum: 0,
            maximum: 2,
            default: 1
          },
          max_tokens: {
            type: 'integer',
            description: 'Maximum number of tokens to generate',
            default: 16384
          }
        },
        required: ['messages']
      }
    },
  • Input schema definition for the 'chat_completion' tool, specifying the structure and types for messages, model, temperature, and max_tokens.
    inputSchema: {
      type: 'object',
      properties: {
        messages: {
          type: 'array',
          description: 'Array of message objects with role and content',
          items: {
            type: 'object',
            properties: {
              role: {
                type: 'string',
                description: 'Role of the message sender (system, user, assistant)',
                enum: ['system', 'user', 'assistant']
              },
              content: {
                type: 'string',
                description: 'Content of the message'
              }
            },
            required: ['role', 'content']
          }
        },
        model: {
          type: 'string',
          description: 'Grok model to use (e.g., grok-2-latest, grok-3, grok-3-reasoner, grok-3-deepsearch, grok-3-mini-beta)',
          default: 'grok-3-mini-beta'
        },
        temperature: {
          type: 'number',
          description: 'Sampling temperature (0-2)',
          minimum: 0,
          maximum: 2,
          default: 1
        },
        max_tokens: {
          type: 'integer',
          description: 'Maximum number of tokens to generate',
          default: 16384
        }
      },
      required: ['messages']
    }
  • Helper method in GrokApiClient that performs the actual HTTP POST request to the xAI API's /chat/completions endpoint, invoked by the handler.
    async createChatCompletion(messages: any[], options: any = {}): Promise<any> {
      try {
        console.error('[API] Creating chat completion...');
        
        const requestBody = {
          messages,
          model: options.model || 'grok-3-mini-beta',
          ...options
        };
        
        const response = await this.axiosInstance.post('/chat/completions', requestBody);
        return response.data;
      } catch (error) {
        console.error('[Error] Failed to create chat completion:', error);
        throw error;
      }
    }
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure but offers minimal information. It states what the tool does but doesn't describe rate limits, authentication requirements, response formats, error conditions, or any operational constraints. For a generative AI tool with significant behavioral implications, this is inadequate.

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?

The description is a single, efficient sentence that states the core purpose without unnecessary elaboration. It's appropriately sized for a tool with comprehensive schema documentation and gets straight to the point with zero wasted words.

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

Completeness2/5

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

For a generative AI tool with no annotations and no output schema, the description is insufficient. It doesn't explain what kind of response is generated, how to interpret results, error handling, or operational constraints. The agent lacks crucial context about this tool's behavior and outputs despite the comprehensive input schema.

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?

Schema description coverage is 100%, so the schema fully documents all 4 parameters. The description adds no parameter-specific information beyond what's already in the schema. According to scoring rules, when schema coverage is high (>80%), the baseline is 3 even with no param info in description.

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

Purpose4/5

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

The description clearly states the action ('Generate a response') and the resource/technology ('using Grok AI chat completion'), which is specific and unambiguous. However, it doesn't differentiate this tool from its sibling tools (function_calling, image_understanding) - all three appear to be different Grok AI capabilities, but the description doesn't explain how chat completion differs from function calling or image understanding.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus its siblings. There's no mention of appropriate contexts for chat completion versus function calling or image understanding, nor any prerequisites or constraints. The agent must infer usage from the tool name alone.

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/Bob-lance/grok-mcp'

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