共计 2981 个字符,预计需要花费 8 分钟才能阅读完成。
作为 Ubuntu 开发者,每次调试代码想快速咨询 ChatGPT 时,都要:
1. 切到浏览器
2. 等待页面加载
3. 重新登录
4. 找到历史会话 … 这套流程简直让人崩溃。今天分享几个终端直连方案,让 AI 助手真正融入开发流。

基础方案:curl+API 闪电访问
最快上手的方案,适合简单查询场景。核心是处理好 Bearer Token 和响应解析:
#!/bin/bash
# 从环境变量读取 API 密钥(安全存储方案见第四章)AUTH_TOKEN=${CHATGPT_TOKEN}
# 防御性检查
if [-z "$AUTH_TOKEN"]; then
echo "错误:未检测到 API 令牌" >&2
exit 1
fi
# 构造带超时和重试的 curl 请求
response=$(curl -sS --max-time 30 --retry 2 \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AUTH_TOKEN" \
-d '{"model":"gpt-3.5-turbo","messages": [{"role":"user","content":"'"$1"'"}]}' \
https://api.openai.com/v1/chat/completions)
# 用 jq 解析 JSON 响应,过滤 null 结果
echo $response | jq -r '.choices[0].message.content //"Empty response"'
关键点说明:
– User-Agent 建议设置为 ”ChatGPT-Terminal/1.0″ 方便服务端识别
– 使用 max-time 避免僵尸请求
– jq 的 // 运算符提供默认值防止脚本中断
进阶方案:Python 全功能封装
需要上下文保持时(比如调试多轮对话),推荐用 Python 实现:
import os
import asyncio
from typing import List, Dict
import aiohttp # 异步 HTTP 客户端
class ChatGPTClient:
def __init__(self):
self.session = aiohttp.ClientSession(
headers={"Authorization": f"Bearer {os.getenv('CHATGPT_TOKEN')}",
"User-Agent": "Python-ChatGPT/1.0"
},
timeout=aiohttp.ClientTimeout(total=30)
)
self.conversation_history: List[Dict] = [] # 会话上下文存储
async def ask(self, prompt: str) -> str:
self.conversation_history.append({"role": "user", "content": prompt})
try:
async with self.session.post(
"https://api.openai.com/v1/chat/completions",
json={
"model": "gpt-3.5-turbo",
"messages": self.conversation_history
}
) as resp:
if resp.status == 429: # 处理速率限制
retry_after = int(resp.headers.get("Retry-After", 5))
await asyncio.sleep(retry_after)
return await self.ask(prompt)
data = await resp.json()
reply = data["choices"][0]["message"]
self.conversation_history.append(reply)
return reply["content"]
except Exception as e:
print(f"请求失败: {str(e)}")
return ""
这段代码实现了:
1. 异步非阻塞调用
2. 自动维护对话历史
3. 基础速率限制处理
4. 类型注解提升可维护性
高阶方案:TUI 交互界面
用 urwid 库构建终端 GUI,伪代码示意核心架构:
import urwid
class ChatGPTUI:
def __init__(self):
self.client = ChatGPTClient()
self.message_list = urwid.SimpleListWalker([])
# 构建界面组件
self.input_box = urwid.Edit("你说:")
self.output_box = urwid.ListBox(self.message_list)
self.frame = urwid.Frame(
body=self.output_box,
footer=self.input_box
)
async def on_submit(self, user_input):
# 显示用户输入
self.message_list.append(urwid.Text(f"» {user_input}"))
# 获取 AI 回复并更新 UI
response = await self.client.ask(user_input)
self.message_list.append(urwid.Text(f"« {response}"))
# 主事件循环
loop = urwid.MainLoop(ChatGPTUI().frame)
loop.run()
安全与优化实践
敏感信息存储
三种安全方案对比:
-
环境变量(适合开发环境):
echo 'export CHATGPT_TOKEN="sk-xxx"' >> ~/.bashrc -
keyring(生产环境推荐):
import keyring keyring.set_password("chatgpt", "api_key", "sk-xxx") token = keyring.get_password("chatgpt", "api_key") -
加密配置文件(平衡方案):
from cryptography.fernet import Fernet cipher = Fernet.generate_key() encrypted = Fernet(cipher).encrypt(b"sk-xxx")
网络代理配置
如果公司网络需要代理:
import os
# 在 ClientSession 中增加代理参数
proxy = os.getenv("HTTPS_PROXY")
connector = aiohttp.TCPConnector(ssl=False if proxy else True)
日志脱敏
处理日志时自动过滤敏感信息:
import re
def sanitize_log(text: str) -> str:
return re.sub(r"(sk-)[a-zA-Z0-9]{20,}", r"\1[REDACTED]", text)
延伸思考
尝试实现这些进阶功能:
1. 将 CLI 工具与 VSCode 结合,通过 Ctrl+Shift+P 直接调用
2. 设计优先级队列处理 429 错误,重要查询优先重试
3. 添加 --stream 参数支持流式响应(类似官方网页效果)
这些方案已在我的 Ubuntu 22.04 上稳定运行半年,现在每天节省至少 1 小时的上下文切换时间。关键是所有操作都不需要离开心爱的终端!
