pydantic-claude-code 0.7.1__tar.gz → 0.7.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/PKG-INFO +10 -6
  2. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/README.md +9 -5
  3. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/pyproject.toml +1 -1
  4. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/src/pydantic_ai_claude_code/__init__.py +1 -1
  5. pydantic_claude_code-0.7.3/src/pydantic_ai_claude_code/model.py +141 -0
  6. pydantic_claude_code-0.7.3/tests/test_model.py +146 -0
  7. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/uv.lock +1 -1
  8. pydantic_claude_code-0.7.1/src/pydantic_ai_claude_code/model.py +0 -111
  9. pydantic_claude_code-0.7.1/tests/test_model.py +0 -59
  10. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/.github/workflows/ci.yml +0 -0
  11. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/.github/workflows/publish.yml +0 -0
  12. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/.gitignore +0 -0
  13. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/LICENSE +0 -0
  14. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/examples/basic.py +0 -0
  15. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/install.sh +0 -0
  16. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/scripts/sync_gist.sh +0 -0
  17. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/src/pydantic_ai_claude_code/__main__.py +0 -0
  18. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/src/pydantic_ai_claude_code/auth.py +0 -0
  19. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/src/pydantic_ai_claude_code/clai2.py +0 -0
  20. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/src/pydantic_ai_claude_code/config.py +0 -0
  21. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/src/pydantic_ai_claude_code/credentials.py +0 -0
  22. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/src/pydantic_ai_claude_code/flow.py +0 -0
  23. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/src/pydantic_ai_claude_code/provider.py +0 -0
  24. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/src/pydantic_ai_claude_code/py.typed +0 -0
  25. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/src/pydantic_ai_claude_code/storage.py +0 -0
  26. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/src/pydantic_ai_claude_code/updates.py +0 -0
  27. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/tests/conftest.py +0 -0
  28. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/tests/test_callback_server.py +0 -0
  29. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/tests/test_clai2.py +0 -0
  30. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/tests/test_credentials.py +0 -0
  31. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/tests/test_flow.py +0 -0
  32. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/tests/test_install.py +0 -0
  33. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/tests/test_integration.py +0 -0
  34. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/tests/test_keyring_store.py +0 -0
  35. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/tests/test_provider.py +0 -0
  36. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/tests/test_refresh.py +0 -0
  37. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/tests/test_storage.py +0 -0
  38. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.3}/tests/test_updates.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pydantic-claude-code
3
- Version: 0.7.1
3
+ Version: 0.7.3
4
4
  Summary: Use your Claude Code subscription from a Pydantic AI Agent or CLAI2, with full tool support
5
5
  Project-URL: Source, https://gist.github.com/mpfaffenberger/bd75c7b424ffdc6d81645bfe7de822d3
6
6
  Project-URL: Homepage, https://pypi.org/project/pydantic-claude-code/
@@ -201,10 +201,14 @@ provider. Instead of a `claude-code:` model string, construct
201
201
  `ClaudeCodeModel('claude-fable-5-1')` directly; it connects itself to a
202
202
  `ClaudeCodeProvider` by default.
203
203
 
204
- `ClaudeCodeModel` enables prompt caching with a **1-hour TTL** by default. Override it with
205
- `settings=AnthropicModelSettings(anthropic_cache="5m")`, or disable default caching with
206
- `settings=AnthropicModelSettings(anthropic_cache=False)`. Per-request settings take precedence.
207
- Tool-definition, static-instruction, and latest-tool-call breakpoints use Pydantic AI's caching implementation.
204
+ `ClaudeCodeModel` enables prompt caching with a **1-hour TTL** by default, on the conversation and on the
205
+ static prefix: the tool definitions and the instructions get breakpoints of their own, so a new conversation
206
+ reads the prefix earlier ones cached instead of writing it again at the 1-hour price. Passing any
207
+ `anthropic_cache*` setting to the model replaces this default as a whole: for example
208
+ `settings=AnthropicModelSettings(anthropic_cache="5m")` caches only the conversation, for 5 minutes, and
209
+ `settings=AnthropicModelSettings(anthropic_cache=False)` turns caching off. Per-request settings take precedence
210
+ key by key, so to turn caching off for one request, set `anthropic_cache`, `anthropic_cache_instructions` and
211
+ `anthropic_cache_tool_definitions` to `False`.
208
212
 
209
213
  ### Quick start
210
214
 
@@ -336,7 +340,7 @@ uv run pytest
336
340
 
337
341
  To release, bump `version` in `pyproject.toml` and `__version__` in
338
342
  `src/pydantic_ai_claude_code/__init__.py` (a test checks they match), merge, and
339
- push a matching tag (`git tag v0.7.1 && git push origin v0.7.1`). The `Publish` workflow tests,
343
+ push a matching tag (`git tag v0.7.3 && git push origin v0.7.3`). The `Publish` workflow tests,
340
344
  builds, and uploads it to PyPI with the `PYPI_API_TOKEN` repository secret. Then run
341
345
  `scripts/sync_gist.sh` to publish the release to the install gist, which is what the one-liner and the
342
346
  update notice install from.
@@ -172,10 +172,14 @@ provider. Instead of a `claude-code:` model string, construct
172
172
  `ClaudeCodeModel('claude-fable-5-1')` directly; it connects itself to a
173
173
  `ClaudeCodeProvider` by default.
174
174
 
175
- `ClaudeCodeModel` enables prompt caching with a **1-hour TTL** by default. Override it with
176
- `settings=AnthropicModelSettings(anthropic_cache="5m")`, or disable default caching with
177
- `settings=AnthropicModelSettings(anthropic_cache=False)`. Per-request settings take precedence.
178
- Tool-definition, static-instruction, and latest-tool-call breakpoints use Pydantic AI's caching implementation.
175
+ `ClaudeCodeModel` enables prompt caching with a **1-hour TTL** by default, on the conversation and on the
176
+ static prefix: the tool definitions and the instructions get breakpoints of their own, so a new conversation
177
+ reads the prefix earlier ones cached instead of writing it again at the 1-hour price. Passing any
178
+ `anthropic_cache*` setting to the model replaces this default as a whole: for example
179
+ `settings=AnthropicModelSettings(anthropic_cache="5m")` caches only the conversation, for 5 minutes, and
180
+ `settings=AnthropicModelSettings(anthropic_cache=False)` turns caching off. Per-request settings take precedence
181
+ key by key, so to turn caching off for one request, set `anthropic_cache`, `anthropic_cache_instructions` and
182
+ `anthropic_cache_tool_definitions` to `False`.
179
183
 
180
184
  ### Quick start
181
185
 
@@ -307,7 +311,7 @@ uv run pytest
307
311
 
308
312
  To release, bump `version` in `pyproject.toml` and `__version__` in
309
313
  `src/pydantic_ai_claude_code/__init__.py` (a test checks they match), merge, and
310
- push a matching tag (`git tag v0.7.1 && git push origin v0.7.1`). The `Publish` workflow tests,
314
+ push a matching tag (`git tag v0.7.3 && git push origin v0.7.3`). The `Publish` workflow tests,
311
315
  builds, and uploads it to PyPI with the `PYPI_API_TOKEN` repository secret. Then run
312
316
  `scripts/sync_gist.sh` to publish the release to the install gist, which is what the one-liner and the
313
317
  update notice install from.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "pydantic-claude-code"
7
- version = "0.7.1"
7
+ version = "0.7.3"
8
8
  description = "Use your Claude Code subscription from a Pydantic AI Agent or CLAI2, with full tool support"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10,<3.15"
@@ -26,7 +26,7 @@ from .model import ClaudeCodeModel
26
26
  from .provider import ClaudeCodeProvider
27
27
  from .storage import ClaudeCodeTokenStore, KeyringTokenStore, default_auth_path, default_store
28
28
 
29
- __version__ = "0.7.1"
29
+ __version__ = "0.7.3"
30
30
  """Matches `version` in pyproject.toml (a test checks), so a copied folder knows its release."""
31
31
 
32
32
 
@@ -0,0 +1,141 @@
1
+ """The Claude Code model: an `AnthropicModel` whose system prompt always opens with the Claude Code persona."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import AsyncGenerator, Iterator
6
+ from contextlib import asynccontextmanager, contextmanager
7
+ from typing import Any
8
+
9
+ from anthropic.types.beta import BetaMessageParam, BetaTextBlockParam
10
+ from pydantic_ai import RunContext
11
+ from pydantic_ai.exceptions import ModelAPIError
12
+ from pydantic_ai.messages import ModelMessage, ModelResponse
13
+ from pydantic_ai.models import ModelRequestParameters, StreamedResponse
14
+ from pydantic_ai.models.anthropic import AnthropicModel, AnthropicModelSettings
15
+ from pydantic_ai.providers import Provider
16
+ from pydantic_ai.settings import ModelSettings
17
+
18
+ from . import config
19
+ from .auth import ClaudeCodeSignInExpiredError
20
+
21
+ _CACHE_SETTINGS = (
22
+ "anthropic_cache",
23
+ "anthropic_cache_instructions",
24
+ "anthropic_cache_tool_definitions",
25
+ "anthropic_cache_messages",
26
+ )
27
+ """The explicit Anthropic cache settings. Any one of them replaces the default caching as a whole."""
28
+
29
+
30
+ def _default_cache_settings(settings: ModelSettings | None) -> AnthropicModelSettings:
31
+ """One-hour caching of the conversation and of the static prefix, unless `settings` choose caching themselves.
32
+
33
+ Pydantic AI's unified `cache` setting, which CLAI sends, puts breakpoints after the tool definitions and the
34
+ instructions, so every new conversation reads that shared prefix instead of writing it again. An explicit
35
+ `anthropic_cache*` setting turns the unified one off, so a default naming only `anthropic_cache` would leave
36
+ just the conversation breakpoint: each new session would write its whole prefix at the one-hour price.
37
+ """
38
+ if settings and any(key in settings for key in _CACHE_SETTINGS):
39
+ return AnthropicModelSettings()
40
+ return AnthropicModelSettings(
41
+ anthropic_cache="1h", anthropic_cache_instructions="1h", anthropic_cache_tool_definitions="1h"
42
+ )
43
+
44
+
45
+ class ClaudeCodeModel(AnthropicModel):
46
+ """AnthropicModel whose system prompt opens with the Claude Code persona.
47
+
48
+ The subscription backend expects the persona as the first `system` block, on its own. That is enforced
49
+ on every request as it is built, not in message history, which compaction rewrites: see `_persona_first`.
50
+ """
51
+
52
+ def __init__(
53
+ self,
54
+ model_name: str,
55
+ *,
56
+ provider: Provider[Any] | None = None,
57
+ settings: ModelSettings | None = None,
58
+ **kwargs: Any,
59
+ ) -> None:
60
+ """Initialize a Claude Code model.
61
+
62
+ Args:
63
+ model_name: The model name to use, e.g. `'claude-fable-5-1'`.
64
+ provider: The provider to authenticate with. Defaults to a
65
+ `ClaudeCodeProvider` backed by the default token store.
66
+ """
67
+ if provider is None:
68
+ from .provider import ClaudeCodeProvider
69
+
70
+ provider = ClaudeCodeProvider()
71
+ super().__init__(
72
+ model_name, provider=provider, settings={**_default_cache_settings(settings), **(settings or {})}, **kwargs
73
+ )
74
+
75
+ async def _map_message(
76
+ self,
77
+ messages: list[ModelMessage],
78
+ model_request_parameters: ModelRequestParameters,
79
+ model_settings: AnthropicModelSettings,
80
+ ) -> tuple[str | list[BetaTextBlockParam], list[BetaMessageParam]]:
81
+ system, anthropic_messages = await super()._map_message(messages, model_request_parameters, model_settings)
82
+ return _persona_first(system), anthropic_messages
83
+
84
+ async def request(
85
+ self,
86
+ messages: list[ModelMessage],
87
+ model_settings: ModelSettings | None,
88
+ model_request_parameters: ModelRequestParameters,
89
+ ) -> ModelResponse:
90
+ with _surface_expired_sign_in():
91
+ return await super().request(messages, model_settings, model_request_parameters)
92
+
93
+ @asynccontextmanager
94
+ async def request_stream(
95
+ self,
96
+ messages: list[ModelMessage],
97
+ model_settings: ModelSettings | None,
98
+ model_request_parameters: ModelRequestParameters,
99
+ run_context: RunContext[Any] | None = None,
100
+ ) -> AsyncGenerator[StreamedResponse]:
101
+ with _surface_expired_sign_in():
102
+ async with super().request_stream(
103
+ messages, model_settings, model_request_parameters, run_context
104
+ ) as response:
105
+ yield response
106
+
107
+
108
+ @contextmanager
109
+ def _surface_expired_sign_in() -> Iterator[None]:
110
+ """Re-raise an expired sign-in that the SDK reported as `Connection error.`."""
111
+ try:
112
+ yield
113
+ except ModelAPIError as exc:
114
+ cause: BaseException | None = exc
115
+ while cause is not None:
116
+ if isinstance(cause, ClaudeCodeSignInExpiredError):
117
+ raise cause from exc
118
+ cause = cause.__cause__
119
+ raise
120
+
121
+
122
+ def _persona_first(system: str | list[BetaTextBlockParam]) -> list[BetaTextBlockParam]:
123
+ """`system` as blocks, the first being the persona alone and no other block repeating it.
124
+
125
+ History cannot be trusted to keep the persona in place: `AnthropicModel` joins all of a run's opening
126
+ `SystemPromptPart`s into one block, and compaction rewrites them, which once left a conversation summary
127
+ inside the persona's block. So every request is fixed up here, whatever its history holds. A cache
128
+ breakpoint on a block that held only the persona stays with the persona.
129
+ """
130
+ persona = BetaTextBlockParam(type="text", text=config.CLAUDE_CODE_SYSTEM_PROMPT)
131
+ rest: list[BetaTextBlockParam] = []
132
+ for block in [BetaTextBlockParam(type="text", text=system)] if isinstance(system, str) else system:
133
+ pieces = (piece.strip() for piece in block["text"].split(config.CLAUDE_CODE_SYSTEM_PROMPT))
134
+ text = "\n\n".join(piece for piece in pieces if piece)
135
+ if text:
136
+ kept = block.copy()
137
+ kept["text"] = text
138
+ rest.append(kept)
139
+ elif "cache_control" in block:
140
+ (rest[-1] if rest else persona)["cache_control"] = block["cache_control"]
141
+ return [persona, *rest]
@@ -0,0 +1,146 @@
1
+ """`ClaudeCodeModel`: its caching default, and the persona every request opens its system prompt with."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import timedelta
6
+ from typing import Any
7
+
8
+ import pytest
9
+ from anthropic.types.beta import BetaTextBlockParam
10
+ from pydantic_ai import Agent
11
+ from pydantic_ai.messages import ModelMessage, ModelRequest, ModelResponse, SystemPromptPart, TextPart, UserPromptPart
12
+ from pydantic_ai.models.anthropic import AnthropicModelSettings
13
+ from pydantic_ai.providers.anthropic import AnthropicProvider
14
+
15
+ from conftest import MessagesServer
16
+ from pydantic_ai_claude_code import config
17
+ from pydantic_ai_claude_code.credentials import ClaudeCodeCredentials
18
+ from pydantic_ai_claude_code.model import ClaudeCodeModel, _default_cache_settings, _persona_first
19
+ from pydantic_ai_claude_code.provider import ClaudeCodeProvider
20
+
21
+
22
+ @pytest.mark.parametrize(
23
+ ("settings", "expected"),
24
+ [
25
+ (None, timedelta(hours=1)),
26
+ (AnthropicModelSettings(anthropic_cache="5m"), timedelta(minutes=5)),
27
+ (AnthropicModelSettings(anthropic_cache=False), None),
28
+ (AnthropicModelSettings(anthropic_cache_messages="1h"), timedelta(hours=1)),
29
+ ],
30
+ )
31
+ def test_cache_retention_defaults_to_one_hour(
32
+ settings: AnthropicModelSettings | None, expected: timedelta | None
33
+ ) -> None:
34
+ model = ClaudeCodeModel("claude-sonnet-4-6", provider=AnthropicProvider(api_key="test-key"), settings=settings)
35
+ assert model.resolve_cache_retention(None) == expected
36
+ # Per-request settings win key by key, and the longest active breakpoint sets the retention.
37
+ assert model.resolve_cache_retention(
38
+ AnthropicModelSettings(
39
+ anthropic_cache="5m",
40
+ anthropic_cache_instructions="5m",
41
+ anthropic_cache_tool_definitions="5m",
42
+ anthropic_cache_messages=False,
43
+ )
44
+ ) == timedelta(minutes=5)
45
+
46
+
47
+ ONE_HOUR = {"type": "ephemeral", "ttl": "1h"}
48
+
49
+
50
+ def test_the_default_caches_the_static_prefix_as_well_as_the_conversation() -> None:
51
+ assert _default_cache_settings(None) == AnthropicModelSettings(
52
+ anthropic_cache="1h", anthropic_cache_instructions="1h", anthropic_cache_tool_definitions="1h"
53
+ )
54
+
55
+
56
+ @pytest.mark.parametrize(
57
+ "settings",
58
+ [
59
+ AnthropicModelSettings(anthropic_cache="5m"),
60
+ AnthropicModelSettings(anthropic_cache=False),
61
+ AnthropicModelSettings(anthropic_cache_instructions=False),
62
+ AnthropicModelSettings(anthropic_cache_tool_definitions="5m"),
63
+ AnthropicModelSettings(anthropic_cache_messages="1h"),
64
+ ],
65
+ )
66
+ def test_any_explicit_cache_setting_replaces_the_whole_default(settings: AnthropicModelSettings) -> None:
67
+ model = ClaudeCodeModel("claude-sonnet-4-6", provider=AnthropicProvider(api_key="test-key"), settings=settings)
68
+ assert model.settings == settings
69
+
70
+
71
+ async def test_a_new_session_marks_the_tools_and_instructions_for_reuse(messages_stub: MessagesServer) -> None:
72
+ """CLAI sends the unified `cache` setting; the plugin's one-hour default must keep its static breakpoints."""
73
+ provider = ClaudeCodeProvider(
74
+ ClaudeCodeCredentials(access_token="sub-token", refresh_token="refresh"), base_url=messages_stub.url
75
+ )
76
+ agent = Agent(ClaudeCodeModel("claude-opus-5-5", provider=provider), instructions="Be terse.")
77
+
78
+ @agent.tool_plain
79
+ def lookup(key: str) -> str:
80
+ """Look a key up."""
81
+ return key # pragma: no cover -- the stub never calls tools
82
+
83
+ await agent.run("go on", model_settings={"cache": True})
84
+ body = messages_stub.received
85
+ tools = body["tools"]
86
+ system = body["system"]
87
+ assert isinstance(tools, list) and isinstance(system, list)
88
+ assert tools[-1]["cache_control"] == ONE_HOUR
89
+ assert system[-1]["cache_control"] == ONE_HOUR
90
+ assert body["cache_control"] == ONE_HOUR, "the conversation keeps its moving one-hour breakpoint"
91
+
92
+
93
+ PERSONA = config.CLAUDE_CODE_SYSTEM_PROMPT
94
+ SUMMARY = "Summary of previous conversation:\n\n## Intent\nShip the plugin."
95
+
96
+
97
+ async def _sent_system(
98
+ messages_stub: MessagesServer, history: list[ModelMessage], **agent: Any
99
+ ) -> list[dict[str, Any]]:
100
+ """The `system` blocks the subscription backend receives for a run continuing `history`."""
101
+ provider = ClaudeCodeProvider(
102
+ ClaudeCodeCredentials(access_token="sub-token", refresh_token="refresh"), base_url=messages_stub.url
103
+ )
104
+ await Agent(ClaudeCodeModel("claude-opus-5-5", provider=provider), **agent).run("go on", message_history=history)
105
+ system = messages_stub.received["system"]
106
+ assert isinstance(system, list)
107
+ return system # type: ignore[return-value]
108
+
109
+
110
+ def _texts(system: list[dict[str, Any]]) -> list[str]:
111
+ return [block["text"] for block in system]
112
+
113
+
114
+ @pytest.mark.parametrize(
115
+ "parts",
116
+ [
117
+ pytest.param([SystemPromptPart(f"{PERSONA}\n\n{SUMMARY}")], id="summary-inside-the-persona-part"),
118
+ pytest.param([SystemPromptPart(PERSONA), SystemPromptPart(SUMMARY)], id="joined-into-one-block"),
119
+ pytest.param([SystemPromptPart(SUMMARY), SystemPromptPart(PERSONA)], id="summary-before-the-persona"),
120
+ pytest.param([SystemPromptPart(SUMMARY)], id="compaction-dropped-the-persona"),
121
+ ],
122
+ )
123
+ async def test_compacted_history_still_sends_the_persona_alone_first(
124
+ messages_stub: MessagesServer, parts: list[SystemPromptPart]
125
+ ) -> None:
126
+ history: list[ModelMessage] = [ModelRequest([*parts, UserPromptPart("earlier")]), ModelResponse([TextPart("ok")])]
127
+ system = await _sent_system(messages_stub, history)
128
+ assert _texts(system) == [PERSONA, SUMMARY]
129
+
130
+
131
+ async def test_instructions_follow_the_persona_and_keep_their_cache_breakpoint(messages_stub: MessagesServer) -> None:
132
+ settings = AnthropicModelSettings(anthropic_cache_instructions="1h")
133
+ system = await _sent_system(messages_stub, [], instructions="Be terse.", model_settings=settings)
134
+ assert _texts(system) == [PERSONA, "Be terse."]
135
+ assert system[-1]["cache_control"] == {"type": "ephemeral", "ttl": "1h"}, "the breakpoint caches the persona too"
136
+
137
+
138
+ async def test_a_fresh_run_without_any_system_prompt_gets_just_the_persona(messages_stub: MessagesServer) -> None:
139
+ assert _texts(await _sent_system(messages_stub, [])) == [PERSONA]
140
+
141
+
142
+ def test_a_cache_breakpoint_on_a_persona_only_block_moves_to_the_persona() -> None:
143
+ cached = BetaTextBlockParam(type="text", text=PERSONA, cache_control={"type": "ephemeral"})
144
+ first, *rest = _persona_first([cached])
145
+ assert first == cached
146
+ assert rest == []
@@ -1430,7 +1430,7 @@ wheels = [
1430
1430
 
1431
1431
  [[package]]
1432
1432
  name = "pydantic-claude-code"
1433
- version = "0.7.1"
1433
+ version = "0.7.3"
1434
1434
  source = { editable = "." }
1435
1435
  dependencies = [
1436
1436
  { name = "keyring" },
@@ -1,111 +0,0 @@
1
- """The Claude Code model: an `AnthropicModel` with the Claude Code persona prepended."""
2
-
3
- from __future__ import annotations
4
-
5
- from collections.abc import AsyncGenerator, Iterator
6
- from contextlib import asynccontextmanager, contextmanager
7
- from typing import Any
8
-
9
- from pydantic_ai import RunContext
10
- from pydantic_ai.exceptions import ModelAPIError
11
- from pydantic_ai.messages import ModelMessage, ModelRequest, ModelResponse, SystemPromptPart
12
- from pydantic_ai.models import ModelRequestParameters, StreamedResponse
13
- from pydantic_ai.models.anthropic import AnthropicModel, AnthropicModelSettings
14
- from pydantic_ai.providers import Provider
15
- from pydantic_ai.settings import ModelSettings
16
-
17
- from . import config
18
- from .auth import ClaudeCodeSignInExpiredError
19
-
20
-
21
- class ClaudeCodeModel(AnthropicModel):
22
- """AnthropicModel whose system prompt opens with the Claude Code persona.
23
-
24
- The subscription backend expects the Claude Code persona at position 0 of
25
- the system context. Prepending a `SystemPromptPart` here is idempotent:
26
- once it's in history it stays, and repeated `prepare_messages` calls don't
27
- duplicate it.
28
- """
29
-
30
- def __init__(
31
- self,
32
- model_name: str,
33
- *,
34
- provider: Provider[Any] | None = None,
35
- settings: ModelSettings | None = None,
36
- **kwargs: Any,
37
- ) -> None:
38
- """Initialize a Claude Code model.
39
-
40
- Args:
41
- model_name: The model name to use, e.g. `'claude-fable-5-1'`.
42
- provider: The provider to authenticate with. Defaults to a
43
- `ClaudeCodeProvider` backed by the default token store.
44
- """
45
- if provider is None:
46
- from .provider import ClaudeCodeProvider
47
-
48
- provider = ClaudeCodeProvider()
49
- defaults = AnthropicModelSettings(
50
- anthropic_cache=False if settings and settings.get("anthropic_cache_messages") else "1h",
51
- )
52
- super().__init__(model_name, provider=provider, settings={**defaults, **(settings or {})}, **kwargs)
53
-
54
- def prepare_messages(
55
- self,
56
- messages: list[ModelMessage],
57
- model_request_parameters=None,
58
- ) -> list[ModelMessage]:
59
- return super().prepare_messages(_prepend_persona(messages), model_request_parameters)
60
-
61
- async def request(
62
- self,
63
- messages: list[ModelMessage],
64
- model_settings: ModelSettings | None,
65
- model_request_parameters: ModelRequestParameters,
66
- ) -> ModelResponse:
67
- with _surface_expired_sign_in():
68
- return await super().request(messages, model_settings, model_request_parameters)
69
-
70
- @asynccontextmanager
71
- async def request_stream(
72
- self,
73
- messages: list[ModelMessage],
74
- model_settings: ModelSettings | None,
75
- model_request_parameters: ModelRequestParameters,
76
- run_context: RunContext[Any] | None = None,
77
- ) -> AsyncGenerator[StreamedResponse]:
78
- with _surface_expired_sign_in():
79
- async with super().request_stream(
80
- messages, model_settings, model_request_parameters, run_context
81
- ) as response:
82
- yield response
83
-
84
-
85
- @contextmanager
86
- def _surface_expired_sign_in() -> Iterator[None]:
87
- """Re-raise an expired sign-in that the SDK reported as `Connection error.`."""
88
- try:
89
- yield
90
- except ModelAPIError as exc:
91
- cause: BaseException | None = exc
92
- while cause is not None:
93
- if isinstance(cause, ClaudeCodeSignInExpiredError):
94
- raise cause from exc
95
- cause = cause.__cause__
96
- raise
97
-
98
-
99
- def _prepend_persona(messages: list[ModelMessage]) -> list[ModelMessage]:
100
- """Return `messages` with the persona added first, unless it's already there."""
101
- for index, message in enumerate(messages):
102
- if not isinstance(message, ModelRequest):
103
- continue
104
- if any(
105
- isinstance(part, SystemPromptPart) and part.content.strip().startswith(config.CLAUDE_CODE_SYSTEM_PROMPT)
106
- for part in message.parts
107
- ):
108
- return messages
109
- updated = ModelRequest([SystemPromptPart(config.CLAUDE_CODE_SYSTEM_PROMPT), *message.parts])
110
- return [*messages[:index], updated, *messages[index + 1 :]]
111
- return messages
@@ -1,59 +0,0 @@
1
- """Tests for the Claude Code persona prepend logic."""
2
-
3
- from __future__ import annotations
4
-
5
- from datetime import timedelta
6
-
7
- import pytest
8
-
9
- from pydantic_ai.messages import ModelMessage, ModelRequest, SystemPromptPart, UserPromptPart
10
- from pydantic_ai.models.anthropic import AnthropicModelSettings
11
- from pydantic_ai.providers.anthropic import AnthropicProvider
12
-
13
- from pydantic_ai_claude_code import config
14
- from pydantic_ai_claude_code.model import ClaudeCodeModel, _prepend_persona
15
-
16
-
17
- @pytest.mark.parametrize(
18
- ("settings", "expected"),
19
- [
20
- (None, timedelta(hours=1)),
21
- (AnthropicModelSettings(anthropic_cache="5m"), timedelta(minutes=5)),
22
- (AnthropicModelSettings(anthropic_cache=False), None),
23
- (AnthropicModelSettings(anthropic_cache_messages="1h"), timedelta(hours=1)),
24
- ],
25
- )
26
- def test_cache_retention_defaults_to_one_hour(
27
- settings: AnthropicModelSettings | None, expected: timedelta | None
28
- ) -> None:
29
- model = ClaudeCodeModel("claude-sonnet-4-6", provider=AnthropicProvider(api_key="test-key"), settings=settings)
30
- assert model.resolve_cache_retention(None) == expected
31
- assert model.resolve_cache_retention(
32
- AnthropicModelSettings(anthropic_cache="5m", anthropic_cache_messages=False)
33
- ) == timedelta(minutes=5)
34
-
35
-
36
- def test_persona_prepended_to_leading_request() -> None:
37
- messages: list[ModelMessage] = [
38
- ModelRequest([SystemPromptPart("You are a helpful assistant."), UserPromptPart("hi")])
39
- ]
40
- out = _prepend_persona(messages)
41
- leading = out[0]
42
- assert isinstance(leading, ModelRequest)
43
- persona, user_system = leading.parts[:2]
44
- assert isinstance(persona, SystemPromptPart)
45
- assert persona.content == config.CLAUDE_CODE_SYSTEM_PROMPT
46
- assert isinstance(user_system, SystemPromptPart)
47
- assert user_system.content == "You are a helpful assistant."
48
- # The user prompt is untouched.
49
- assert leading.parts[2].content == "hi" # type: ignore[attr-defined]
50
-
51
-
52
- def test_persona_prepend_is_idempotent() -> None:
53
- messages: list[ModelMessage] = [ModelRequest([SystemPromptPart("hi")])]
54
- once = _prepend_persona(messages)
55
- twice = _prepend_persona(once)
56
- parts = twice[0].parts # type: ignore[attr-defined]
57
- assert (
58
- sum(1 for p in parts if isinstance(p, SystemPromptPart) and p.content == config.CLAUDE_CODE_SYSTEM_PROMPT) == 1
59
- )