ctxbudgeter 0.2.0__py3-none-any.whl
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.
- ctxbudgeter/__init__.py +90 -0
- ctxbudgeter/adapters/__init__.py +24 -0
- ctxbudgeter/adapters/anthropic.py +124 -0
- ctxbudgeter/adapters/langchain.py +68 -0
- ctxbudgeter/adapters/openai.py +130 -0
- ctxbudgeter/adapters/pydantic_ai.py +75 -0
- ctxbudgeter/cli.py +449 -0
- ctxbudgeter/compiler.py +1184 -0
- ctxbudgeter/content.py +79 -0
- ctxbudgeter/item.py +116 -0
- ctxbudgeter/loaders.py +100 -0
- ctxbudgeter/memory.py +171 -0
- ctxbudgeter/pack.py +357 -0
- ctxbudgeter/py.typed +0 -0
- ctxbudgeter/pytest_plugin.py +60 -0
- ctxbudgeter/reference.py +79 -0
- ctxbudgeter/report.py +150 -0
- ctxbudgeter/scoring.py +55 -0
- ctxbudgeter/spec.py +307 -0
- ctxbudgeter/testing.py +233 -0
- ctxbudgeter/tokenizer.py +97 -0
- ctxbudgeter-0.2.0.dist-info/METADATA +570 -0
- ctxbudgeter-0.2.0.dist-info/RECORD +26 -0
- ctxbudgeter-0.2.0.dist-info/WHEEL +4 -0
- ctxbudgeter-0.2.0.dist-info/entry_points.txt +5 -0
- ctxbudgeter-0.2.0.dist-info/licenses/LICENSE +21 -0
ctxbudgeter/__init__.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""ctxbudgeter — compile clean, cheap, auditable context for AI agents.
|
|
2
|
+
|
|
3
|
+
Framework-agnostic. Local-first. Deterministic. No LLM API calls in the core.
|
|
4
|
+
|
|
5
|
+
Quick start::
|
|
6
|
+
|
|
7
|
+
from ctxbudgeter import ContextPack
|
|
8
|
+
|
|
9
|
+
pack = ContextPack(model="claude-sonnet-4.6", token_budget=24_000, reserved_output_tokens=4_000)
|
|
10
|
+
pack.add(name="system_rules", content="You are a careful coding agent...",
|
|
11
|
+
kind="system", priority=100, cache_policy="stable", required=True)
|
|
12
|
+
pack.add_file("README.md", kind="project_doc", priority=80)
|
|
13
|
+
pack.add(name="task", content="Build the referral packet UI.",
|
|
14
|
+
kind="task", priority=95, required=True)
|
|
15
|
+
|
|
16
|
+
compiled = pack.compile()
|
|
17
|
+
print(compiled.report())
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from . import adapters, loaders
|
|
23
|
+
from .compiler import (
|
|
24
|
+
BudgetExceededError,
|
|
25
|
+
CompiledPack,
|
|
26
|
+
CompilerConfig,
|
|
27
|
+
Compressor,
|
|
28
|
+
ItemDecision,
|
|
29
|
+
SecretContentError,
|
|
30
|
+
SecretPolicy,
|
|
31
|
+
acompile_items,
|
|
32
|
+
compile_items,
|
|
33
|
+
compiled_pack_from_dict,
|
|
34
|
+
)
|
|
35
|
+
from .content import Attachment, ImageBlock, StructuredBlock, TextBlock
|
|
36
|
+
from .item import CachePolicy, ContextItem, ContextKind, Sensitivity
|
|
37
|
+
from .memory import InMemoryStore, JSONMemoryStore, MemoryNote, MemoryStore
|
|
38
|
+
from .pack import ContextPack
|
|
39
|
+
from .reference import AsyncLoader, Loader, Reference, SyncLoader
|
|
40
|
+
from .report import to_json, to_markdown, to_text
|
|
41
|
+
from .scoring import DEFAULT_WEIGHTS, score_item
|
|
42
|
+
from .tokenizer import TokenCounter
|
|
43
|
+
|
|
44
|
+
__version__ = "0.2.0"
|
|
45
|
+
|
|
46
|
+
__all__ = [
|
|
47
|
+
"DEFAULT_WEIGHTS",
|
|
48
|
+
"AsyncLoader",
|
|
49
|
+
# multimodal
|
|
50
|
+
"Attachment",
|
|
51
|
+
"BudgetExceededError",
|
|
52
|
+
"CachePolicy",
|
|
53
|
+
"CompiledPack",
|
|
54
|
+
"CompilerConfig",
|
|
55
|
+
"Compressor",
|
|
56
|
+
# core
|
|
57
|
+
"ContextItem",
|
|
58
|
+
"ContextKind",
|
|
59
|
+
"ContextPack",
|
|
60
|
+
"ImageBlock",
|
|
61
|
+
"InMemoryStore",
|
|
62
|
+
"ItemDecision",
|
|
63
|
+
"JSONMemoryStore",
|
|
64
|
+
"Loader",
|
|
65
|
+
"MemoryNote",
|
|
66
|
+
# memory (Write strategy)
|
|
67
|
+
"MemoryStore",
|
|
68
|
+
# references (just-in-time loading)
|
|
69
|
+
"Reference",
|
|
70
|
+
"SecretContentError",
|
|
71
|
+
"SecretPolicy",
|
|
72
|
+
"Sensitivity",
|
|
73
|
+
"StructuredBlock",
|
|
74
|
+
"SyncLoader",
|
|
75
|
+
"TextBlock",
|
|
76
|
+
"TokenCounter",
|
|
77
|
+
# version
|
|
78
|
+
"__version__",
|
|
79
|
+
"acompile_items",
|
|
80
|
+
# adapters
|
|
81
|
+
"adapters",
|
|
82
|
+
"compile_items",
|
|
83
|
+
"compiled_pack_from_dict",
|
|
84
|
+
"loaders",
|
|
85
|
+
"score_item",
|
|
86
|
+
"to_json",
|
|
87
|
+
"to_markdown",
|
|
88
|
+
# reports
|
|
89
|
+
"to_text",
|
|
90
|
+
]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Framework adapters. Convert a CompiledPack into the message format of a target SDK.
|
|
2
|
+
|
|
3
|
+
Each adapter is independent — you only pay the import cost for the one you use, and
|
|
4
|
+
optional SDKs (langchain-core, anthropic, openai) are only imported lazily inside the
|
|
5
|
+
function that needs them.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from .anthropic import to_anthropic_messages, to_anthropic_request
|
|
11
|
+
from .langchain import to_langchain_messages
|
|
12
|
+
from .openai import stable_prefix_cache_key, to_openai_messages, to_openai_request
|
|
13
|
+
from .pydantic_ai import to_pydantic_ai, to_pydantic_ai_deps
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"stable_prefix_cache_key",
|
|
17
|
+
"to_anthropic_messages",
|
|
18
|
+
"to_anthropic_request",
|
|
19
|
+
"to_langchain_messages",
|
|
20
|
+
"to_openai_messages",
|
|
21
|
+
"to_openai_request",
|
|
22
|
+
"to_pydantic_ai", # deprecated alias
|
|
23
|
+
"to_pydantic_ai_deps",
|
|
24
|
+
]
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Adapter: CompiledPack → Anthropic Messages API format with prompt-caching hints.
|
|
2
|
+
|
|
3
|
+
Returns plain dicts — no anthropic SDK dependency. Cache breakpoints are placed on
|
|
4
|
+
the LAST stable system block, since Anthropic's prompt cache key covers everything
|
|
5
|
+
up to and including the marked block. That gives you the longest possible cacheable
|
|
6
|
+
prefix from a single breakpoint.
|
|
7
|
+
|
|
8
|
+
`to_anthropic_request(pack, ...)` wraps the messages payload with `model` and
|
|
9
|
+
`max_tokens` so it slots straight into `client.messages.create(**kwargs)`.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
|
|
16
|
+
from ..compiler import CompiledPack
|
|
17
|
+
from ..content import ImageBlock, StructuredBlock, TextBlock
|
|
18
|
+
|
|
19
|
+
CHAT_KINDS = {"user_message", "assistant_message", "tool_result"}
|
|
20
|
+
MAX_CACHE_BREAKPOINTS = 4
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _attachments_to_blocks(content: str, attachments: list) -> list[dict]:
|
|
24
|
+
"""Return a list of Anthropic content blocks for a chat message."""
|
|
25
|
+
blocks: list[dict] = []
|
|
26
|
+
if content:
|
|
27
|
+
blocks.append({"type": "text", "text": content})
|
|
28
|
+
for a in attachments:
|
|
29
|
+
if isinstance(a, TextBlock):
|
|
30
|
+
blocks.append({"type": "text", "text": a.text})
|
|
31
|
+
elif isinstance(a, ImageBlock):
|
|
32
|
+
if a.base64:
|
|
33
|
+
blocks.append(
|
|
34
|
+
{
|
|
35
|
+
"type": "image",
|
|
36
|
+
"source": {
|
|
37
|
+
"type": "base64",
|
|
38
|
+
"media_type": a.media_type or "image/png",
|
|
39
|
+
"data": a.base64,
|
|
40
|
+
},
|
|
41
|
+
}
|
|
42
|
+
)
|
|
43
|
+
elif a.url:
|
|
44
|
+
blocks.append({"type": "image", "source": {"type": "url", "url": a.url}})
|
|
45
|
+
elif isinstance(a, StructuredBlock):
|
|
46
|
+
blocks.append({"type": "text", "text": json.dumps(a.data, sort_keys=True, default=str)})
|
|
47
|
+
return blocks
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def to_anthropic_messages(
|
|
51
|
+
pack: CompiledPack,
|
|
52
|
+
*,
|
|
53
|
+
user_message: str | None = None,
|
|
54
|
+
) -> dict:
|
|
55
|
+
"""Convert a CompiledPack to Anthropic Messages API input."""
|
|
56
|
+
system_blocks: list[dict] = []
|
|
57
|
+
chat: list[dict] = []
|
|
58
|
+
|
|
59
|
+
system_items = [it for it in pack.included_items if it.kind not in CHAT_KINDS]
|
|
60
|
+
last_stable_idx = -1
|
|
61
|
+
for i, it in enumerate(system_items):
|
|
62
|
+
if it.cache_policy == "stable":
|
|
63
|
+
last_stable_idx = i
|
|
64
|
+
for i, it in enumerate(system_items):
|
|
65
|
+
content = it.effective_content()
|
|
66
|
+
text = content if it.kind == "system" else f"## {it.name}\n{content}"
|
|
67
|
+
block: dict = {"type": "text", "text": text}
|
|
68
|
+
if i == last_stable_idx and last_stable_idx >= 0:
|
|
69
|
+
block["cache_control"] = {"type": "ephemeral"}
|
|
70
|
+
system_blocks.append(block)
|
|
71
|
+
# Attachments on system-attached items become extra text/image blocks
|
|
72
|
+
for extra in _attachments_to_blocks("", it.attachments):
|
|
73
|
+
system_blocks.append(extra)
|
|
74
|
+
|
|
75
|
+
for it in pack.included_in_input_order():
|
|
76
|
+
if it.kind not in CHAT_KINDS:
|
|
77
|
+
continue
|
|
78
|
+
content = it.effective_content()
|
|
79
|
+
if it.kind == "user_message":
|
|
80
|
+
blocks = _attachments_to_blocks(content, it.attachments)
|
|
81
|
+
chat.append({"role": "user", "content": blocks if it.attachments else content})
|
|
82
|
+
elif it.kind == "assistant_message":
|
|
83
|
+
blocks = _attachments_to_blocks(content, it.attachments)
|
|
84
|
+
chat.append({"role": "assistant", "content": blocks if it.attachments else content})
|
|
85
|
+
elif it.kind == "tool_result":
|
|
86
|
+
tool_use_id = str(it.metadata.get("tool_use_id", it.name))
|
|
87
|
+
chat.append(
|
|
88
|
+
{
|
|
89
|
+
"role": "user",
|
|
90
|
+
"content": [
|
|
91
|
+
{
|
|
92
|
+
"type": "tool_result",
|
|
93
|
+
"tool_use_id": tool_use_id,
|
|
94
|
+
"content": content,
|
|
95
|
+
}
|
|
96
|
+
],
|
|
97
|
+
}
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
if user_message is not None:
|
|
101
|
+
chat.append({"role": "user", "content": user_message})
|
|
102
|
+
|
|
103
|
+
if not chat:
|
|
104
|
+
chat.append({"role": "user", "content": ""})
|
|
105
|
+
elif chat[0]["role"] != "user":
|
|
106
|
+
chat.insert(0, {"role": "user", "content": ""})
|
|
107
|
+
|
|
108
|
+
return {"system": system_blocks, "messages": chat}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def to_anthropic_request(
|
|
112
|
+
pack: CompiledPack,
|
|
113
|
+
*,
|
|
114
|
+
user_message: str | None = None,
|
|
115
|
+
max_tokens: int | None = None,
|
|
116
|
+
) -> dict:
|
|
117
|
+
"""Return a kwargs dict for ``client.messages.create(**kwargs)``."""
|
|
118
|
+
payload = to_anthropic_messages(pack, user_message=user_message)
|
|
119
|
+
return {
|
|
120
|
+
"model": pack.model,
|
|
121
|
+
"max_tokens": max_tokens or pack.reserved_output_tokens,
|
|
122
|
+
"system": payload["system"],
|
|
123
|
+
"messages": payload["messages"],
|
|
124
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Adapter: CompiledPack → langchain_core BaseMessage list.
|
|
2
|
+
|
|
3
|
+
Requires `langchain-core` (install via `pip install ctxbudgeter[langchain]`).
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from ..compiler import CompiledPack
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def to_langchain_messages(
|
|
14
|
+
pack: CompiledPack,
|
|
15
|
+
*,
|
|
16
|
+
user_message: str | None = None,
|
|
17
|
+
) -> list[Any]:
|
|
18
|
+
"""Convert a CompiledPack into a list of langchain_core message objects.
|
|
19
|
+
|
|
20
|
+
Returns a list of SystemMessage / HumanMessage / AIMessage / ToolMessage.
|
|
21
|
+
|
|
22
|
+
Raises ImportError if langchain-core is not installed.
|
|
23
|
+
"""
|
|
24
|
+
try:
|
|
25
|
+
from langchain_core.messages import (
|
|
26
|
+
AIMessage,
|
|
27
|
+
HumanMessage,
|
|
28
|
+
SystemMessage,
|
|
29
|
+
ToolMessage,
|
|
30
|
+
)
|
|
31
|
+
except ImportError as e: # pragma: no cover
|
|
32
|
+
raise ImportError(
|
|
33
|
+
"langchain-core is required for the langchain adapter. "
|
|
34
|
+
"Install via `pip install ctxbudgeter[langchain]`."
|
|
35
|
+
) from e
|
|
36
|
+
|
|
37
|
+
chat_kinds = {"user_message", "assistant_message", "tool_result"}
|
|
38
|
+
system_parts: list[str] = []
|
|
39
|
+
chat: list[Any] = []
|
|
40
|
+
|
|
41
|
+
for it in pack.included_items:
|
|
42
|
+
if it.kind in chat_kinds:
|
|
43
|
+
continue
|
|
44
|
+
content = it.effective_content()
|
|
45
|
+
if it.kind == "system":
|
|
46
|
+
system_parts.append(content)
|
|
47
|
+
else:
|
|
48
|
+
system_parts.append(f"## {it.name}\n{content}")
|
|
49
|
+
|
|
50
|
+
for it in pack.included_in_input_order():
|
|
51
|
+
if it.kind not in chat_kinds:
|
|
52
|
+
continue
|
|
53
|
+
content = it.effective_content()
|
|
54
|
+
if it.kind == "user_message":
|
|
55
|
+
chat.append(HumanMessage(content=content))
|
|
56
|
+
elif it.kind == "assistant_message":
|
|
57
|
+
chat.append(AIMessage(content=content))
|
|
58
|
+
elif it.kind == "tool_result":
|
|
59
|
+
tool_call_id = str(it.metadata.get("tool_call_id", it.name))
|
|
60
|
+
chat.append(ToolMessage(content=content, tool_call_id=tool_call_id))
|
|
61
|
+
|
|
62
|
+
out: list[Any] = []
|
|
63
|
+
if system_parts:
|
|
64
|
+
out.append(SystemMessage(content="\n\n".join(system_parts)))
|
|
65
|
+
out.extend(chat)
|
|
66
|
+
if user_message is not None:
|
|
67
|
+
out.append(HumanMessage(content=user_message))
|
|
68
|
+
return out
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Adapter: CompiledPack → OpenAI Chat Completions / Responses message format.
|
|
2
|
+
|
|
3
|
+
No openai SDK dependency — returns plain dicts. Compatible with both the legacy
|
|
4
|
+
Chat Completions schema and the newer Responses API input format.
|
|
5
|
+
|
|
6
|
+
`to_openai_request(pack, user_message=...)` returns the full kwargs dict including
|
|
7
|
+
a deterministic `prompt_cache_key` derived from the stable prefix — wire it
|
|
8
|
+
straight into `client.chat.completions.create(**kwargs)` for explicit cache routing.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import hashlib
|
|
14
|
+
import json
|
|
15
|
+
|
|
16
|
+
from ..compiler import CompiledPack
|
|
17
|
+
from ..content import ImageBlock, StructuredBlock, TextBlock
|
|
18
|
+
|
|
19
|
+
CHAT_KINDS = {"user_message", "assistant_message", "tool_result"}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def stable_prefix_cache_key(pack: CompiledPack) -> str | None:
|
|
23
|
+
"""Hash the stable-cache prefix into a deterministic cache key.
|
|
24
|
+
|
|
25
|
+
Returns None if there's no stable prefix (no point setting a cache key for an
|
|
26
|
+
empty prefix). The key is stable across runs as long as the stable items'
|
|
27
|
+
content doesn't change — which is exactly what prompt caching wants.
|
|
28
|
+
"""
|
|
29
|
+
parts: list[str] = [pack.model]
|
|
30
|
+
for it in pack.included_items:
|
|
31
|
+
if it.cache_policy != "stable":
|
|
32
|
+
break
|
|
33
|
+
parts.append(it.name)
|
|
34
|
+
parts.append(it.effective_content())
|
|
35
|
+
if len(parts) == 1:
|
|
36
|
+
return None
|
|
37
|
+
digest = hashlib.sha256("\n".join(parts).encode("utf-8")).hexdigest()
|
|
38
|
+
return f"ctxbudgeter-{digest[:24]}"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _content_for_message(content: str, attachments: list) -> object:
|
|
42
|
+
"""If there are attachments, return a list-of-parts OpenAI multimodal payload.
|
|
43
|
+
Otherwise return the plain text string."""
|
|
44
|
+
if not attachments:
|
|
45
|
+
return content
|
|
46
|
+
parts: list[dict] = []
|
|
47
|
+
if content:
|
|
48
|
+
parts.append({"type": "text", "text": content})
|
|
49
|
+
for a in attachments:
|
|
50
|
+
if isinstance(a, TextBlock):
|
|
51
|
+
parts.append({"type": "text", "text": a.text})
|
|
52
|
+
elif isinstance(a, ImageBlock):
|
|
53
|
+
url = a.url or (f"data:{a.media_type or 'image/png'};base64,{a.base64}" if a.base64 else None)
|
|
54
|
+
if url:
|
|
55
|
+
parts.append({"type": "image_url", "image_url": {"url": url, "detail": a.detail}})
|
|
56
|
+
elif isinstance(a, StructuredBlock):
|
|
57
|
+
parts.append({"type": "text", "text": json.dumps(a.data, sort_keys=True, default=str)})
|
|
58
|
+
return parts
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def to_openai_messages(
|
|
62
|
+
pack: CompiledPack,
|
|
63
|
+
*,
|
|
64
|
+
user_message: str | None = None,
|
|
65
|
+
merge_system: bool = True,
|
|
66
|
+
) -> list[dict]:
|
|
67
|
+
"""Convert a CompiledPack to a list of OpenAI chat messages."""
|
|
68
|
+
system_parts: list[str] = []
|
|
69
|
+
chat: list[dict] = []
|
|
70
|
+
|
|
71
|
+
for it in pack.included_items:
|
|
72
|
+
if it.kind in CHAT_KINDS:
|
|
73
|
+
continue
|
|
74
|
+
content = it.effective_content()
|
|
75
|
+
if it.kind == "system":
|
|
76
|
+
system_parts.append(content)
|
|
77
|
+
else:
|
|
78
|
+
system_parts.append(f"## {it.name}\n{content}")
|
|
79
|
+
|
|
80
|
+
for it in pack.included_in_input_order():
|
|
81
|
+
if it.kind not in CHAT_KINDS:
|
|
82
|
+
continue
|
|
83
|
+
content = it.effective_content()
|
|
84
|
+
payload = _content_for_message(content, it.attachments)
|
|
85
|
+
if it.kind == "user_message":
|
|
86
|
+
chat.append({"role": "user", "content": payload})
|
|
87
|
+
elif it.kind == "assistant_message":
|
|
88
|
+
chat.append({"role": "assistant", "content": payload})
|
|
89
|
+
elif it.kind == "tool_result":
|
|
90
|
+
tool_call_id = str(it.metadata.get("tool_call_id", it.name))
|
|
91
|
+
chat.append({"role": "tool", "tool_call_id": tool_call_id, "content": content})
|
|
92
|
+
|
|
93
|
+
out: list[dict] = []
|
|
94
|
+
if system_parts:
|
|
95
|
+
if merge_system:
|
|
96
|
+
out.append({"role": "system", "content": "\n\n".join(system_parts)})
|
|
97
|
+
else:
|
|
98
|
+
out.extend({"role": "system", "content": p} for p in system_parts)
|
|
99
|
+
out.extend(chat)
|
|
100
|
+
if user_message is not None:
|
|
101
|
+
out.append({"role": "user", "content": user_message})
|
|
102
|
+
return out
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def to_openai_request(
|
|
106
|
+
pack: CompiledPack,
|
|
107
|
+
*,
|
|
108
|
+
user_message: str | None = None,
|
|
109
|
+
merge_system: bool = True,
|
|
110
|
+
max_completion_tokens: int | None = None,
|
|
111
|
+
set_cache_key: bool = True,
|
|
112
|
+
) -> dict:
|
|
113
|
+
"""Return a kwargs dict suitable for ``client.chat.completions.create(**kwargs)``.
|
|
114
|
+
|
|
115
|
+
Includes `model`, `messages`, `max_completion_tokens` (default: pack.reserved_output_tokens),
|
|
116
|
+
and `prompt_cache_key` (default: hash of stable prefix). Drop directly into the
|
|
117
|
+
OpenAI client for explicit, cache-aware calls.
|
|
118
|
+
"""
|
|
119
|
+
kwargs: dict = {
|
|
120
|
+
"model": pack.model,
|
|
121
|
+
"messages": to_openai_messages(
|
|
122
|
+
pack, user_message=user_message, merge_system=merge_system
|
|
123
|
+
),
|
|
124
|
+
"max_completion_tokens": max_completion_tokens or pack.reserved_output_tokens,
|
|
125
|
+
}
|
|
126
|
+
if set_cache_key:
|
|
127
|
+
key = stable_prefix_cache_key(pack)
|
|
128
|
+
if key:
|
|
129
|
+
kwargs["prompt_cache_key"] = key
|
|
130
|
+
return kwargs
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Adapter: CompiledPack → PydanticAI-friendly dict.
|
|
2
|
+
|
|
3
|
+
Returns a plain dict — no pydantic-ai SDK dependency. The dict has:
|
|
4
|
+
- "system_prompt": str — concatenated system + non-chat content
|
|
5
|
+
- "message_history": list[dict] — chat turns
|
|
6
|
+
- "deps_context": dict[name -> {content, kind, priority, source}] — every included
|
|
7
|
+
item, indexed by name; useful as `deps` for PydanticAI Agent.run() so tools can
|
|
8
|
+
pull specific context by name without re-parsing the system prompt.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from ..compiler import CompiledPack
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def to_pydantic_ai_deps(pack: CompiledPack) -> dict[str, Any]:
|
|
19
|
+
"""Convert a CompiledPack to a structured dict for PydanticAI agents.
|
|
20
|
+
|
|
21
|
+
Returns a dict you can pass into Agent.run() as `deps`, with:
|
|
22
|
+
- `system_prompt`: concatenated system + non-chat content
|
|
23
|
+
- `message_history`: list of chat turns in chronological order
|
|
24
|
+
- `deps_context`: name → {content, kind, priority, source} for tool lookup
|
|
25
|
+
"""
|
|
26
|
+
chat_kinds = {"user_message", "assistant_message", "tool_result"}
|
|
27
|
+
system_parts: list[str] = []
|
|
28
|
+
history: list[dict] = []
|
|
29
|
+
deps_context: dict[str, dict] = {}
|
|
30
|
+
|
|
31
|
+
# Build deps_context in prompt order; system_parts in prompt order
|
|
32
|
+
for it in pack.included_items:
|
|
33
|
+
content = it.effective_content()
|
|
34
|
+
deps_context[it.name] = {
|
|
35
|
+
"content": content,
|
|
36
|
+
"kind": it.kind,
|
|
37
|
+
"priority": it.priority,
|
|
38
|
+
"cache_policy": it.cache_policy,
|
|
39
|
+
"source": it.source,
|
|
40
|
+
}
|
|
41
|
+
if it.kind in chat_kinds:
|
|
42
|
+
continue
|
|
43
|
+
if it.kind == "system":
|
|
44
|
+
system_parts.append(content)
|
|
45
|
+
else:
|
|
46
|
+
system_parts.append(f"## {it.name}\n{content}")
|
|
47
|
+
|
|
48
|
+
# Chat history in insertion order
|
|
49
|
+
for it in pack.included_in_input_order():
|
|
50
|
+
if it.kind not in chat_kinds:
|
|
51
|
+
continue
|
|
52
|
+
content = it.effective_content()
|
|
53
|
+
if it.kind == "user_message":
|
|
54
|
+
history.append({"role": "user", "content": content})
|
|
55
|
+
elif it.kind == "assistant_message":
|
|
56
|
+
history.append({"role": "model", "content": content})
|
|
57
|
+
elif it.kind == "tool_result":
|
|
58
|
+
history.append(
|
|
59
|
+
{
|
|
60
|
+
"role": "tool",
|
|
61
|
+
"content": content,
|
|
62
|
+
"tool_call_id": it.metadata.get("tool_call_id", it.name),
|
|
63
|
+
}
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
return {
|
|
67
|
+
"system_prompt": "\n\n".join(system_parts),
|
|
68
|
+
"message_history": history,
|
|
69
|
+
"deps_context": deps_context,
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def to_pydantic_ai(pack: CompiledPack) -> dict[str, Any]:
|
|
74
|
+
"""Deprecated alias for :func:`to_pydantic_ai_deps`. Kept for backward compatibility."""
|
|
75
|
+
return to_pydantic_ai_deps(pack)
|