python -m build打包成为tar.gz或者whl
一个非常简单的命令行工具
体验地址
https://deepblog.net/p/482ca30d58fe4bc09fe3d8a6e9abdc58?u=csdn_lineuman&utm_source=share_project&f=link
main.py
import typer
import requests
from typing import Optional
import os
import json# 假设的 DeepSeek API 配置(需替换为实际值)
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")app = typer.Typer(help="cli tools power by DeepSeek")@app.command()
def main(message: str,model: Optional[str] = typer.Option("deepseek-chat", help="指定模型"),stream: Optional[bool] = typer.Option(False, help="流式输出"),
):"""get a reply from DeepSeek"""headers = {"Authorization": f"Bearer {DEEPSEEK_API_KEY}","Content-Type": "application/json",}data = {"model": model,"messages": [{"role": "user", "content": message}],"stream": stream,}try:if stream:# 流式输出(逐词显示)response = requests.post(DEEPSEEK_API_URL, headers=headers, json=data, stream=True)response.raise_for_status()for chunk in response.iter_lines():if chunk:# 解码并移除可能的 "data: " 前缀chunk_str = chunk.decode("utf-8").strip()if chunk_str.startswith("data: "):chunk_str = chunk_str[6:] # 移除 "data: "try:# 解析 JSONchunk_data = json.loads(chunk_str)# 提取内容(根据 DeepSeek API 的实际结构调整)if "choices" in chunk_data:content = chunk_data["choices"][0].get("delta", {}).get("content", "")if content:typer.echo(content, nl=False)except json.JSONDecodeError:# 忽略非 JSON 数据(如心跳信号)passelse:# 普通输出response = requests.post(DEEPSEEK_API_URL, headers=headers, json=data)response.raise_for_status()reply = response.json()["choices"][0]["message"]["content"]typer.echo(reply)except Exception as e:typer.secho(f"Error: {e}", fg=typer.colors.RED, err=True)if __name__ == "__main__":app()
pyproject.toml
[project]
name = "deep_cli"
version = "0.1.0"
description = "cli tool powered by deepseek"
authors = [{ name = "lineuman", email = "lxx" }]
requires-python = ">=3.8"
license = "MIT" dependencies = ["typer>=0.9.0","requests>=2.31.0","rich>=13.0.0", # 可选:美化输出
][project.scripts]
deep_cli = "deep_cli.main:app"[tool.setuptools]
packages = ["deep_cli"][build-system]
requires = ["setuptools>=65.0.0"]
build-backend = "setuptools.build_meta"