Skip to content

JChan2787/xai-grok-python-cli-bot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

xAI Grok Python CLI Bot

A production-ready, interactive command-line chatbot powered by xAI's Grok models with autonomous research capabilities, image analysis, and persistent conversation history.

Features

🧠 Autonomous Agentic Capabilities

  • Web Search: Real-time internet search for current information
  • X (Twitter) Search: Access trending topics and social media discussions
  • Code Execution: Run Python code for calculations and data analysis

πŸ–ΌοΈ Vision API Integration

  • Analyze images with detailed descriptions
  • Automatic image preprocessing to stay under gRPC message size limits
  • Support for JPG/JPEG and PNG formats

πŸ’Ύ Persistent Conversation Management

  • JSONL-based storage (one message per line)
  • Resume previous conversations
  • No Assumed State principle - deterministic rebuilds from ground truth

πŸ”„ Multiple Model Support

  • grok-4 - Higher quality, slower
  • grok-4-fast - Recommended for agentic workflows
  • grok-4-fast-non-reasoning - Fastest, no reasoning tokens

πŸ“Š Real-time Observability

  • Live tool call visibility
  • Token usage tracking (prompt, completion, reasoning, image tokens)
  • Citations display

Installation

###1. Clone the repository

git clone https://github.com/yourusername/xai-grok-python-cli-bot
cd xai-grok-python-cli-bot

2. Install dependencies

pip install -r requirements.txt

3. Set up environment variables

Copy the example environment file and add your xAI API key:

cp .env.example .env

Edit .env and add your API key:

XAI_API_KEY=your_xai_api_key_here

Get your API key from: https://console.x.ai/

4. Run the bot

python grok_chat.py

Usage

Basic Commands

# Start with default settings
python grok_chat.py

# Use a specific model
python grok_chat.py --model grok-4

# Resume a previous conversation
python grok_chat.py --resume ca6ae2b8

# Use a custom persona
python grok_chat.py --persona personas/custom_persona.md

# Combine options
python grok_chat.py -m grok-4 -r ca6ae2b8

Runtime Commands

While chatting, you can use these commands:

  • /model - Show current model
  • /model grok-4 - Switch to a different model
  • /list - Show all saved conversations
  • /resume <id> - Resume a specific conversation
  • /new - Start a new conversation
  • image:<path> - Analyze an image
  • exit, quit, bye - End session

Example Session

You: What are the latest developments in AI?
[πŸ”§ Calling: web_search]
Assistant: Based on recent search results, here are the latest AI developments...

You: image:/path/to/image.jpg
βœ“ Image loaded: image.jpg (2345.6 KB)
What should I do with this image? Analyze this image in detail
Assistant: This image shows...

You: /list
Found 3 conversation(s):
  4a3d8c91 - 2025-11-08 12:34:56 - 8 messages
  ca6ae2b8 - 2025-11-09 02:39:35 - 12 messages (current)
  e7f2a1b9 - 2025-11-09 03:15:22 - 5 messages

Architecture

No Assumed State Principle

This bot follows the "No Ass" (No Assumed State) principle:

  1. Ground Truth: JSONL file is the single source of truth
  2. Fresh API Calls: Create a new chat object on every turn
  3. Deterministic Rebuilds: Conversation history rebuilt from disk each time
  4. No Persistent SDK State: Prevents tool result pollution and state accumulation bugs

JSONL Storage Format

Each message is stored as a single JSON line:

{
  "id": "uuid",
  "role": "user|assistant",
  "timestamp": "ISO8601",
  "content": "message text",
  "input_tokens": 0,
  "output_tokens": 0,
  "image": {"image_url": "data:...", "detail": "high"}  // optional
}

Directory Structure

conversations/
└── [8-char-uuid]/
    β”œβ”€β”€ messages.jsonl      # Ground truth conversation log
    └── metadata.json       # Conversation metadata

Image Handling

Images are automatically preprocessed to stay under xAI's gRPC 4 MB message size limit:

  • Target: 2 MB max encoded size (~1.5 MB binary)
  • Automatic resizing with high-quality LANCZOS resampling
  • Iterative compression (quality 95 β†’ 85 β†’ 75 β†’ 65)
  • RGBA β†’ RGB conversion with white background
  • Only the most recent image is included in message history to prevent exponential growth

Customization

Creating Custom Personas

Create a markdown file in personas/ directory:

# My Custom Persona

You are a [description]...

## Capabilities
- [capability 1]
- [capability 2]

## Response Style
- [guideline 1]
- [guideline 2]

Use it with:

python grok_chat.py --persona personas/my_custom_persona.md

Configuration Options

Edit the GrokChat class initialization in grok_chat.py:

self.max_history = 50  # Number of messages to keep in context window

Troubleshooting

Image Size Errors

If you get "message larger than max" errors:

  • Images are automatically resized, but extremely large files may still fail
  • Try using a smaller source image
  • Check that image format is JPG/JPEG or PNG

API Key Issues

Error: XAI_API_KEY not found in .env file

Make sure:

  1. .env file exists in the project root
  2. File contains XAI_API_KEY=your_key_here
  3. No quotes around the key value

Missing Dependencies

Error: xAI SDK not found or outdated

Install requirements:

pip install -r requirements.txt

Known Limitations

  1. Context Window Management: No automatic overflow handling beyond max_history limit
  2. Image History: Previous images are not re-sent in conversation history (only text context retained)
  3. Model Persistence: Model changes don't persist across script restarts

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

MIT License - see LICENSE file for details

Acknowledgments

  • Built with xAI SDK
  • Image processing with Pillow
  • Architecture inspired by the "No Assumed State" principle

Support


Note: This is an unofficial community project. For official xAI support, visit https://x.ai/

About

Interactive CLI chatbot powered by xAI Grok with autonomous web search, X search, vision analysis, and persistent conversation history. Features JSONL-based storage and multi-model support.

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages