Skip to content

claude agent sdk query cannot pass dict to options #446

@musnows

Description

@musnows

I'm following the example in https://platform.claude.com/docs/zh-CN/agent-sdk/structured-outputs#python

from pydantic import BaseModel
from claude_agent_sdk import query

class Issue(BaseModel):
    severity: str  # 'low', 'medium', 'high'
    description: str
    file: str

class AnalysisResult(BaseModel):
    summary: str
    issues: list[Issue]
    score: int

# 在查询中使用
async def main():
    async for message in query(
        prompt="Analyze the codebase for security issues",
        options={
            "output_format": {
                "type": "json_schema",
                "schema": AnalysisResult.model_json_schema()
            }
        }
    ):
        if hasattr(message, 'structured_output'):
            # 验证并获取完全类型化的结果
            result = AnalysisResult.model_validate(message.structured_output)
            print(f"Score: {result.score}")
            print(f"Found {len(result.issues)} issues")
            for issue in result.issues:
                print(f"[{issue.severity}] {issue.file}: {issue.description}")

if __name__ == '__main__':
    import asyncio
    asyncio.run(main())

It errors

Traceback (most recent call last):
  File "/Users/mu/data/code/mcp/code_index_agent/test.py", line 38, in <module>
    asyncio.run(main())
  File "/opt/homebrew/Cellar/[email protected]/3.11.13/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "/opt/homebrew/Cellar/[email protected]/3.11.13/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/Cellar/[email protected]/3.11.13/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/base_events.py", line 654, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "/Users/mu/data/code/mcp/code_index_agent/test.py", line 18, in main
    async for message in query(
  File "/Users/mu/data/code/mcp/code_index_agent/.venv/lib/python3.11/site-packages/claude_agent_sdk/query.py", line 123, in query
    async for message in client.process_query(
  File "/Users/mu/data/code/mcp/code_index_agent/.venv/lib/python3.11/site-packages/claude_agent_sdk/_internal/client.py", line 53, in process_query
    if options.can_use_tool:
       ^^^^^^^^^^^^^^^^^^^^
AttributeError: 'dict' object has no attribute 'can_use_tool'

the right way to do it is passing ClaudeAgentOptions object to option instead of dict

from pydantic import BaseModel
from claude_agent_sdk import query, ClaudeAgentOptions
from dotenv import load_dotenv
load_dotenv(override=True)

class Issue(BaseModel):
    severity: str  # 'low', 'medium', 'high'
    description: str
    file: str

class AnalysisResult(BaseModel):
    summary: str
    issues: list[Issue]
    score: int

async def main():
    # 在查询中使用
    async for message in query(
        prompt="output an example of AnalysisResult",
        options=ClaudeAgentOptions(
            output_format= {
                "type": "json_schema",
                "schema": AnalysisResult.model_json_schema()
            }
        )
    ):
        print(message)
        if hasattr(message, 'structured_output'):
            # 验证并获取完全类型化的结果
            result = AnalysisResult.model_validate(message.structured_output)
            print(f"Score: {result.score}")
            print(f"Found {len(result.issues)} issues")
            for issue in result.issues:
                print(f"[{issue.severity}] {issue.file}: {issue.description}")

if __name__ == '__main__':
    import asyncio
    asyncio.run(main())

Is the example in the document outdated or is my SDK version incorrect?

claude-agent-sdk 0.1.18
Python 3.11.13

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingdocumentationImprovements or additions to documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions