AIFeed

在终端里加入 AI 会发生什么?一次个人实验

Translation(model translation, not the source's own text)

在终端里加入 AI 会发生什么?一次个人实验¶

一个简单的想法¶

我想试着给一个 CLI 工具加上 AI,看看这件事有多容易。想法很简单:不用去查命令语法,直接用大白话问终端就行。

动手实现¶

下面是使用 OpenAI API 的基本实现,后来它被移植到了 pulp-cli:


        import json
import click
import requests

@click.command()
@click.argument("question", type=str)
@click.option("--api-key", envvar="OPENAI_API_KEY", help="OpenAI API key")
@click.option("--model", default="gpt-3.5-turbo", help="ChatGPT model to use")
def ask(question, api_key, model):
    """Ask a question to ChatGPT and get a response."""

if not api_key:
        raise click.ClickException("OpenAI API key is required")

url = "https://api.openai.com/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    }

payload = {
        "model": model,
        "messages": [
            {"role": "user", "content": question}
        ],
        "max_tokens": 150,
        "temperature": 0.7,
    }

try:
        response = requests.post(url, headers=headers, json=payload, timeout=30)
        response.raise_for_status()

result = response.json()
        answer = result["choices"][0]["message"]["content"].strip()
        click.echo(answer)

except requests.exceptions.RequestException as e:
        raise click.ClickException(f"API request failed: {str(e)}")
    except (json.JSONDecodeError, KeyError):
        raise click.ClickException("Failed to parse API response")

if __name__ == "__main__":
    ask()
      

用法示例¶


        # Set your API key
export OPENAI_API_KEY="your-api-key-here"

# Ask questions
python3 openai.py "how do I list files in linux"
python3 openai.py "explain git rebase"

# Or pass the API key directly
python3 openai.py --api-key "your-key" "what is docker"
      

与 Pulp CLI 集成时:


        # Ask about repository management
pulp console chat ask "How do I create an RPM repository?"

# Get help with workflows
pulp console chat ask --model gpt-4.1 "How do I sync and publish content?"

# Troubleshooting
pulp console chat ask "Why is my sync failing with authentication errors?"
      

有多容易¶

照着 OpenAI 的文档来做,执行起来很直接。实际实现还包含了一些额外功能,比如:

  • 多种输出格式(JSON/text)
  • 模型选择选项
  • 可配置的响应参数
  • 更好的错误处理

你可以通过以下方式把它加到任何 CLI 工具里:1. 把 chat 命令加入你的 CLI 框架 2. 设置 OpenAI API 集成 3. 处理 API key 和错误情况

完整实现见 Pulp CLI Console 扩展——可以查看 https://github.com/pulp/pulp-cli-console/blob/pulp-cli-ai-experiment/pulpcore/cli/console/chat.py。

The translation is machine-generated and individual terms may be off. Nothing is rewritten or cut; the original is authoritative.

Published by HN AI
This site only summarises and aggregates; copyright stays with the original author. Headlines and summaries follow the source — where they differ, the original wins.
Read the original ↗