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.}}
\]
相关推荐
测试老哥1 小时前
Pytest自动化测试详解
自动化测试·软件测试·python·测试工具·测试用例·pytest·接口测试
坚持学习前端日记1 小时前
国产化适配全流程适配英伟达本地开发
人工智能·python
源图客2 小时前
云途物流API开发-鉴权认证(Java)
java·网络·python
三川6983 小时前
Tkinter库的学习记录06-变量类别
python
wenying_443237443 小时前
Python脚本—1.提取压缩包中的pdf文件
python·ai编程
_Jimmy_3 小时前
SQLAlchemy 复杂 SQL 执行指南与模板库
python·sql
六个九十度3 小时前
用python脚本访问被网关隔离的嵌入式设备
开发语言·python
GEO_ai_zhijian4 小时前
饮料生产线质量检测系统供应商哪家强
大数据·python
小Bk4 小时前
我用 Next.js 16 + DeepSeek API 做了一个 AI 简历吐槽器,已开源
openai·next.js·deepseek