59API

← 返回教程列表

Build a GPT and Claude CLI with 59API

入门教程 · EN · 2026-09-26

Build a Multi-Model AI CLI from Scratch

A command-line AI assistant is useful when it fits existing developer workflows: summarizing logs, drafting release notes, explaining failing tests, or reviewing a diff without leaving the terminal. This walkthrough builds a Node.js CLI that lets users choose GPT or Claude with one flag, while using a single API integration through 59API.

59API is a practical choice when you want official-quality GPT and Claude-family models without maintaining separate provider accounts and billing paths. Its relay supports the OpenAI SDK and uses the base URL https://api.59api.com, so the application code remains familiar. It also provides pay-as-you-go pricing, access to Claude Opus, Sonnet, Haiku, and Fable models alongside GPT models, and a referral rebate for developers who share the service.

1. Create the Project and Install Dependencies

Start with Node.js 20 or later. Create a project directory, run npm init -y, and install openai and commander. The OpenAI package provides the request client, while Commander handles predictable command-line flags. Add a bin entry in package.json that points to cli.js, then run npm link during local development so the command is available globally.

Create an API key in your 59API account and export it in your shell as API_59API_KEY. Do not place credentials in source code or commit them to a repository. For local convenience, use a .env file ignored by Git and load it with dotenv if your team already uses that pattern.

2. Implement the CLI Interface

Your command should accept a required prompt plus optional model and system-instruction flags. A clear interface is: aiask "explain this stack trace" --model claude-sonnet. Add --system for a reusable role instruction, --temperature for creativity, and --json for automation-friendly output. Set a sensible default model, such as a fast GPT or Claude Haiku option, so simple requests do not require extra typing.

In cli.js, initialize the SDK with an API key read from process.env.API_59API_KEY and set baseURL to https://api.59api.com. Build a messages array containing the optional system message followed by the user prompt. Send that array through the SDK chat-completions method using the selected model. Print only the assistant text on success; scripts and shell pipelines depend on clean standard output.

3. Add Model Selection That Has a Purpose

Do not treat model choice as a cosmetic toggle. Use lower-cost, faster models for frequent tasks such as formatting text, generating commit messages, and extracting fields from logs. Reserve more capable GPT or Claude Opus/Sonnet models for architecture analysis, difficult debugging, long-context repository questions, and nuanced writing. Centralize aliases such as fast, balanced, and powerful, then map them to the current 59API model IDs in one file. This prevents scattered model strings and makes pricing or model updates straightforward.

A useful enhancement is a --task flag. For example, --task review can select a reasoning-focused model and add a system instruction that requires concrete findings, severity, and suggested fixes. Meanwhile, --task summarize can select an economical model with a short, structured answer format. Users get an ergonomic command, while the CLI makes cost-aware decisions consistently.

4. Make It Reliable in Production

Wrap the request in retry logic for transient failures such as rate limits, gateway timeouts, and temporary network errors. Retry only retryable status codes, use exponential backoff with jitter, and cap attempts at three. Never retry authentication failures or malformed requests. Set a request timeout with AbortController so a stalled connection cannot block a CI job indefinitely.

For long answers, enable streaming if the selected API path supports it and write chunks immediately to standard output. Streaming improves terminal feedback and reduces the appearance of latency. Keep the non-streaming path for --json mode, where consumers need one valid JSON document rather than partial tokens.

Protect privacy by avoiding automatic prompt logging. If debugging is needed, add an explicit --debug option that records request metadata such as model, duration, status code, and token usage, but not source code or user content by default. In CI, inject API_59API_KEY through the platform secret manager and set usage limits appropriate for the repository.

5. Test and Ship the Tool

Unit-test argument parsing, model aliases, request construction, and error-to-exit-code behavior by mocking the SDK client. Add an integration test behind an opt-in environment variable so normal test runs never spend API credit. Test at least one GPT request, one Claude request, an invalid model, a missing key, and a timeout path.

Before publishing, document installation, environment variables, supported aliases, examples, and exit codes in the README. Version the package semantically and publish it to npm when the command is stable. To keep a multi-model CLI affordable as usage grows, sign up for 59API and route requests through its compatible API endpoint while choosing the smallest model that reliably completes each task.

价格 · 接入文档

准备好开始了吗?

几分钟接入 Claude 与 GPT,全网超低价,原生不降智。立即注册即可领取 API 密钥。

免费注册