Experimental Python SDK for programmatic access to Qwen Code through the
stream-json protocol.
pip install qwen-code-sdk- Python
>=3.10 - External
qwenCLI installed and available inPATH
You can also point the SDK at an explicit CLI binary or script with
path_to_qwen_executable.
import asyncio
from qwen_code_sdk import is_sdk_result_message, query
async def main() -> None:
result = query(
"List the top-level packages in this repository.",
{
"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())from qwen_code_sdk import query_sync
with query_sync(
"Say hello",
{
"path_to_qwen_executable": "qwen",
},
) as result:
for message in result:
print(message)query(prompt, options=None) -> Queryquery_sync(prompt, options=None) -> SyncQueryQuery.close(),interrupt(),set_model(),set_permission_mode()Query.supported_commands(),mcp_server_status(),get_session_id()
prompt accepts either a single str or an AsyncIterable[SDKUserMessage]
for multi-turn sessions.
from qwen_code_sdk import query
async def can_use_tool(tool_name, tool_input, context):
if tool_name == "write_file":
return {"behavior": "deny", "message": "Writes disabled in this app"}
return {"behavior": "allow", "updatedInput": tool_input}
result = query(
"Create hello.txt",
{
"path_to_qwen_executable": "qwen",
"can_use_tool": can_use_tool,
},
)The callback defaults to deny. If it does not return within 60 seconds, the SDK auto-denies the tool request.
The context argument includes cancel_event, suggestions, and
blocked_path when the CLI provides a path-specific permission target.
can_use_tool must be an async def callback accepting
(tool_name, tool_input, context). stderr must accept a single str.
ValidationError: invalid query options or malformed session identifiersControlRequestTimeoutError: CLI control operation exceeded timeoutProcessExitError:qwenexited with a non-zero codeAbortError: query or control request was cancelled
0.1.x is intentionally narrow:
- Uses external
qwenCLI via process transport - Targets
stream-jsonparity with the TypeScript SDK core flow - Does not yet implement ACP transport
- Does not yet embed MCP servers inside the SDK process
See developer documentation for more detail.