这里的“覆盖”指什么

教程覆盖当前固定版本中扫描到的原生语法、标准库接口及有接收者线索的方法,每节末尾都有全部相关源码位置。标准库知识先用小实验讲清,再到完整源码查看它在业务里的输入、交接和退出。

同名的 .get()、.join()、.close() 不能单凭名字认定为并发接口。没有可靠接收者线索的记录仍放在第 21 节的核对表中,保留原始代码,不混入已确认的 API 数量。

固定版本 2f2318653f6f794dddd321eff7c9d4b7b174643f,共扫描 381 个 Python 文件。下面的“对应”表示有明确讲解入口,不表示执行过 Slime 训练或证明了所有运行时类型。

记录数量怎样阅读
直接标准库 API518 个位置 / 83 个名称逐项对应下面的讲解
异步语法747定义、等待、资源作用域、异步迭代
导入147对应所属机制的入口
有接收者线索的方法206按构造或注解对应具体接口;仍保留推断标记
其余同名方法候选670到第 21 节核对类型,不算作已确认的原生 API
Markdown 中的示例29本页下方保留全文及对应讲解

每种用法到哪里学习

讲解对应的 API、方法与语法(含理解所需的补充接口)源码位置数
定义协程函数与创建协程对象async_def281
运行顶层协程与事件循环入口asyncio asyncio.run112
沿当前调用链等待与恢复asyncio.sleep await442
阻塞线程与挂起任务的区别time.sleep57
创建任务与保留引用asyncio.create_task asyncio.Task24
收集整组结果与异常边界asyncio.gather27
等待条件与完成集合asyncio.wait asyncio.FIRST_COMPLETED8
按完成顺序消费结果asyncio.as_completed1
请求取消与等待清理asyncio.CancelledError11
超时与取消保护的边界asyncio.TimeoutError asyncio.timeout asyncio.wait_for asyncio.shield18
许可区域、限流与归还asyncio.Semaphore asyncio.Semaphore.acquire asyncio.Semaphore.release11
异步队列的生产消费与背压asyncio.Queue asyncio.Queue.put asyncio.Queue.get asyncio.Queue.empty4
同步队列与立刻尝试取结果queue.Queue queue.Empty queue.Queue.put queue.Queue.get queue.Queue.get_nowait queue.Queue.qsize queue.Queue.empty15
把同步函数交给工作线程asyncio.to_thread asyncio.AbstractEventLoop.run_in_executor15
线程启动、互斥、通知与退出threading.Thread threading.Lock threading.Event threading.get_ident threading.Thread.start threading.Thread.join threading.Thread.is_alive threading.Lock.acquire threading.Lock.release threading.Event.wait threading.Event.set threading.Event.clear threading.Event.is_set120
异步进入、退出与资源回收contextlib.asynccontextmanager async_with48
异步迭代与异步生成器async_for async_generator_def async_yield15
任务上下文与 token 恢复contextvars.ContextVar contextvars.ContextVar.get contextvars.ContextVar.set contextvars.ContextVar.reset18
进程池分配与收集工作multiprocessing.Pool.starmap multiprocessing.context.BaseContext.Pool2
回到 Slime 的创建、交接与清理0
Event 的等待、通知、状态与清零asyncio.Event asyncio.Event.wait asyncio.Event.set asyncio.Event.clear asyncio.Event.is_set35
asyncio.Lock 保护任务共享状态asyncio.Lock asyncio.Lock.acquire asyncio.Lock.release asyncio.Lock.locked1
Condition 谓词循环、锁交接与通知threading.Condition threading.Condition.wait threading.Condition.wait_for threading.Condition.notify_all24
同一线程重入 RLockthreading.RLock threading.RLock.acquire threading.RLock.release6
Timer 启动、取消与退出threading.Timer threading.Timer.start threading.Timer.cancel threading.Timer.join3
线程池 submit 与 map 的结果组织concurrent.futures.ThreadPoolExecutor concurrent.futures.ThreadPoolExecutor.submit concurrent.futures.ThreadPoolExecutor.map concurrent.futures.Executor.submit concurrent.futures.Executor.map39
同步 Future 的结果、异常与完成状态concurrent.futures.CancelledError concurrent.futures.Future.result concurrent.futures.Future.exception concurrent.futures.Future.done11
Future 取消边界与完成回调concurrent.futures.Future.cancel concurrent.futures.Future.cancelled concurrent.futures.Future.running concurrent.futures.Future.add_done_callback0
同步 wait 与 FIRST_COMPLETEDconcurrent.futures.wait concurrent.futures.FIRST_COMPLETED4
按完成次序消费线程池结果concurrent.futures.as_completed4
线程池关闭与在途工作清理concurrent.futures.ThreadPoolExecutor.shutdown concurrent.futures.Executor.shutdown2
测试替身直接构造 Future 并设置结果concurrent.futures.Future concurrent.futures.Future.set_result concurrent.futures.Future.set_exception5
创建进程、启动上下文与所有权multiprocessing.Process multiprocessing.get_context multiprocessing.set_start_method multiprocessing.active_children multiprocessing.Process.start multiprocessing.Process.is_alive multiprocessing.context.BaseContext.Process multiprocessing.context.BaseContext.Queue20
跨进程生产消费与结束协议multiprocessing.Queue queue.Empty multiprocessing.Queue.put multiprocessing.Queue.get multiprocessing.Queue.empty multiprocessing.Queue.qsize3
等待、终止、回收与队列关闭multiprocessing.Process.join multiprocessing.Process.terminate multiprocessing.Process.kill multiprocessing.Process.close multiprocessing.Queue.close multiprocessing.Queue.join_thread0
进程池分派与退出multiprocessing.Pool multiprocessing.context.BaseContext.Pool multiprocessing.Pool.starmap multiprocessing.Pool.close multiprocessing.Pool.terminate multiprocessing.Pool.join multiprocessing.Pool.__enter__ multiprocessing.Pool.__exit__0
子进程通信、超时与回收subprocess.Popen subprocess.TimeoutExpired subprocess subprocess.Popen.communicate subprocess.Popen.poll subprocess.Popen.wait subprocess.Popen.kill subprocess.Popen.terminate52
捕获、合并与丢弃输出subprocess.PIPE subprocess.STDOUT subprocess.DEVNULL16
同步命令检查与失败状态subprocess.run subprocess.check_call subprocess.check_output subprocess.CalledProcessError22
跨进程文件锁与目录所有权fcntl.flock fcntl.LOCK_EX fcntl.LOCK_NB fcntl.LOCK_SH9
管道可读等待与就绪协议select.select2
进程退出与解锁fcntl.LOCK_UN1
父子身份与定向信号os.getpid os.getppid os.kill35
保存、安装与恢复信号处理器signal.signal signal.getsignal signal.SIGINT signal.SIGTERM signal.SIGHUP signal.SIGKILL14
进程组信号与清理范围os.killpg signal.SIG_IGN2
同步工作闹钟与恢复边界signal.alarm signal.SIGALRM3
同步 shell 调用与退出状态os.system4
Task、线程、进程和进程组的不同停止责任0
Future:待完成结果与所属 loopasyncio.get_running_loop asyncio.Future asyncio.InvalidStateError asyncio.AbstractEventLoop.create_future asyncio.Future.result13
Future 完成、取消与分批回调asyncio.AbstractEventLoop.call_soon asyncio.AbstractEventLoop.call_later asyncio.Future.done asyncio.Future.set_result asyncio.Future.set_exception asyncio.Future.cancel asyncio.Future.cancelled asyncio.Future.add_done_callback4
创建、登记、运行与跨线程提交asyncio.AbstractEventLoop asyncio.new_event_loop asyncio.set_event_loop asyncio.run_coroutine_threadsafe asyncio.wrap_future asyncio.AbstractEventLoop.run_forever asyncio.AbstractEventLoop.run_until_complete concurrent.futures.Future.result23
事件循环停止、executor 排空与关闭asyncio.AbstractEventLoop.call_soon_threadsafe asyncio.AbstractEventLoop.is_running asyncio.AbstractEventLoop.stop asyncio.AbstractEventLoop.close asyncio.AbstractEventLoop.shutdown_default_executor2
Task 身份、归属与完成读取asyncio.current_task asyncio.all_tasks asyncio.Task asyncio.CancelledError asyncio.Task.done asyncio.Task.result asyncio.Task.exception asyncio.Task.cancel asyncio.Task.cancelled asyncio.Task.get_loop asyncio.Task.add_done_callback17
手动 loop 的异步生成器兜底清理asyncio.AbstractEventLoop.shutdown_asyncgens0
创建本地监听与流式连接asyncio.start_server asyncio.open_connection asyncio.Server asyncio.StreamReader asyncio.StreamWriter1
流式读取与协议分帧asyncio.LimitOverrunError asyncio.StreamReader.read asyncio.StreamReader.readline asyncio.StreamReader.readuntil asyncio.StreamReader.readexactly0
提前 EOF 的部分数据与期待长度asyncio.IncompleteReadError1
写入流量控制与连接关闭asyncio.StreamWriter.write asyncio.StreamWriter.drain asyncio.StreamWriter.close asyncio.StreamWriter.wait_closed0
监听器与连接任务的独立收尾asyncio.Server.is_serving asyncio.Server.serve_forever asyncio.Server.close asyncio.Server.wait_closed0
调用后检查返回对象能否 awaitinspect.isawaitable3
装饰时判断协程函数并选择 wrapperinspect.iscoroutinefunction1
Awaitable 和 AsyncIterator 注解契约collections.abc.Awaitable collections.abc.AsyncIterator7
上下文与迭代的异步协议入口builtins.StopAsyncIteration contextlib.AbstractAsyncContextManager.__aenter__ contextlib.AbstractAsyncContextManager.__aexit__ collections.abc.AsyncIterable.__aiter__ collections.abc.AsyncIterator.__anext__ async_protocol_def0
提前退出异步生成器时显式关闭contextlib.aclosing collections.abc.AsyncGenerator.aclose0
同名方法与原生接收者证据边界dict.get str.join queue.Queue.get queue.Queue.join asyncio.Queue.get asyncio.Queue.join threading.Thread.join670

源码位置数只计算扫描到的记录;部分接口为理解完整机制而补充,不能据此认定 Slime 使用了表内每个接口。

文档中的全部 Python 示例

以下代码出自 Slime 文档,保留原文;其中可能有省略号、业务对象和第三方依赖,不能当作独立可运行实验。每节下载的 example.py 才是验证过的最小实验。

DOC-001 · .claude/skills/add-reward-function/SKILL.md:36

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象

async def custom_rm(args, sample):
    return float_reward_or_reward_dict
DOC-002 · .claude/skills/add-reward-function/SKILL.md:41

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象

async def custom_rm(args, samples):
    return list_of_rewards
DOC-003 · docs/en/advanced/sglang-config.md:173

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象 沿当前调用链等待与恢复

from slime.rollout.sglang_rollout import get_model_url
from slime.utils.http_utils import post

async def my_generate(args, sample, sampling_params):
    # Route to the actor model (default)
    actor_url = get_model_url(args, "actor", "/generate")
    output = await post(actor_url, {"text": sample.prompt, "sampling_params": sampling_params})
    
    # Route to the reference model
    ref_url = get_model_url(args, "ref", "/generate")
    ref_output = await post(ref_url, {"text": sample.prompt, "sampling_params": sampling_params})
    
    # Route to the reward model (e.g., OpenAI-compatible API)
    reward_url = get_model_url(args, "reward", "/v1/chat/completions")
    reward_output = await post(reward_url, {...})
    
    ...
DOC-004 · docs/en/advanced/sglang-config.md:402

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象 沿当前调用链等待与恢复

from slime.rollout.sglang_rollout import get_model_url
from slime.utils.http_utils import post

async def generate_with_models(args, sample, sampling_params):
    """Generate using actor, score with reward model, compare with reference."""
    
    # Generate from actor
    actor_url = get_model_url(args, "actor", "/generate")
    actor_output = await post(actor_url, {
        "text": sample.prompt,
        "sampling_params": sampling_params,
        "return_logprob": True,
    })
    
    # Get reference logprobs for KL penalty
    ref_url = get_model_url(args, "ref", "/generate")
    ref_output = await post(ref_url, {
        "text": sample.prompt + actor_output["text"],
        "sampling_params": {"max_new_tokens": 0, "temperature": 0},
        "return_logprob": True,
    })
    
    # Score with reward model
    reward_url = get_model_url(args, "reward", "/v1/chat/completions")
    reward_output = await post(reward_url, {
        "model": "reward",
        "messages": [{"role": "user", "content": sample.prompt + actor_output["text"]}],
    })
    
    # ... process outputs and return Sample
DOC-005 · docs/en/developer_guide/trace.md:60

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象

from slime.observability.trace_utils import trace_function


@trace_function("generate_and_rm", target="sample")
async def generate_and_rm(args, sample, sampling_params, evaluation=False):
    ...


@trace_function(
    "generate_and_rm_group",
    target="group",
    attrs_getter=lambda args, group, sampling_params, evaluation=False: {"group_size": len(group)},
)
async def generate_and_rm_group(args, group, sampling_params, evaluation=False):
    ...
DOC-006 · docs/en/developer_guide/trace.md:90

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象

@trace_function(
    "custom_rollout_batch",
    target="samples",
    attrs_getter=lambda samples, **_: {"batch_size": len(samples)},
)
async def custom_rollout_batch(samples, **kwargs):
    ...
DOC-007 · docs/en/developer_guide/trace.md:107

固定版本的原文 · 对应讲解: 沿当前调用链等待与恢复

from slime.observability.trace_utils import build_sglang_meta_trace_attrs, trace_span

with trace_span(sample, "sglang_generate") as span:
    output = await post(url, payload)
    span.update(build_sglang_meta_trace_attrs(output["meta_info"]))
DOC-008 · docs/en/get_started/agent.md:41

固定版本的原文 · 对应讲解: 沿当前调用链等待与恢复

from slime.agent.adapters import AnthropicAdapter

adapter = AnthropicAdapter(
    tokenizer=tokenizer,
    sglang_url=sglang_url,
    tool_parser=tool_parser,
    reasoning_parser=reasoning_parser,
)

adapter.open_session(session_id, sampling_defaults=sampling_params)
# Agent client sends requests to adapter.app.
segments = await adapter.finish_session(session_id)
DOC-009 · docs/en/get_started/customization.md:77

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象 异步迭代与异步生成器 沿当前调用链等待与恢复

from slime.data.transport import publish_rollout_async
from slime.rollout.base_types import finalize_rollout_groups


async def generate_stored_batch(args, rollout_id, data_source, completed_groups):
    refs = []
    async for group in completed_groups:
        ref = await publish_rollout_async(
            group, args, rollout_id, group=True, controller=data_source.controller
        )
        refs.append(ref)
    return finalize_rollout_groups(args, rollout_id, refs, controller=data_source.controller)
DOC-010 · docs/en/get_started/customization.md:115

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象

async def custom_generate(args, sample: Sample, sampling_params: dict) -> Sample | list[Sample]
DOC-011 · docs/en/get_started/customization.md:130

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象 沿当前调用链等待与恢复

import copy

from slime.utils.types import Sample


async def custom_generate(args, sample: Sample, sampling_params: dict) -> list[Sample]:
    segments = await run_agent_and_split_segments(args, sample, sampling_params)
    rollout_id = sample.rollout_id if sample.rollout_id is not None else sample.index

    samples: list[Sample] = []
    for segment in segments:
        s = copy.copy(sample)
        s.tokens = segment.tokens
        s.response = segment.response
        s.response_length = segment.response_length
        s.loss_mask = segment.loss_mask
        s.reward = segment.reward
        s.status = Sample.Status.COMPLETED
        s.rollout_id = rollout_id
        samples.append(s)
    return samples
DOC-012 · docs/en/get_started/customization.md:167

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象

async def custom_rm(args, sample: Sample) -> float
DOC-013 · docs/en/get_started/customization.md:172

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象

async def batched_custom_rm(args, samples: list[Sample]) -> list[float]
DOC-014 · docs/en/get_started/quick_start.md:500

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象 沿当前调用链等待与恢复

async def generate(args, sample: Sample, sampling_params) -> Sample:
    # ... initialization ...
    prompt, full_response, loss_masks = sample.prompt, "", []

    for _ in range(max_turns):
        # 1. Model generates action
        model_output = await call_sglang(prompt + full_response, ...)
        # ... tokenization and appending ...
        loss_masks += [1] * len(model_tokens) # loss_mask = 1
        full_response += model_output

        # 2. Parse and execute action
        action, content = parse_action(model_output)
        if action == "search":
            # 3 & 4. Get and append observation results
            tool_output = await google_search(content)
            # ... tokenization and appending ...
            loss_masks += [0] * len(tool_tokens) # loss_mask = 0
            full_response += tool_output

        elif action == "answer":
            break # end loop

    # 7. Fill and return Sample object
    sample.response = full_response
    sample.tokens = ...
    sample.loss_mask = loss_masks
    return sample
DOC-015 · docs/en/get_started/usage.md:356

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象 沿当前调用链等待与恢复

    async def generate(args, sample: Sample, sampling_params) -> Sample:
        global TOKENIZER
        if TOKENIZER is None:
            TOKENIZER = AutoTokenizer.from_pretrained(args.hf_checkpoint, trust_remote_code=True)

        # send request to router
        output = await post(
            f"http://{args.sglang_router_ip}:{args.sglang_router_port}/generate",
            {
                "text": sample.prompt,
                "sampling_params": sampling_params,
            }
        )

        prompt_tokens_ids = TOKENIZER(sample.prompt, add_special_tokens=False)["input_ids"]
        response_token_ids = TOKENIZER(output["text"], add_special_tokens=False)["input_ids"]

        # set sample
        sample.tokens = prompt_tokens_ids + response_token_ids
        sample.response_length = len(response_token_ids)
        finish_reason = output["meta_info"]["finish_reason"]["type"]
        if finish_reason == "length":
            sample.status = Sample.Status.TRUNCATED
        elif finish_reason == "abort":
            sample.status = Sample.Status.ABORTED
        else:
            sample.status = Sample.Status.COMPLETED
        sample.response = output["text"]

        return sample
DOC-016 · docs/zh/advanced/sglang-config.md:173

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象 沿当前调用链等待与恢复

from slime.rollout.sglang_rollout import get_model_url
from slime.utils.http_utils import post

async def my_generate(args, sample, sampling_params):
    # 路由到 actor 模型(默认)
    actor_url = get_model_url(args, "actor", "/generate")
    output = await post(actor_url, {"text": sample.prompt, "sampling_params": sampling_params})
    
    # 路由到 reference 模型
    ref_url = get_model_url(args, "ref", "/generate")
    ref_output = await post(ref_url, {"text": sample.prompt, "sampling_params": sampling_params})
    
    # 路由到 reward 模型(如 OpenAI 兼容 API)
    reward_url = get_model_url(args, "reward", "/v1/chat/completions")
    reward_output = await post(reward_url, {...})
    
    ...
DOC-017 · docs/zh/advanced/sglang-config.md:401

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象 沿当前调用链等待与恢复

from slime.rollout.sglang_rollout import get_model_url
from slime.utils.http_utils import post

async def generate_with_models(args, sample, sampling_params):
    """使用 actor 生成,用 reward 模型打分,与 reference 比较。"""
    
    # 从 actor 生成
    actor_url = get_model_url(args, "actor", "/generate")
    actor_output = await post(actor_url, {
        "text": sample.prompt,
        "sampling_params": sampling_params,
        "return_logprob": True,
    })
    
    # 获取 reference logprobs 用于 KL penalty
    ref_url = get_model_url(args, "ref", "/generate")
    ref_output = await post(ref_url, {
        "text": sample.prompt + actor_output["text"],
        "sampling_params": {"max_new_tokens": 0, "temperature": 0},
        "return_logprob": True,
    })
    
    # 用 reward 模型打分
    reward_url = get_model_url(args, "reward", "/v1/chat/completions")
    reward_output = await post(reward_url, {
        "model": "reward",
        "messages": [{"role": "user", "content": sample.prompt + actor_output["text"]}],
    })
    
    # ... 处理输出并返回 Sample
DOC-018 · docs/zh/developer_guide/trace.md:60

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象

from slime.observability.trace_utils import trace_function


@trace_function("generate_and_rm", target="sample")
async def generate_and_rm(args, sample, sampling_params, evaluation=False):
    ...


@trace_function(
    "generate_and_rm_group",
    target="group",
    attrs_getter=lambda args, group, sampling_params, evaluation=False: {"group_size": len(group)},
)
async def generate_and_rm_group(args, group, sampling_params, evaluation=False):
    ...
DOC-019 · docs/zh/developer_guide/trace.md:90

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象

@trace_function(
    "custom_rollout_batch",
    target="samples",
    attrs_getter=lambda samples, **_: {"batch_size": len(samples)},
)
async def custom_rollout_batch(samples, **kwargs):
    ...
DOC-020 · docs/zh/developer_guide/trace.md:107

固定版本的原文 · 对应讲解: 沿当前调用链等待与恢复

from slime.observability.trace_utils import build_sglang_meta_trace_attrs, trace_span

with trace_span(sample, "sglang_generate") as span:
    output = await post(url, payload)
    span.update(build_sglang_meta_trace_attrs(output["meta_info"]))
DOC-021 · docs/zh/get_started/agent.md:41

固定版本的原文 · 对应讲解: 沿当前调用链等待与恢复

from slime.agent.adapters import AnthropicAdapter

adapter = AnthropicAdapter(
    tokenizer=tokenizer,
    sglang_url=sglang_url,
    tool_parser=tool_parser,
    reasoning_parser=reasoning_parser,
)

adapter.open_session(session_id, sampling_defaults=sampling_params)
# Agent client 向 adapter.app 发送请求。
segments = await adapter.finish_session(session_id)
DOC-022 · docs/zh/get_started/customization.md:72

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象 异步迭代与异步生成器 沿当前调用链等待与恢复

from slime.data.transport import publish_rollout_async
from slime.rollout.base_types import finalize_rollout_groups


async def generate_stored_batch(args, rollout_id, data_source, completed_groups):
    refs = []
    async for group in completed_groups:
        ref = await publish_rollout_async(
            group, args, rollout_id, group=True, controller=data_source.controller
        )
        refs.append(ref)
    return finalize_rollout_groups(args, rollout_id, refs, controller=data_source.controller)
DOC-023 · docs/zh/get_started/customization.md:100

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象

async def custom_generate(args, sample: Sample, sampling_params: dict) -> Sample | list[Sample]
DOC-024 · docs/zh/get_started/customization.md:115

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象 沿当前调用链等待与恢复

import copy

from slime.utils.types import Sample


async def custom_generate(args, sample: Sample, sampling_params: dict) -> list[Sample]:
    segments = await run_agent_and_split_segments(args, sample, sampling_params)
    rollout_id = sample.rollout_id if sample.rollout_id is not None else sample.index

    samples: list[Sample] = []
    for segment in segments:
        s = copy.copy(sample)
        s.tokens = segment.tokens
        s.response = segment.response
        s.response_length = segment.response_length
        s.loss_mask = segment.loss_mask
        s.reward = segment.reward
        s.status = Sample.Status.COMPLETED
        s.rollout_id = rollout_id
        samples.append(s)
    return samples
DOC-025 · docs/zh/get_started/customization.md:152

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象

async def custom_rm(args, sample: Sample) -> float
DOC-026 · docs/zh/get_started/customization.md:157

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象

async def batched_custom_rm(args, samples: list[Sample]) -> list[float]
DOC-027 · docs/zh/get_started/quick_start.md:506

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象 沿当前调用链等待与恢复

async def generate(args, sample: Sample, sampling_params) -> Sample:
    # ... 初始化 ...
    prompt, full_response, loss_masks = sample.prompt, "", []

    for _ in range(max_turns):
        # 1. 模型生成动作
        model_output = await call_sglang(prompt + full_response, ...)
        # ... tokenization and appending ...
        loss_masks += [1] * len(model_tokens) # loss_mask = 1
        full_response += model_output

        # 2. 解析并执行动作
        action, content = parse_action(model_output)
        if action == "search":
            # 3 & 4. 获取并追加观察结果
            tool_output = await google_search(content)
            # ... tokenization and appending ...
            loss_masks += [0] * len(tool_tokens) # loss_mask = 0
            full_response += tool_output

        elif action == "answer":
            break # 结束循环

    # 7. 填充并返回 Sample 对象
    sample.response = full_response
    sample.tokens = ...
    sample.loss_mask = loss_masks
    return sample
DOC-028 · docs/zh/get_started/usage.md:358

固定版本的原文 · 对应讲解: 定义协程函数与创建协程对象 沿当前调用链等待与恢复

  async def generate(args, sample: Sample, sampling_params) -> Sample:
      global TOKENIZER
      if TOKENIZER is None:
          TOKENIZER = AutoTokenizer.from_pretrained(args.hf_checkpoint, trust_remote_code=True)
  
      # send request to router
      output = await post(
          f"http://{args.sglang_router_ip}:{args.sglang_router_port}/generate",
          {
              "text": sample.prompt,
              "sampling_params": sampling_params,
          }
      )
  
      prompt_tokens_ids = TOKENIZER(sample.prompt, add_special_tokens=False)["input_ids"]
      response_token_ids = TOKENIZER(output["text"], add_special_tokens=False)["input_ids"]
  
      # set sample
      sample.tokens = prompt_tokens_ids + response_token_ids
      sample.response_length = len(response_token_ids)
      finish_reason = output["meta_info"]["finish_reason"]["type"]
      if finish_reason == "length":
          sample.status = Sample.Status.TRUNCATED
      elif finish_reason == "abort":
          sample.status = Sample.Status.ABORTED
      else:
          sample.status = Sample.Status.COMPLETED
      sample.response = output["text"]
  
      return sample
DOC-029 · examples/coding_agent_rl/README.md:194

固定版本的原文 · 对应讲解: 异步进入、退出与资源回收 沿当前调用链等待与恢复

await sb.exec(cmd, user=..., check=..., timeout=...)
await sb.write_file(sandbox_path, content_or_host_path, user=...)
await sb.read_file(sandbox_path, user=...)
async with E2BSandbox(...) as sb: ...

下载与重新核对

这份对照不声称覆盖其他 Slime 版本、动态生成的代码或 Python 标准库里本仓库未使用的所有接口。更新源码后需要重新扫描并补齐新增映射,不能沿用旧的“无缺项”结论。

回到学习顺序