> ## Documentation Index
> Fetch the complete documentation index at: https://docs.qoder.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 多轮对话

要在同一会话里发多条用户消息，使用 `QoderSDKClient`——它维护长连接，可以根据模型回复决定下一句。一次性、无状态查询用 `query()`，见 [快速开始](/zh/cli/sdk/python/quick-start)。

<div id="多消息会话" />

## 多消息会话

每次调用 `client.query(...)` 追加一轮输入，再用 `client.receive_response()` 消费到本轮回复结束：

```python theme={null}
import anyio

from qoder_agent_sdk import (
    AssistantMessage,
    QoderAgentOptions,
    QoderSDKClient,
    ResultMessage,
    TextBlock,
    access_token_from_env,
)


async def main():
    options = QoderAgentOptions(auth=access_token_from_env())

    async with QoderSDKClient(options=options) as client:
        await client.query("What's the capital of France?")
        async for msg in client.receive_response():
            if isinstance(msg, AssistantMessage):
                for block in msg.content:
                    if isinstance(block, TextBlock):
                        print(f"Assistant: {block.text}")

        # 根据上一轮回复决定下一句
        await client.query("What's the population of that city?")
        async for msg in client.receive_response():
            if isinstance(msg, ResultMessage):
                print(f"Done: {msg.subtype}")


anyio.run(main)
```

<div id="管理会话生命周期" />

## 管理会话生命周期

`QoderSDKClient` 的连接生命周期由调用方掌握。两种管理方式：

<div id="自动管理推荐" />

### 自动管理（推荐）

适合会话生命周期跟某个函数 / 代码块绑定的场景：

```python theme={null}
async with QoderSDKClient(options=options) as client:
    await client.query("Hello")
    async for msg in client.receive_response():
        ...
# 离开 async with 作用域自动 disconnect
```

<div id="手动管理" />

### 手动管理

适合 client 被长生命周期对象持有、或需要从外部条件（超时、用户取消等）触发关闭的场景：

```python theme={null}
client = QoderSDKClient(options=options)
await client.connect()

try:
    await client.query("Hello")
    async for msg in client.receive_response():
        ...
finally:
    await client.disconnect()
```
