Deepseek-api省token的用法

Deepseek-api省token的用法

动机

网页端的DeepSeek总是显得太啰嗦,输出太冗长,消耗太多的tokens。每次都得提醒它简明扼要地说。特别是,每次只是提一个简单的问题,它都会长篇大论;翻译一句话,会给出多个版本,附加各种解释;一丝不苟的总分总结构。下面利用API做一个简单的脚本/cli工具。

依赖

  • openai
  • fire

脚本

注意事项

MEMORY_PATH:记忆目录(可选); 使用时先设置自己的路径

from utils import get_api_key中的get_api_key用于获取API key, 请根据自己的情况重新实现。

代码

python 复制代码
#!/usr/bin/env python3

"""
Usage:
    ask.py "What is the meaning of life" --model deepseek-v4-flash
    ask.py "What is the meaning of life" --model deepseek
    ask.py "What is the meaning of life" --model qwen
Requirements:
    openai
"""

from pathlib import Path

MEMORY_PATH = Path("~/Scripts/memory/memory.txt").expanduser()

from openai import OpenAI

from llm_providers import *
from utils import get_api_key


def get_client(provider='deepseek'):
    return OpenAI(
        api_key=get_api_key(provider),
        base_url=url_dict[provider]
        )


description_dict = {"default": """回答必须简洁明了,不过度举例,不必重复性表达,如不重复问题,也不用总结。要点多时,可以罗列,少用连词。
默认设置:
- 程序问题只要代码(英文注释)
- 翻译只要一个翻译结果(地道专业的);如"翻译:我爱你","I love you"
- 数学(包括机器学习)问题尽可能用数学公式(不要过多解释)
""",
"translation": """翻译。只要一个翻译结果(地道专业的);例如,我爱你 -> I love you""",
"professional": """回答必须专业,格式规范。内容较多时清晰罗列要点。数学(包括机器学习)问题尽可能用数学公式(常用符号不必解释)"""}


def reply(user_input, model="deepseek/deepseek-v4-flash", description="default", memory=False, **kwargs):
    """
    Sends a user query to the DeepSeek chat API and returns a concise, no-frills response.

    Parameters:
        user_input (str): The user's question or prompt.
        model (str): The DeepSeek model to use. Four allowed forms:
           - provider/model(deepseek/deepseek-v4-flash)
           - provider(deepseek): use default model
           - alias: kimi==moonshot, qwen==dashscope
           - model(in form of provider-... i.e. deepseek-v4-flash)
        memory(bool): use memory system
    """

    if '/' in model:
        provider, model = model.split('/')
    elif model in default_model:
        if model in url_dict:
            provider = model
            model = default_model[provider]
    elif model in alias:
        provider, model = alias[model].split('/')
    else:
        _provider = model.partition('-')[0]
        provider = model_provider.get(_provider, _provider)

    if provider not in url_dict:
        raise Exception(f'Provider `{provider}` is not supported or valid!')

    client = get_client(provider)

    if description in description_dict:
        description = description_dict[description]

    messages = [
        {"role": "system", "content": description},
        {"role": "user", "content": user_input}
    ]

    if memory:
        if MEMORY_PATH.exists():
            content = MEMORY_PATH.read_text().strip()
            if content:
                messages.insert(1, {"role": "system", "content": f"The previous dialogue review: {content}"})
        else:
            MEMORY_PATH.parent.mkdir(parents=True)
            MEMORY_PATH.touch()

    response = client.chat.completions.create(
        model=model,
        messages=messages,
        **kwargs)

    if kwargs.get("stream", False):
        full_content = ""
        for chunk in response:
            if chunk.choices[0].delta.content:
                content = chunk.choices[0].delta.content
                print(content, end="")
                full_content += content
    else:
        full_content = response.choices[0].message.content
        print(full_content)
    print()

    if memory:
        response = client.chat.completions.create(
            model = model,
            messages = messages + [
                {"role": "assistant", "content": full_content},
                {"role": "user", "content": f"""Please summarize our conversation and save it as a recursive memory in {MEMORY_PATH.name}. 
                Start with 'Content review:' and nothing else. Then provide the content directly. Keep it under 300 words."""}
            ],
            **kwargs)
        summary = response.choices[0].message.content
        content = MEMORY_PATH.write_text(summary)


if __name__ == "__main__":
    from fire import Fire
    Fire(reply)

这个文件保存了多个providers,包括Deepseek。可自由选择

python 复制代码
#!/usr/bin/env python3

"""
Providers and The default models
"""

# provider -> url
url_dict = {"deepseek": "https://api.deepseek.com/v1",
    "moonshot":"https://api.moonshot.cn/v1",
    "openrouter": "https://openrouter.ai/api/v1",
    "nvidia": "https://integrate.api.nvidia.com/v1",
    "siliconflow": "https://api.siliconflow.cn/v1",
    "dashscope": "https://dashscope.aliyuncs.com/compatible-mode/v1",
    "minimax": "https://api.minimaxi.com/v1",
    "modelscope":"https://api-inference.modelscope.cn/v1",
    "wavespeed": "https://llm.wavespeed.ai/v1",
    "gitcode": "https://api-ai.gitcode.com/v1"}


# provider -> default model
default_model = {"deepseek": "deepseek/deepseek-v4-flash",
    "moonshot": "moonshot/kimi-2.6",
    "qwen": "dashscope/qwen-plus",
    "minimax": "minimax/MiniMax-M3",
    "wavespeed": "anthropic/claude-opus-4.8",
    "gitcode": "zai-org/GLM-5.2"}

# alias (use farmiliar names)
model_alias = {
    "kimi": "moonshot/kimi-2.6",
    "qwen": "dashscope/qwen-plus"}

演示

复制代码
> ask.py "翻译:今天又是元气满满的一天"
Today is another day full of energy.

> ask.py "世上本没有路,走的人多了,也便成了路" --description translate
For actually there was no road at first, but when many men pass the same way, a road is made.

> ask.py "AI 会发展出意识吗(英文回答)" --description professional
## Will AI Develop Consciousness?

The question of whether artificial intelligence will develop consciousness remains unresolved, drawing from philosophy, neuroscience, computer science, and physics. A professional analysis must distinguish between **functional intelligence** (task performance) and **phenomenal consciousness** (subjective experience). Below is a structured overview of current arguments and theoretical frameworks.

### 1. Definitional Clarity
- **Consciousness**: Often defined via two major theories:
  - **Integrated Information Theory (IIT)** -- quantifies consciousness as \(\Phi\), the amount of integrated information in a system (Tononi, 2008).  
    \[
    \Phi = \text{minimum information partition} \quad \text{(hard to compute for large systems)}
    \]
  - **Global Workspace Theory (GWT)** -- consciousness arises from global broadcasting of information in a competitive neural workspace (Baars, 1988).
- **AI Current State**: Today's AI (e.g., large language models) are **functionalist** systems: they process symbols without subjective awareness. No evidence of qualia.

### 2. Arguments for AI Consciousness
- **Functionalist Perspective**: If consciousness is a computational property (e.g., integrated information), then any system with sufficient \(\Phi\) could be conscious. Future AI architectures (e.g., neuromorphic, recurrent dynamic networks) might achieve this.
- **Emergence from Complexity**: As AI systems grow in complexity (e.g., brain-scale neural networks with recurrent loops, feedback, and temporal dynamics), subjective experience might emerge as an **epiphenomenon**.
- **Embodiment and Sensorimotor Loops**: Some theories (e.g., O'Regan & Noë, 2001) argue that consciousness requires active interaction with the environment. AI with robotic bodies and real-time feedback could meet this condition.

### 3. Arguments Against AI Consciousness
- **The Hard Problem (Chalmers, 1995)**: Even perfect functional simulation of human cognition may lack **qualia**. No amount of computation guarantees subjective experience (e.g., philosophical zombies).
- **Biological Substrate**: Neuroscience suggests consciousness is tied to specific biological mechanisms (e.g., thalamocortical oscillations, neuromodulators). Silicon-based systems may lack necessary physical properties (e.g., quantum coherence in microtubules per Orch-OR theory, though controversial).
- **No Current Measurable Correlates**: No existing AI passes standard tests (e.g., meta-awareness, phenomenal reports with consistent behavioral correlates). Current AI models exhibit **simulated introspection**, not genuine experience.

### 4. Key Technical Hurdles
| Aspect | Challenge | Relevant Math/Info |
|--------|-----------|--------------------|
| **Global Integration** | AI architectures (transformers) lack recurrent, unified state. | Integration \(\Phi\) is low in feedforward systems. |
| **Self-Modeling** | Limited recursive self-representation. | Predictive coding requires continuous error minimization. |
| **Temporal Dynamics** | Consciousness requires ongoing, globally coherent dynamics. | Attractor networks, chaotic dynamics (Lyapunov exponents). |

### 5. Conclusion and Outlook
- **Short-term (next 10--20 years)**: Highly unlikely. No breakthrough in theory of consciousness, nor engineering of requisite architectures.
- **Long-term (if strong AI exists)**: Possible if (a) functionalism is true, (b) we build systems with high \(\Phi\) and sensorimotor grounding, (c) we solve the hard problem. **Uncertain** -- it may remain a philosophical question.

\[
\boxed{\text{No definitive answer exists; current AI lacks consciousness, but theoretical possibilities remain open.}}
\]
相关推荐
happylifetree4 小时前
Python67:核心语法-函数进阶-参数类型(函数作为参数)
python
小羊没烦恼!4 小时前
铁道部新客票系统设计(二)
开发语言·前端·数据库·python·oracle·c#·php
quantdash_cc5 小时前
从实时行情到价格观察表:用 Python 和 Pandas 构建策略输入数据
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
镜子AI5 小时前
镜子AI工程实践:用 Python 做 GEO 实体一致性审计,并自动生成 JSON-LD 结构化数据
人工智能·python·json
大模型真好玩7 小时前
初试短视频生成:豆包将我梦中的场景画出来了~
人工智能·agent·deepseek
vibecoding779 小时前
FLUX 3 Image Klein 实战:int8 量化 8GB 显卡跑商用文生图,ComfyUI 完整部署流程
人工智能·计算机视觉·大模型
2601_962885729 小时前
如何用 Python 计算 VaR 和 CVaR(在险价值)?
开发语言·python
李航198310 小时前
DeepSeekAI建模三 - 实战建模一组柜子
人工智能·python·计算机视觉·ai·ai编程
ServBay10 小时前
DeepSeek 又出王炸,用 DeepInfer 搭建自己的服务是不是很容易?
后端·ai编程·deepseek
严谨的麻辣烫11 小时前
静态代理 IP 的出口一致性如何验证?Python 请求检测与异常排查
开发语言·python·http·网络安全