Skip to content

Token节省技巧

概述

在AI应用开发中,Token消耗直接影响成本。掌握Token节省技巧不仅能降低费用,还能提升响应速度和处理效率。本文将介绍一系列实用的Token优化方法,帮助开发者在保证功能的前提下最大化节省成本。

核心内容

提示词优化

1. 精简提示词

python
# 不推荐:冗长的提示词
prompt = """
请帮我分析以下文本的情感倾向,并给出详细的分析结果。
文本内容是:{text}
请从正面、负面、中性三个方面进行分析,并给出置信度。
最后请总结一下整体情感倾向。
"""

# 推荐:精简的提示词
prompt = "分析情感:{text}\n输出:情感类型+置信度"

2. 使用模板变量

python
# 定义可复用的模板
templates = {
    'sentiment': "情感分析:{text}",
    'summary': "总结:{text}",
    'translate': "翻译成{lang}{text}"
}

def create_prompt(template_name, **kwargs):
    return templates[template_name].format(**kwargs)

3. 避免重复信息

python
# 不推荐:重复上下文
messages = [
    {"role": "user", "content": "请记住:项目名称是AI助手"},
    {"role": "assistant", "content": "好的,我记住了项目名称是AI助手"},
    {"role": "user", "content": "项目名称是什么?"}  # 不必要的重复
]

# 推荐:使用系统提示
messages = [
    {"role": "system", "content": "项目名称:AI助手"},
    {"role": "user", "content": "请介绍项目"}
]

上下文压缩

1. 信息摘要

python
def compress_context(long_text, max_tokens=500):
    prompt = f"用最简洁的语言总结以下内容(不超过{max_tokens}个token):\n{long_text}"
    return call_api(prompt)

2. 关键信息提取

python
def extract_key_info(text):
    prompt = f"""提取关键信息(JSON格式):
{text}
输出格式:{{"主题": "", "要点": [], "结论": ""}}"""
    return call_api(prompt)

3. 历史对话管理

python
class ConversationManager:
    def __init__(self, max_history=5):
        self.history = []
        self.max_history = max_history
    
    def add_message(self, role, content):
        self.history.append({"role": role, "content": content})
        
        if len(self.history) > self.max_history * 2:
            self._compress_history()
    
    def _compress_history(self):
        if len(self.history) > 2:
            summary = self._summarize_old_messages()
            self.history = [
                {"role": "system", "content": f"历史摘要:{summary}"},
                self.history[-2],
                self.history[-1]
            ]

响应控制

1. 限制输出长度

python
# 使用max_tokens参数
response = client.chat.completions.create(
    model="gpt-3.5-turbo",
    messages=messages,
    max_tokens=100  # 限制输出Token数
)

2. 指定输出格式

python
# 不推荐:开放式输出
prompt = "请详细描述这个产品的特点"

# 推荐:结构化输出
prompt = """列出产品特点(每项不超过10字):
1. 
2. 
3. 
"""

3. 使用停止符

python
response = client.chat.completions.create(
    model="gpt-3.5-turbo",
    messages=messages,
    stop=["\n\n", "结束"]  # 遇到停止符立即结束
)

批量处理优化

1. 合并请求

python
# 不推荐:多次单独请求
for text in texts:
    result = analyze_sentiment(text)

# 推荐:批量处理
def batch_analyze(texts, batch_size=10):
    results = []
    for i in range(0, len(texts), batch_size):
        batch = texts[i:i+batch_size]
        prompt = "批量分析情感:\n" + "\n".join(batch)
        results.extend(call_api(prompt).split("\n"))
    return results

2. 并行处理

python
import asyncio

async def process_concurrent(texts, max_concurrent=5):
    semaphore = asyncio.Semaphore(max_concurrent)
    
    async def process_with_limit(text):
        async with semaphore:
            return await call_api_async(text)
    
    tasks = [process_with_limit(text) for text in texts]
    return await asyncio.gather(*tasks)

缓存策略

1. 相同请求缓存

python
from functools import lru_cache
import hashlib

@lru_cache(maxsize=1000)
def cached_api_call(prompt_hash):
    return call_api(prompt_hash)

def smart_api_call(prompt):
    prompt_hash = hashlib.md5(prompt.encode()).hexdigest()
    return cached_api_call(prompt_hash)

2. 语义相似缓存

python
from sentence_transformers import SentenceTransformer
import numpy as np

class SemanticCache:
    def __init__(self, similarity_threshold=0.95):
        self.model = SentenceTransformer('all-MiniLM-L6-v2')
        self.cache = {}
        self.threshold = similarity_threshold
    
    def get(self, prompt):
        prompt_embedding = self.model.encode(prompt)
        
        for cached_prompt, (embedding, response) in self.cache.items():
            similarity = np.dot(prompt_embedding, embedding) / (
                np.linalg.norm(prompt_embedding) * np.linalg.norm(embedding)
            )
            if similarity > self.threshold:
                return response
        
        return None

实用技巧

1. Token预算管理

python
class TokenBudget:
    def __init__(self, daily_limit=100000):
        self.daily_limit = daily_limit
        self.current_usage = 0
    
    def can_proceed(self, estimated_tokens):
        return self.current_usage + estimated_tokens <= self.daily_limit
    
    def estimate_prompt_tokens(self, prompt):
        return len(prompt) // 3  # 粗略估算

2. 智能截断

python
def smart_truncate(text, max_tokens, model="gpt-3.5-turbo"):
    encoding = tiktoken.encoding_for_model(model)
    tokens = encoding.encode(text)
    
    if len(tokens) <= max_tokens:
        return text
    
    truncated_tokens = tokens[:max_tokens]
    return encoding.decode(truncated_tokens) + "..."

3. 分层处理

python
def tiered_processing(query, complexity_threshold=100):
    tokens = count_tokens(query)
    
    if tokens < complexity_threshold:
        return call_light_model(query)
    else:
        return call_advanced_model(query)

4. 增量更新

python
def incremental_update(full_content, new_info):
    prompt = f"""基于现有内容,仅添加新信息:
现有内容:{full_content}
新信息:{new_info}
输出:更新后的内容(保持简洁)"""
    return call_api(prompt)

小结

Token节省技巧的核心在于:

  1. 提示词优化:精简、模板化、避免重复
  2. 上下文管理:压缩、摘要、限制历史长度
  3. 响应控制:限制输出、结构化格式、使用停止符
  4. 批量处理:合并请求、并行执行、提高效率
  5. 缓存策略:相同请求缓存、语义相似匹配
  6. 预算管理:设置限制、智能截断、分层处理

通过综合运用这些技巧,可以在保证应用质量的前提下,显著降低Token消耗和API成本。建议根据具体场景选择合适的优化策略,并持续监控效果。