docs/developers/sdk-python.md
qwen-code-sdkqwen-code-sdk is an experimental Python SDK for Qwen Code. v1 targets the
existing stream-json CLI protocol and keeps the transport surface small and
testable.
qwen-code-sdkqwen_code_sdk>=3.10qwen executable is required in v1pip install qwen-code-sdk
If qwen is not on PATH, pass path_to_qwen_executable explicitly.
import asyncio
from qwen_code_sdk import is_sdk_result_message, query
async def main() -> None:
result = query(
"Explain the repository structure.",
{
"cwd": "/path/to/project",
"path_to_qwen_executable": "qwen",
},
)
async for message in result:
if is_sdk_result_message(message):
print(message["result"])
asyncio.run(main())
query(prompt, options=None) -> Queryquery_sync(prompt, options=None) -> SyncQueryprompt supports either:
str for single-turn requestsAsyncIterable[SDKUserMessage] for multi-turn streamsQueryclose()interrupt()set_model(model)set_permission_mode(mode)supported_commands()mcp_server_status()get_session_id()is_closed()QueryOptionsSupported options in v1:
cwdmodelpath_to_qwen_executablepermission_modecan_use_toolenvsystem_promptappend_system_promptdebugmax_session_turnscore_toolsexclude_toolsallowed_toolsauth_typeinclude_partial_messagesresumecontinue_sessionsession_idtimeoutmcp_serversstderrSession argument priority is fixed as:
resumecontinue_sessionsession_idWhen the CLI emits a can_use_tool control request, the SDK routes it through
can_use_tool(tool_name, tool_input, context).
cancel_event, suggestions, and blocked_pathcan_use_tool must be async with 3 positional arguments;
stderr must accept 1 positional string argumentValidationError: invalid options, invalid UUIDs, unsupported combinationsControlRequestTimeoutError: initialize, interrupt, or other control request
timed outProcessExitError: CLI exited non-zeroAbortError: control request or session was cancelledIf the SDK cannot start the CLI:
qwen --version works in the target environmentpath_to_qwen_executable if your shell uses nvm, pyenv, or other
non-standard PATH setupdebug=True or stderr=print to surface CLI stderr while debuggingIf session control calls time out:
qwen version supports --input-format stream-jsontimeout.control_requestRepository-level helper commands:
npm run test:sdk:pythonnpm run lint:sdk:pythonnpm run typecheck:sdk:pythonnpm run smoke:sdk:python -- --qwen qwenFor a real runtime check (actual qwen process + real model call), run from
the repository root. The npm helper uses python3, so ensure it resolves to a
Python >=3.10 interpreter:
npm run smoke:sdk:python -- --qwen qwen
This script runs:
supported_commands, permission mode updates)query_sync queryIt prints JSON and returns non-zero on failure.