Skip to main content

Overview

OpenCode is a fully open-source AI coding agent built with TypeScript and AI SDK, offering terminal TUI, IDE integration, and desktop applications. The project has 94.9k+ stars on GitHub with an active community. By configuring API易 service, you can get:

🖥️ Multi-Platform Support

Terminal TUI, VS Code extension, and desktop apps

🔌 75+ Model Support

Supports 75+ LLM providers via Models.dev

🛠️ Built-in LSP

Language Server Protocol support for intelligent code understanding

🔄 Multi-Session Parallel

Parallel session processing and session sharing
Project Info: OpenCode is an actively maintained open-source project. Website: opencode.ai, Repository: github.com/anomalyco/opencode.

Prerequisites

Install OpenCode

Verify installation:
opencode --version

Quick Configuration

OpenCode uses JSON configuration files with multiple config locations (priority from low to high):
  1. Remote config (.well-known/opencode)
  2. Global config: ~/.config/opencode/opencode.json
  3. Custom config: path specified by OPENCODE_CONFIG environment variable
  4. Project config: opencode.json in project root
  5. .opencode directory config
  6. Inline config: OPENCODE_CONFIG_CONTENT environment variable
Create or edit the config file ~/.config/opencode/opencode.json:
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "apiyi": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "API易",
      "options": {
        "baseURL": "https://api.apiyi.com/v1",
        "apiKey": "{env:APIYI_API_KEY}"
      },
      "models": {
        "claude-sonnet-4-20250514": {
          "name": "Claude Sonnet 4",
          "limit": { "context": 200000, "output": 8192 }
        },
        "gpt-4.1": {
          "name": "GPT-4.1",
          "limit": { "context": 1047576, "output": 32768 }
        },
        "deepseek-chat": {
          "name": "DeepSeek V3",
          "limit": { "context": 65536, "output": 8192 }
        },
        "gemini-2.5-pro-preview-05-06": {
          "name": "Gemini 2.5 Pro",
          "limit": { "context": 1048576, "output": 65536 }
        }
      }
    }
  },
  "model": "apiyi/claude-sonnet-4-20250514"
}
Then set the environment variable:
# zsh
echo 'export APIYI_API_KEY="sk-your-apiyi-key"' >> ~/.zshrc
source ~/.zshrc

# bash
echo 'export APIYI_API_KEY="sk-your-apiyi-key"' >> ~/.bashrc
source ~/.bashrc

Method 2: /connect Command Authentication

OpenCode provides the /connect command to quickly connect new providers:
  1. After starting OpenCode, type /connect
  2. Select “Other”
  3. Enter provider ID (e.g., apiyi)
  4. Enter API key
Then add the provider and models definition in the config file to use.

Method 3: Override Existing Provider

For quick setup, override the built-in OpenAI provider’s baseURL:
{
  "provider": {
    "openai": {
      "options": {
        "baseURL": "https://api.apiyi.com/v1",
        "apiKey": "{env:APIYI_API_KEY}"
      }
    }
  }
}

Method 4: Project-Level Configuration

Create opencode.json in your project root for project-specific settings:
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "apiyi": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "API易",
      "options": {
        "baseURL": "https://api.apiyi.com/v1",
        "apiKey": "{env:APIYI_API_KEY}"
      },
      "models": {
        "claude-sonnet-4-20250514": {
          "name": "Claude Sonnet 4",
          "limit": { "context": 200000, "output": 8192 }
        }
      }
    }
  },
  "model": "apiyi/claude-sonnet-4-20250514"
}

Agent System

OpenCode has three built-in agents, each with specific purposes:
AgentDescriptionUsage
buildDefault agent with full access, handles code generation and modificationDirect conversation
planRead-only agent for code analysis and planning, won’t modify files/plan command
generalComplex search sub-agent for multi-step information retrieval@general invocation

Agent Model Configuration

Configure different models for different agents:
{
  "provider": {
    "apiyi": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "API易",
      "options": {
        "baseURL": "https://api.apiyi.com/v1",
        "apiKey": "{env:APIYI_API_KEY}"
      },
      "models": {
        "claude-sonnet-4-20250514": {
          "name": "Claude Sonnet 4",
          "limit": { "context": 200000, "output": 8192 }
        },
        "deepseek-chat": {
          "name": "DeepSeek V3",
          "limit": { "context": 65536, "output": 8192 }
        },
        "gpt-4.1-mini": {
          "name": "GPT-4.1 Mini",
          "limit": { "context": 1047576, "output": 32768 }
        }
      }
    }
  },
  "agents": {
    "build": {
      "model": "apiyi/claude-sonnet-4-20250514"
    },
    "plan": {
      "model": "apiyi/deepseek-chat"
    },
    "general": {
      "model": "apiyi/gpt-4.1-mini"
    }
  }
}
OpenCode supports 200+ AI models through API易. Choose the right model for different tasks.

View Programming Model Recommendations

Check the latest programming model recommendations, performance comparisons, and usage suggestions. Includes top-tier models, cost-effective options, and reasoning-enhanced models.

Scenario-Based Model Recommendations

AgentPurposeRecommended Model
buildCode generation and modificationClaude Sonnet 4, GPT-4.1
planTask planning and analysisDeepSeek V3, Gemini 2.5 Pro
generalQuick search and Q&AGPT-4.1 Mini (low cost)

Core Features

Terminal Interactive Interface

Start OpenCode to enter the interactive TUI:
# Start in current directory
opencode

# Specify project directory
opencode /path/to/project

File Operations

OpenCode can read, search, and modify project files:
> View the contents of src/index.ts

> Search for all files containing "TODO" in the project

> Refactor the calculateSum function in utils.ts to a more efficient implementation

Command Execution

Execute commands in the terminal and view results:
> Run npm test and analyze the failed tests

> Execute npm install and check for dependency conflicts

Session Management

  • Multi-session parallel: Run multiple sessions simultaneously
  • Session sharing: Export and share sessions
  • Auto-save: All sessions are automatically persisted
  • Context retention: Maintain complete conversation context during sessions

Usage Tips

1. Keyboard Shortcuts

ShortcutFunction
Ctrl+CInterrupt current operation
Ctrl+DExit OpenCode
TabAuto-complete
↑/↓Browse command history

2. Common Commands

CommandFunction
/connectConnect new Provider
/modelSwitch current model
/planUse plan agent for analysis
/clearClear current session
/helpView help information

3. Invoke Sub-Agent

Use @general to invoke the search sub-agent for complex queries:
> @general Find all files handling user authentication in the codebase and summarize their functions

4. Incremental Development

{/* Step 1: Generate basic framework */}
> Create a basic REST API structure

{/* Step 2: Add specific features */}
> Add user authentication middleware

{/* Step 3: Refine details */}
> Add request parameter validation and error handling

Troubleshooting

  1. Check if environment variable is set correctly:
echo $APIYI_API_KEY  # macOS/Linux
echo %APIYI_API_KEY%  # Windows
  1. Verify baseURL in configuration file:
"baseURL": "https://api.apiyi.com/v1"
  1. Test API connectivity:
curl -H "Authorization: Bearer $APIYI_API_KEY" \
     https://api.apiyi.com/v1/models
Verify the model ID is correct. Check the API易 console for supported models.Common model IDs:
  • claude-sonnet-4-20250514
  • gpt-4.1
  • deepseek-chat
  • gemini-2.5-pro-preview-05-06
Configuration file loading priority (from low to high):
  1. Remote config (.well-known/opencode)
  2. Global config: ~/.config/opencode/opencode.json
  3. OPENCODE_CONFIG environment variable
  4. Project config: opencode.json
  5. .opencode directory config
  6. OPENCODE_CONFIG_CONTENT environment variable
Ensure the config file is in the correct location with valid JSON format.
  1. Try using a lighter model (e.g., GPT-4.1 Mini)
  2. Reduce context length, start a new session
  3. Check network connection stability

Best Practices

1. Model Selection Strategy

Task TypeRecommended ModelReason
Complex code generationClaude Sonnet 4Strong coding ability, good context understanding
Code reviewGPT-4.1Strong analytical ability, good attention to detail
Quick Q&ADeepSeek V3Fast response, cost-effective
Long document analysisGemini 2.5 ProSupports ultra-long context

2. Effective Prompts

❌ Poor prompt: Help me write code

✅ Good prompt: Write an HTTP middleware in TypeScript that
logs requests, including request method, path,
response time, and status code, using pino for output

3. Security Considerations

  • Don’t hardcode API keys in code
  • Use environment variables to manage sensitive information
  • Review AI-generated code, especially security-related parts
  • Be careful not to let AI execute dangerous system commands

4. Cost Control

  • Configure different models for different agents (strong models for build, lightweight for general)
  • Use lightweight models for simple tasks
  • Regularly check API易 console to monitor usage

Alternatives

If OpenCode doesn’t meet your needs, consider these tools:

Claude Code

Anthropic’s official terminal programming assistant

Codex CLI

OpenAI’s official command-line tool

Gemini CLI

Google’s official terminal programming assistant

Roo Code

VS Code AI programming extension

API易 Console

Manage API keys and view usage

Model Recommendations

View programming scenario model recommendations