LLM 深度解析 2025:为什么 Claude 4 和 GPT-5.1 改变一切

发布: (2025年12月29日 GMT+8 16:59)
12 min read
原文: Dev.to

Source: Dev.to

上下文管理:从令牌限制到智能摘要

在长时间交互中保持连贯且相关的上下文一直是个挑战。到2025年底,OpenAI 和 Anthropic 已经不再仅仅通过提升令牌上限来解决问题,而是采用了更智能的上下文管理策略。

OpenAI – Responses API

  • 策略转变 – 最初的 Assistants API(v1,已于2024年底弃用)让位于 Assistants API v2,随后推出了 Responses API(2025年3月11日发布)。
  • 意义所在 – Responses API 从底层设计即能够更高效地处理对话历史和上下文,抽象掉了开发者之前必须手动管理的状态。
  • 技术底层
    • 滑动窗口注意力:模型聚焦于对话的最近片段,同时智能地摘要或丢弃不太相关的旧信息。
    • 二次成本缓解:尽管令牌窗口大幅提升,注意力仍保持二次复杂度,因此摘要仍是必需的。
  • 模型亮点GPT‑4.1 在编码任务上表现出色,并展示了在大型代码库中更好的上下文保持能力。

Anthropic – Claude 的扩展窗口

模型发布上下文窗口
Claude Opus 4.12025年8月200 k 令牌
Claude Sonnet 4(公开测试版)20251 M 令牌(实验性)
  • 意义所在 – 这些窗口能够一次性处理整本书、庞大的代码库或多小时的重构会话。
  • SDK 辅助 – Anthropic SDK 附带了 compaction_control 辅助函数,当达到预设阈值时会自动进行摘要并清理上下文,免去自行编写压缩逻辑的需求。

使用 compaction_control 与 Claude(Python 示例)

import anthropic
import os

# Ensure your ANTHROPIC_API_KEY is set as an environment variable
# os.environ["ANTHROPIC_API_KEY"] = "YOUR_ANTHROPIC_API_KEY"

client = anthropic.Anthropic()

# ----------------------------------------------------------------------
# Configuration for automatic context compaction
# ----------------------------------------------------------------------
compaction_settings = {
    "token_threshold": 5_000,                     # Summarize when history > 5k tokens
    "summarization_model": "claude-sonnet-4.5-20251130",
    "summarization_prompt": (
        "Summarize the preceding conversation for Claude, focusing on key facts "
        "and the user's ultimate goal to help it continue accurately."
    ),
}

def chat_with_claude_with_compaction(user_message: str, history: list):
    """Send a message to Claude, automatically compacting the history if needed."""
    # Append the new user message to the history
    history.append({"role": "user", "content": user_message})

    try:
        response = client.messages.create(
            model="claude-opus-4.1-20250805",
            max_tokens=1_024,
            messages=history,
            compaction_control=compaction_settings,
        )
        assistant_response = response.content[0].text
        history.append({"role": "assistant", "content": assistant_response})
        return assistant_response
    except Exception as e:
        print(f"An error occurred: {e}")
        return "Sorry, I encountered an error."

# ----------------------------------------------------------------------
# Example usage
# ----------------------------------------------------------------------
conversation_history = []

print("User: Hello, I need help planning a complex project.")
resp = chat_with_claude_with_compaction(
    "Hello, I need help planning a complex project. It involves multiple stakeholders and strict deadlines.",
    conversation_history,
)
print(f"Claude: {resp}")

print("\nUser: The project scope has expanded significantly. We now need to integrate three new modules.")
resp = chat_with_claude_with_compaction(
    "The project scope has expanded significantly. We now need to integrate three new modules. How does this impact our timeline?",
    conversation_history,
)
print(f"Claude: {resp}")

注意: 即使拥有巨大的上下文窗口,针对最佳检索和综合的提示仍是一门技巧。仍然需要仔细的提示工程,尤其是在“针尖在稻草堆中”检索至关重要时。

Source:

工具使用与代理工作流

LLM 与外部系统(数据库、API、代码解释器)交互的能力,使它们成为强大的代理。OpenAI 与 Anthropic 都在不断完善它们的工具使用能力,朝着更自主、更高效的编排方向前进。

Anthropic 最近的增强(2025年11月)

  1. 可编程工具调用 – Claude 现在可以在受管理的执行环境中生成并执行调用多个工具的代码,显著降低延迟和 token 消耗,因为不再需要通过 API 的往返请求。
  2. (此处将列出其他功能…)

这些改进进一步实现了真正自主的 AI 助手的愿景,使其能够以最小的开发者工作量管理复杂的多步骤任务。

工具搜索与使用增强

  • 工具搜索 – 解决了管理海量工具的挑战。Claude 不再需要预先加载所有工具定义,而是可以通过全新的搜索功能动态发现并加载所需的工具。
  • 工具使用示例 – 开发者现在可以直接在工具定义中添加具体的使用模式。这些示例严格按照真实 LLM 输出的格式编写,通过展示 何时如何 使用工具,提升 Claude 的工具使用表现。

OpenAI 的 Responses API

OpenAI 的方法,尤其是全新的 Responses API,同样强调强大的工具集成。

  • Assistants API v2 已经提供了改进的函数调用,并可访问 OpenAI‑托管的工具,如 Code InterpreterFile Search
  • Responses API 旨在更无缝地集成这些工具。
  • 它仍然允许开发者使用 JSON 模式定义自定义工具,模型随后可以调用这些工具。

Claude – 程序化工具调用(Python 示例)

import anthropic
import json
import os

client = anthropic.Anthropic()

def get_user_profile(user_id: str):
    if user_id == "user123":
        return {
            "id": "user123",
            "name": "Alice Smith",
            "email": "alice@example.com",
            "plan": "premium"
        }
    return {"error": "User not found"}

def update_user_subscription(user_id: str, new_plan: str):
    if user_id == "user123":
        return {
            "status": "success",
            "user_id": user_id,
            "old_plan": "premium",
            "new_plan": new_plan
        }
    return {"error": "User not found"}

tools = [
    {
        "name": "get_user_profile",
        "description": "Retrieves the profile information for a given user ID.",
        "input_schema": {
            "type": "object",
            "properties": {
                "user_id": {
                    "type": "string",
                    "description": "The ID of the user."
                }
            },
            "required": ["user_id"]
        }
    },
    {
        "name": "update_user_subscription",
        "description": "Updates the subscription plan for a user.",
        "input_schema": {
            "type": "object",
            "properties": {
                "user_id": {
                    "type": "string",
                    "description": "The ID of the user."
                },
                "new_plan": {
                    "type": "string",
                    "description": "The new subscription plan."
                }
            },
            "required": ["user_id", "new_plan"]
        }
    }
]

def chat_with_claude_tools(user_message: str, history: list):
    """Send a message to Claude with tool definitions attached."""
    history.append({"role": "user", "content": user_message})
    response = client.messages.create(
        model="claude-opus-4.1-20250805",
        max_tokens=2048,
        messages=history,
        tools=tools
    )
    # Logic to handle `tool_code` or `tool_use` stop reasons would follow here
    return response.content[0].text

这种程序化方法标志着向更稳健、出错率更低的代理行为迈进,在这种方式中,LLM 的推理以代码形式表达,而不仅仅是通过自然语言提示来调用工具。

多模态能力(2025)

多模态能力已从未来演示转变为实用的、基于 API 的应用。

OpenAI – GPT‑4o 与 GPT‑5.1 系列

  • GPT‑4o(“Omni”) – 2024 年 5 月发布;在单一神经网络中统一文本、音频和图像模态。
  • API 停用 – GPT‑4o 的 API 访问将在 2026 年 2 月结束,为更强大的 GPT‑5.1 系列以及专用模型 o3o4‑mini(2025 年 4 月发布)让路。
  • 关键特性 – 接受图像输入,能够以文本 图像形式响应;支持跨模态的“多模态链式思考”推理。

Anthropic – Claude Vision

  • Claude OpusClaude Sonnet 模型现已具备视觉能力。
  • 适用于文档分析、图表解读以及视觉内容审核。

OpenAI 多模态示例 (Python)

import openai
import base64
import requests
import os

def encode_image(image_path):
    """Read an image file and return a base64‑encoded string."""
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")

def analyze_image_with_openai_multimodal(image_path: str, prompt: str):
    """Send an image + text prompt to a multimodal OpenAI model."""
    base64_image = encode_image(image_path)

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {os.getenv('OPENAI_API_KEY')}"
    }

    payload = {
        "model": "gpt-5.1-latest-20251115",
        "messages": [
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": prompt},
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": f"data:image/jpeg;base64,{base64_image}"
                        }
                    }
                ]
            }
        ],
        "max_tokens": 500
    }

    response = requests.post(
        "https://api.openai.com/v1/chat/completions",
        headers=headers,
        json=payload
    )
    return response.json()["choices"][0]["message"]["content"]

虽然令人印象深刻,但多模态模型仍面临挑战:

  • 细粒度的对象识别或复杂的空间推理可能不如专用计算机视觉模型稳健。
  • 模糊的视觉线索或高度领域特定的图像仍可能导致“幻觉”。

自主代理工作流的崛起(2025年后期)

  • 开发者 正在构建多步骤系统,让大型语言模型充当智能编排者:它们会对任务进行推理,选择工具,执行操作,并根据反馈优化方案。
  • 研究AI Agents 2025: Why AutoGPT and CrewAI Still Struggle with Autonomy 指出自我导向系统仍存在的局限性。
  • 原生平台 来自 OpenAI 和 Anthropic,旨在弥合这些差距,提供更紧密的工具集成、动态工具发现以及更丰富的多模态推理。

AI 代理生态系统 (2025)

New Agents platform – 基于 Responses API 构建 – 处于这一潮流的前沿。它引入了以下概念:

  • Persistent threads 用于对话记忆
  • 访问 OpenAI 托管的工具:Web SearchFile SearchComputer Use

Agents SDK with Tracing 提供了对这些复杂工作流的关键可观测性,使开发者能够调试并理解代理的决策过程。

Anthropic 的代理能力

Anthropic 在代理解决方案上投入巨大,尤其是面向企业的使用场景:

  • Claude Code – 用于编程辅助的专用代理(现已整合进 Team 和 Enterprise 订阅)
  • Claude Artifacts – 用于创意任务的另一专用代理

Compliance API 让 IT 和安全负责人能够以编程方式访问使用情况和内容指标,这对于在大型团队中治理 AI 辅助编码至关重要。

流行的代理 AI 框架

一个成熟的框架生态系统已经形成,提供了构建复杂代理所需的架构支撑,同时抽象掉了大量状态管理和工具编排的复杂性:

  • LangChain
  • CrewAI
  • AutoGen(Microsoft)
  • Phidata
  • LlamaIndex
  • LangGraph(LangChain 的一部分)

这些框架已被业界广泛采用。

与本主题相关的 DataFormatHub 工具

工具描述
JSON 格式化工具为 API 响应格式化并美化 JSON
Base64 编码器为 API 负载编码数据
AI 代理 2025:为何 AutoGPT 和 CrewAI 仍在自主性上挣扎对当前代理限制的深入分析
Neon Postgres 2025:新无服务器功能为何改变一切对无服务器数据库创新的探索
Pandas vs Polars:2025 年的演进为何改变一切对数据框架库的比较研究

本文最初发表于 DataFormatHub,是您获取数据格式和开发者工具洞见的首选资源。

Back to Blog

相关文章

阅读更多 »

介绍 GPT-5.2

GPT-5.2 是我们面向日常专业工作的最先进前沿模型,具备最先进的推理、长上下文理解、编码和视觉能力。使用……