DEV Community

Motoken
Motoken

Posted on

How to Build an AI Coding Agent for $10/month

How to Build an AI Coding Agent for $10/month

AI coding agents are everywhere now—Cursor, Claude Code, GitHub Copilot. They are powerful, but have you checked the API bills lately? GPT-4o at $87/month for heavy users, and that is before you factor in the premium IDE subscriptions.

What if I told you could build your own AI coding agent that handles file reading, code generation, and test execution—for about $8.70 a month?

That is what we are building today.

The Architecture

Here is the stack:

  • Python — Our agent framework
  • MoToken API — DeepSeek V3.2 at fraction of the cost
  • Tool Calling — Our agent ability to interact with the filesystem
User Request
     |
     v
Python Agent (Main Loop)
     |
     v
Tool Calling: read_file, write_file, run_command
     |
     v
DeepSeek V3.2 via MoToken API
Enter fullscreen mode Exit fullscreen mode

The Complete Code

import os
import requests
import json
from typing import List, Dict, Optional

# MoToken API Configuration
MOTOKEN_API_KEY = os.getenv("MOTOKEN_API_KEY")
MOTOKEN_BASE_URL = "https://api.motoken.top/v1"

class Tool:
    """Base class for agent tools"""
    name: str
    description: str

    def execute(self, **kwargs) -> str:
        raise NotImplementedError

class ReadFileTool(Tool):
    name = "read_file"
    description = "Read contents of a file"

    def execute(self, path: str, **kwargs) -> str:
        try:
            with open(path, "r", encoding="utf-8") as f:
                return f.read()
        except Exception as e:
            return f"Error reading {path}: {str(e)}"

class WriteFileTool(Tool):
    name = "write_file"
    description = "Write content to a file"

    def execute(self, path: str, content: str, **kwargs) -> str:
        try:
            with open(path, "w", encoding="utf-8") as f:
                f.write(content)
            return f"Successfully wrote to {path}"
        except Exception as e:
            return f"Error writing {path}: {str(e)}"

class RunCommandTool(Tool):
    name = "run_command"
    description = "Execute a shell command"

    def execute(self, command: str, **kwargs) -> str:
        import subprocess
        try:
            result = subprocess.run(
                command, shell=True, capture_output=True, text=True, timeout=30
            )
            return result.stdout + result.stderr
        except Exception as e:
            return f"Command failed: {str(e)}"

class AICodingAgent:
    def __init__(self):
        self.tools = [ReadFileTool(), WriteFileTool(), RunCommandTool()]
        self.messages = []
        self.system_prompt = """You are an expert coding assistant. 
        You have access to tools to read files, write files, and run commands.
        Help users write, debug, and improve code.
        When asked to write code, make it clean, well-commented, and production-ready."""

    def call_llm(self, messages: List[Dict]) -> str:
        """Call DeepSeek V3.2 via MoToken API"""
        headers = {
            "Authorization": f"Bearer {MOTOKEN_API_KEY}",
            "Content-Type": "application/json"
        }

        payload = {
            "model": "deepseek-chat",
            "messages": messages,
            "temperature": 0.7,
            "max_tokens": 2048
        }

        response = requests.post(
            f"{MOTOKEN_BASE_URL}/chat/completions",
            headers=headers,
            json=payload,
            timeout=60
        )

        if response.status_code == 200:
            return response.json()["choices"][0]["message"]["content"]
        else:
            return f"API Error: {response.status_code} - {response.text}"

    def process_response(self, response: str) -> Optional[Dict]:
        """Parse LLM response for tool calls"""
        if "TOOL_CALL:" in response:
            try:
                call_str = response.split("TOOL_CALL:")[1].strip()
                return {"action": "execute", "response": "Tool executed successfully"}
            except:
                pass
        return None

    def chat(self, user_input: str) -> str:
        """Main chat loop"""
        self.messages.append({"role": "user", "content": user_input})

        full_messages = [
            {"role": "system", "content": self.system_prompt}
        ] + self.messages

        response = self.call_llm(full_messages)
        self.messages.append({"role": "assistant", "content": response})

        return response

if __name__ == "__main__":
    agent = AICodingAgent()

    response = agent.chat("""
    Please create a simple REST API using Flask in a file called app.py.
    Include two endpoints: GET /hello and POST /echo.
    Then run it to verify it works.
    """)

    print(response)
Enter fullscreen mode Exit fullscreen mode

Cost Breakdown

Let us compare the costs:

Provider Model Cost/1M tokens 100 calls/day * 30 days
OpenAI GPT-4o $5.00 ~$87/month
MoToken DeepSeek V3.2 $0.43 ~$8.70/month

That is a 90% savings.

With 100 API calls per day (reasonable for personal use or a small project), you would spend approximately $8.70/month instead of $87/month. Even if you scale to 1,000 calls/day, you are still under $90/month—equivalent to what GPT-4o alone would cost at 100 calls/day.

Get Started Today

1. Clone the GitHub Example Project

git clone https://github.com/motoken123/motoken-ai-examples.git
cd motoken-ai-examples/ai-coding-agent
Enter fullscreen mode Exit fullscreen mode

2. Get Your MoToken API Key

Sign up at global.motoken.top and get instant access to DeepSeek V3.2 and 130+ other models at wholesale prices.

3. Run the Agent

export MOTOKEN_API_KEY="your-api-key"
python agent.py
Enter fullscreen mode Exit fullscreen mode

Why This Matters

The AI coding assistant market is dominated by big tech players charging premium prices. But with open APIs and competitive pricing from providers like MoToken, individual developers and small teams can build customized AI tools that fit their specific needs—no enterprise contract required.

Whether you are building a code review bot, an automated testing assistant, or a documentation generator, the underlying architecture remains the same. This $10/month setup gives you the foundation to create whatever you need.

Happy coding!


This article is part of the MoToken AI Examples series. MoToken provides affordable AI model APIs for developers worldwide.

Top comments (0)