Mastering OpenCode: A Terminal-Based AI Assistant for Python Development

Overview

OpenCode is an open-source, terminal-native AI coding agent designed to help Python developers analyze, refactor, and understand their projects through natural language conversation. Unlike many chat-based coding tools, OpenCode operates directly in your command line, giving you full project context awareness and deliberate, instruction-driven assistance. It supports over 75 AI providers, including Anthropic, OpenAI, and Google Gemini, making it flexible for different workflows.

Mastering OpenCode: A Terminal-Based AI Assistant for Python Development
Source: realpython.com

In this detailed tutorial, you'll install OpenCode, configure it with a free Google Gemini API key, and learn to use it for practical Python tasks. You'll work with a sample dice-rolling script, refactor it, and explore common pitfalls to avoid. By the end, you'll be able to integrate OpenCode into your daily development routine for efficient, context-aware code improvements.

Prerequisites

Before you begin, ensure your system meets these requirements:

  • Python 3.11 or higher – The sample project requires this version.
  • A modern terminal emulator – Supports features like color output and cursor movement (e.g., iTerm2, Windows Terminal, GNOME Terminal).
  • An AI provider account – This guide uses Google AI Studio's free tier to obtain a Gemini API key. You may also use paid providers like Anthropic (Claude) or OpenAI (GPT) if you have subscriptions.
  • Basic Python knowledge – Understanding of functions, modules, and refactoring concepts.
  • Terminal familiarity – Comfort with command-line navigation and running scripts.

Additionally, download the sample project files from the link below:

Download the sample code (ZIP includes original dice_roller.py and the final refactored version for comparison).

Step-by-Step Instructions

1. Install and Set Up OpenCode

OpenCode's official installation script automates the setup. Run the following command in your terminal:

curl -fsSL https://opencode.ai/install.sh | sh

This script downloads OpenCode and adds it to your PATH. After installation, launch OpenCode by typing:

opencode

You'll see the welcome screen with a prompt awaiting your first query. To connect to an AI provider, you need to configure an API key. For Google Gemini, go to Google AI Studio, sign in, and click Create API Key. Copy the key.

Now, configure OpenCode to use Gemini:

opencode config set provider gemini
opencode config set api_key YOUR_GEMINI_KEY

Replace YOUR_GEMINI_KEY with your actual key. To verify the setup, ask a simple question like:

What is the current Python version?

OpenCode should respond with the version installed on your system, confirming the connection.

2. Prepare the Sample Project

Create a directory for your project and navigate into it:

mkdir dice_project
cd dice_project

Create a file named dice_roller.py with the following starter code:

import random

def roll_dice(num_dice=1, sides=6):
    """Roll a specified number of dice with given sides."""
    return [random.randint(1, sides) for _ in range(num_dice)]

def calculate_total(results):
    """Sum the results of dice rolls."""
    return sum(results)

def display_results(results):
    """Print each die's value and the total."""
    for i, value in enumerate(results, start=1):
        print(f"Die {i}: {value}")
    print(f"Total: {calculate_total(results)}")

if __name__ == "__main__":
    rolls = roll_dice(3, 6)
    display_results(rolls)

This simple script rolls three six-sided dice and prints the results. Now, start OpenCode in this directory:

opencode

OpenCode automatically scans the project and understands its file structure.

3. Analyze Existing Code with OpenCode

Ask OpenCode to review your code. Type the following:

Analyze the functions in dice_roller.py and identify any potential improvements.

OpenCode will output a detailed analysis, noting that the calculate_total function could be inlined, and that the script lacks error handling for invalid inputs. Take note of these suggestions for the next step.

4. Refactor the Code

Based on the analysis, you can ask OpenCode to refactor the script. For example:

Mastering OpenCode: A Terminal-Based AI Assistant for Python Development
Source: realpython.com
Refactor dice_roller.py to remove the separate calculate_total function, add error handling for non-integer sides, and allow custom number of dice via command-line arguments.

OpenCode will generate a new version of the file. You can apply the changes automatically by using:

Apply the changes to dice_roller.py

The tool modifies the file in place. After refactoring, your dice_roller.py might look like:

import random
import sys

def roll_dice(num_dice=1, sides=6):
    if not isinstance(sides, int) or sides < 1:
        raise ValueError("Sides must be a positive integer.")
    return [random.randint(1, sides) for _ in range(num_dice)]

def display_results(results):
    total = sum(results)
    for i, value in enumerate(results, start=1):
        print(f"Die {i}: {value}")
    print(f"Total: {total}")

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("-n", "--num", type=int, default=3, help="Number of dice")
    parser.add_argument("-s", "--sides", type=int, default=6, help="Number of sides")
    args = parser.parse_args()
    rolls = roll_dice(args.num, args.sides)
    display_results(rolls)

5. Customize OpenCode with AGENTS.md

OpenCode respects a project-level configuration file named AGENTS.md. Create this file in your project root to set custom instructions. For example:

# AGENTS.md
- Always use type hints in generated code.
- Prefer list comprehensions over for loops when simple.
- Use f-strings for string formatting.

Now ask OpenCode to generate a new function, like roll_multiple_sets, and it will follow these guidelines automatically.

Common Mistakes

  • Not launching OpenCode in the project root – OpenCode's context awareness depends on scanning the current directory. If you start it from a parent folder, it may miss internal modules.
  • Using ambiguous queries – Be specific. Instead of "fix my code," say "Add input validation for the sides parameter." Vague requests yield generic results.
  • Ignoring the API key expiration – Free Gemini keys have time limits. Check your AI Studio dashboard periodically and regenerate the key if OpenCode stops responding.
  • Over-relying on auto-apply – Always review changes before applying. OpenCode can occasionally misinterpret context and introduce bugs.
  • Forgetting to update AGENTS.md – Custom rules only apply to new requests. Ask OpenCode to "re-evaluate AGENTS.md" after editing the file to refresh its behavior.

Summary

OpenCode brings powerful AI assistance directly to your terminal, enabling context-aware code analysis and refactoring for Python projects. By following this guide, you installed OpenCode, configured it with Google Gemini, analyzed and refactored a dice-rolling script, and learned how to customize its behavior with an AGENTS.md file. With practice, you can integrate OpenCode into your workflow to speed up debugging, enhance code quality, and learn new patterns—all without leaving the command line.

Tags:

Recommended

Discover More

5 Key Insights into Star Wars Battlefront 2's Remarkable Comeback and the Resurgence Day Phenomenon10 Simple Steps to Unlock Claude Code for Free — and Supercharge It with ObsidianCritical Linux Kernel Flaw 'Fragnesia' Opens Door to Full System TakeoverAutomating AI Kernel Optimization: A Step-by-Step Guide to Meta's KernelEvolve SystemBuilding macOS Apps from Scratch: The Complete Beginner’s Guide