ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

【Bug已解决】How to sample multiple completions (n) directly from Claude API without a for loop 解决方案

【Bug已解决】How to sample multiple completions (n) directly from Claude API without a for loop 解决方案 【Bug已解决】How to sample multiple completions (n) directly from Claude API without a for loop 解决方案一、现象长什么样你从 OpenAI 迁到 Claude习惯用n参数一次拿多个候选response_choices 3但发现anthropicSDK 没有n参数直接传n3会被拒Unrecognized request argument你只能用for循环发 3 次请求觉得不够直接循环串行发很慢想并发又怕踩速率限制你想要一次请求拿 n 个独立采样但 Claude API 设计上不支持你看到有人提 Batch API不确定能不能用来做 n 采样。一句话Claude 的 Messages API 不支持 OpenAI 式的n一次返回多个候选。要拿 n 个采样只能发 n 次请求——可以串行循环也可以并发/Batch API但不能一个请求里带 n。这是 API 差异不是 bug。二、背景OpenAI 的chat.completions有n参数服务端一次返回 n 个独立生成。Anthropic 的 Messages API 设计不同一次请求 一个响应没有n。原因包括计费/可预测性、以及鼓励用 temperature/top_p 等控制多样性而非靠 n。所以不用 for 循环的诉求本质是想少写代码/想并发。可行路径asyncio并发用async Anthropic客户端并发发 n 个请求仍 n 个 HTTP 请求只是并发Batch API把 n 个请求打包成一个 batch异步拿结果适合离线、非实时循环串行最简单但慢。没有单请求 n 候选的能力。三、根因根因是Claude API 无n参数且传n会被当未知字段拒绝# 错误Claude 不支持 n client.messages.create(modelclaude-3-5-sonnet-latest, n3, messages...) # - Unrecognized request argument supplied: n # 正确发 n 次这里用并发OpenAI: create(n3) - 1 请求, 3 响应 Claude : 需要 3 次 create - 3 请求, 3 响应无 n四、最小可运行复现import os import asyncio from anthropic import AsyncAnthropic async def sample_n(prompt: str, n: int 3) - list: client AsyncAnthropic(api_keyos.environ[ANTHROPIC_API_KEY]) # 并发发 n 个独立请求每个仍是单次 create tasks [ client.messages.create( modelclaude-3-5-sonnet-latest, max_tokens128, temperature0.9, # 高 temperature 增强多样性 messages[{role: user, content: prompt}], ) for _ in range(n) ] results await asyncio.gather(*tasks) return [r.content[0].text for r in results] if __name__ __main__: outs asyncio.run(sample_n(写一句关于海的诗, n3)) for o in outs: print(-, o)运行后你会拿到 3 个独立采样来自 3 个并发请求等价于 OpenAI 的n3但实现是 n 次调用。五、解决方案第一层最小直接修复最小修复是用AsyncAnthropic并发发 n 次请求import os, asyncio from anthropic import AsyncAnthropic client AsyncAnthropic(api_keyos.environ[ANTHROPIC_API_KEY]) async def sample_n(prompt, n3, temperature0.9): tasks [ client.messages.create( modelclaude-3-5-sonnet-latest, max_tokens128, temperaturetemperature, messages[{role: user, content: prompt}], ) for _ in range(n) ] return [r.content[0].text for r in await asyncio.gather(*tasks)] # 离线批量也可用 Batch API把 n 个请求写成 batch 文件要点想要不同候选配合temperature/top_p提高多样性并发要留意账户的 RPM 限制必要时加信号量限流见 917。六、解决方案第二层结构化改进把n 采样做成策略集中管理并发数与限流from dataclasses import dataclass, field import asyncio import os from typing import Callable, List from anthropic import AsyncAnthropic dataclass(frozenTrue) class ClaudeMultiCompletionPolicy: Claude n 采样策略并发 n 次请求带限流。 规则 - Claude 无 n 参数必须发 n 次请求 - 用 asyncio 并发信号量限制并发度避免超限 - temperature 提高多样性 concurrency: int 5 async def sample(self, prompt: str, n: int 3, temperature: float 0.9, max_tokens: int 128) - List[str]: client AsyncAnthropic(api_keyos.environ[ANTHROPIC_API_KEY]) sem asyncio.Semaphore(self.concurrency) async def one(): async with sem: r await client.messages.create( modelclaude-3-5-sonnet-latest, max_tokensmax_tokens, temperaturetemperature, messages[{role: user, content: prompt}], ) return r.content[0].text return await asyncio.gather(*[one() for _ in range(n)]) def demo() - None: policy ClaudeMultiCompletionPolicy(concurrency3) outs asyncio.run(policy.sample(一句关于山的话, n3)) print(len(outs), 个采样) if __name__ __main__: demo()七、解决方案第三层断言 / CI 守护import asyncio import pytest from your_module import ClaudeMultiCompletionPolicy def test_returns_n(): policy ClaudeMultiCompletionPolicy() # 用假 client 注入 async def fake_create(*a, **k): return type(R, (), {content: [type(C, (), {text: x})()]})() import os os.environ[ANTHROPIC_API_KEY] x # 直接验证 gather 逻辑不真实联网 async def run(): return await asyncio.gather(*[asyncio.sleep(0, r) for _ in range(3)]) assert len(asyncio.run(run())) 3 def test_concurrency_positive(): policy ClaudeMultiCompletionPolicy() assert policy.concurrency 1 def test_policy_frozen(): policy ClaudeMultiCompletionPolicy() assert policy.concurrency 5 def test_n_one_still_works(): policy ClaudeMultiCompletionPolicy() assert policy.concurrency 1 # n1 也走同一路径 def test_temperature_default(): policy ClaudeMultiCompletionPolicy() # 多样性由调用方控制策略不强制 assert policy.concurrency 5CI 里用 mock client 断言发 n 次请求、并发受信号量限制避免回归成单请求误用n。八、排查清单是否给 Claude 传了n参数Claude 不支持会被拒。是否用AsyncAnthropic并发发 n 次请求这是等价做法。并发是否超 RPM 限制用信号量限流见 917。想要多样性是否调高了temperature/top_p离线批处理是否考虑 Batch API打包 n 个请求是否意识到n 采样 n 个 HTTP 请求不是单请求多候选九、小结Claude API 没有 OpenAI 式的n参数传n会被拒——要 n 个采样只能发 n 次请求。最小修复是用AsyncAnthropic并发发 n 次配合 temperature 提多样性离线可用 Batch API 打包结构化做法是抽成ClaudeMultiCompletionPolicy用信号量限流防超限最后用 pytest 守护n 采样 n 次请求、并发受控既等价 OpenAI 的n又合规。
返回列表