weakincentives 0.9.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.
- weakincentives/__init__.py +67 -0
- weakincentives/adapters/__init__.py +37 -0
- weakincentives/adapters/_names.py +32 -0
- weakincentives/adapters/_provider_protocols.py +69 -0
- weakincentives/adapters/_tool_messages.py +80 -0
- weakincentives/adapters/core.py +102 -0
- weakincentives/adapters/litellm.py +254 -0
- weakincentives/adapters/openai.py +254 -0
- weakincentives/adapters/shared.py +1021 -0
- weakincentives/cli/__init__.py +23 -0
- weakincentives/cli/wink.py +58 -0
- weakincentives/dbc/__init__.py +412 -0
- weakincentives/deadlines.py +58 -0
- weakincentives/prompt/__init__.py +105 -0
- weakincentives/prompt/_generic_params_specializer.py +64 -0
- weakincentives/prompt/_normalization.py +48 -0
- weakincentives/prompt/_overrides_protocols.py +33 -0
- weakincentives/prompt/_types.py +34 -0
- weakincentives/prompt/chapter.py +146 -0
- weakincentives/prompt/composition.py +281 -0
- weakincentives/prompt/errors.py +57 -0
- weakincentives/prompt/markdown.py +108 -0
- weakincentives/prompt/overrides/__init__.py +59 -0
- weakincentives/prompt/overrides/_fs.py +164 -0
- weakincentives/prompt/overrides/inspection.py +141 -0
- weakincentives/prompt/overrides/local_store.py +275 -0
- weakincentives/prompt/overrides/validation.py +534 -0
- weakincentives/prompt/overrides/versioning.py +269 -0
- weakincentives/prompt/prompt.py +353 -0
- weakincentives/prompt/protocols.py +103 -0
- weakincentives/prompt/registry.py +375 -0
- weakincentives/prompt/rendering.py +288 -0
- weakincentives/prompt/response_format.py +60 -0
- weakincentives/prompt/section.py +166 -0
- weakincentives/prompt/structured_output.py +179 -0
- weakincentives/prompt/tool.py +397 -0
- weakincentives/prompt/tool_result.py +30 -0
- weakincentives/py.typed +0 -0
- weakincentives/runtime/__init__.py +82 -0
- weakincentives/runtime/events/__init__.py +126 -0
- weakincentives/runtime/events/_types.py +110 -0
- weakincentives/runtime/logging.py +284 -0
- weakincentives/runtime/session/__init__.py +46 -0
- weakincentives/runtime/session/_slice_types.py +24 -0
- weakincentives/runtime/session/_types.py +55 -0
- weakincentives/runtime/session/dataclasses.py +29 -0
- weakincentives/runtime/session/protocols.py +34 -0
- weakincentives/runtime/session/reducer_context.py +40 -0
- weakincentives/runtime/session/reducers.py +82 -0
- weakincentives/runtime/session/selectors.py +56 -0
- weakincentives/runtime/session/session.py +387 -0
- weakincentives/runtime/session/snapshots.py +310 -0
- weakincentives/serde/__init__.py +19 -0
- weakincentives/serde/_utils.py +240 -0
- weakincentives/serde/dataclass_serde.py +55 -0
- weakincentives/serde/dump.py +189 -0
- weakincentives/serde/parse.py +417 -0
- weakincentives/serde/schema.py +260 -0
- weakincentives/tools/__init__.py +154 -0
- weakincentives/tools/_context.py +38 -0
- weakincentives/tools/asteval.py +853 -0
- weakincentives/tools/errors.py +26 -0
- weakincentives/tools/planning.py +831 -0
- weakincentives/tools/podman.py +1655 -0
- weakincentives/tools/subagents.py +346 -0
- weakincentives/tools/vfs.py +1390 -0
- weakincentives/types/__init__.py +35 -0
- weakincentives/types/json.py +45 -0
- weakincentives-0.9.0.dist-info/METADATA +775 -0
- weakincentives-0.9.0.dist-info/RECORD +73 -0
- weakincentives-0.9.0.dist-info/WHEEL +4 -0
- weakincentives-0.9.0.dist-info/entry_points.txt +2 -0
- weakincentives-0.9.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
2
|
+
# you may not use this file except in compliance with the License.
|
|
3
|
+
# You may obtain a copy of the License at
|
|
4
|
+
#
|
|
5
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
6
|
+
#
|
|
7
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
8
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
9
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
10
|
+
# See the License for the specific language governing permissions and
|
|
11
|
+
# limitations under the License.
|
|
12
|
+
|
|
13
|
+
"""Optional OpenAI adapter utilities."""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from collections.abc import Mapping, Sequence
|
|
18
|
+
from dataclasses import replace
|
|
19
|
+
from datetime import timedelta
|
|
20
|
+
from importlib import import_module
|
|
21
|
+
from typing import TYPE_CHECKING, Any, Final, Protocol, cast
|
|
22
|
+
|
|
23
|
+
from ..deadlines import Deadline
|
|
24
|
+
from ..prompt._types import SupportsDataclass
|
|
25
|
+
from ..prompt.prompt import Prompt
|
|
26
|
+
from ..runtime.events import EventBus
|
|
27
|
+
from ..runtime.logging import StructuredLogger, get_logger
|
|
28
|
+
from . import shared as _shared
|
|
29
|
+
from ._provider_protocols import ProviderChoice, ProviderCompletionResponse
|
|
30
|
+
from ._tool_messages import serialize_tool_message
|
|
31
|
+
from .core import (
|
|
32
|
+
PROMPT_EVALUATION_PHASE_REQUEST,
|
|
33
|
+
PromptEvaluationError,
|
|
34
|
+
PromptResponse,
|
|
35
|
+
SessionProtocol,
|
|
36
|
+
)
|
|
37
|
+
from .shared import (
|
|
38
|
+
OPENAI_ADAPTER_NAME,
|
|
39
|
+
ToolChoice,
|
|
40
|
+
build_json_schema_response_format,
|
|
41
|
+
deadline_provider_payload,
|
|
42
|
+
first_choice,
|
|
43
|
+
format_publish_failures,
|
|
44
|
+
parse_tool_arguments,
|
|
45
|
+
run_conversation,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
if TYPE_CHECKING:
|
|
49
|
+
from ..adapters.core import ProviderAdapter
|
|
50
|
+
from ..prompt.overrides import PromptOverridesStore
|
|
51
|
+
|
|
52
|
+
_ERROR_MESSAGE: Final[str] = (
|
|
53
|
+
"OpenAI support requires the optional 'openai' dependency. "
|
|
54
|
+
"Install it with `uv sync --extra openai` or `pip install weakincentives[openai]`."
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class _CompletionsAPI(Protocol):
|
|
59
|
+
def create(self, *args: object, **kwargs: object) -> ProviderCompletionResponse: ...
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class _ChatAPI(Protocol):
|
|
63
|
+
completions: _CompletionsAPI
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class _OpenAIProtocol(Protocol):
|
|
67
|
+
"""Structural type for the OpenAI client."""
|
|
68
|
+
|
|
69
|
+
chat: _ChatAPI
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class _OpenAIClientFactory(Protocol):
|
|
73
|
+
def __call__(self, **kwargs: object) -> _OpenAIProtocol: ...
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
OpenAIProtocol = _OpenAIProtocol
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class _OpenAIModule(Protocol):
|
|
80
|
+
OpenAI: _OpenAIClientFactory
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _load_openai_module() -> _OpenAIModule:
|
|
84
|
+
try:
|
|
85
|
+
module = import_module("openai")
|
|
86
|
+
except ModuleNotFoundError as exc:
|
|
87
|
+
raise RuntimeError(_ERROR_MESSAGE) from exc
|
|
88
|
+
return cast(_OpenAIModule, module)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def create_openai_client(**kwargs: object) -> _OpenAIProtocol:
|
|
92
|
+
"""Create an OpenAI client, raising a helpful error if the extra is missing."""
|
|
93
|
+
|
|
94
|
+
openai_module = _load_openai_module()
|
|
95
|
+
return openai_module.OpenAI(**kwargs)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
logger: StructuredLogger = get_logger(__name__, context={"component": "adapter.openai"})
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class OpenAIAdapter:
|
|
102
|
+
"""Adapter that evaluates prompts against OpenAI's Responses API."""
|
|
103
|
+
|
|
104
|
+
def __init__(
|
|
105
|
+
self,
|
|
106
|
+
*,
|
|
107
|
+
model: str,
|
|
108
|
+
tool_choice: ToolChoice = "auto",
|
|
109
|
+
use_native_response_format: bool = True,
|
|
110
|
+
client: _OpenAIProtocol | None = None,
|
|
111
|
+
client_factory: _OpenAIClientFactory | None = None,
|
|
112
|
+
client_kwargs: Mapping[str, object] | None = None,
|
|
113
|
+
) -> None:
|
|
114
|
+
super().__init__()
|
|
115
|
+
if client is not None:
|
|
116
|
+
if client_factory is not None:
|
|
117
|
+
raise ValueError(
|
|
118
|
+
"client_factory cannot be provided when an explicit client is supplied.",
|
|
119
|
+
)
|
|
120
|
+
if client_kwargs:
|
|
121
|
+
raise ValueError(
|
|
122
|
+
"client_kwargs cannot be provided when an explicit client is supplied.",
|
|
123
|
+
)
|
|
124
|
+
else:
|
|
125
|
+
factory = client_factory or create_openai_client
|
|
126
|
+
client = factory(**dict(client_kwargs or {}))
|
|
127
|
+
|
|
128
|
+
self._client = client
|
|
129
|
+
self._model = model
|
|
130
|
+
self._tool_choice: ToolChoice = tool_choice
|
|
131
|
+
self._use_native_response_format = use_native_response_format
|
|
132
|
+
|
|
133
|
+
def evaluate[OutputT](
|
|
134
|
+
self,
|
|
135
|
+
prompt: Prompt[OutputT],
|
|
136
|
+
*params: SupportsDataclass,
|
|
137
|
+
parse_output: bool = True,
|
|
138
|
+
bus: EventBus,
|
|
139
|
+
session: SessionProtocol,
|
|
140
|
+
deadline: Deadline | None = None,
|
|
141
|
+
overrides_store: PromptOverridesStore | None = None,
|
|
142
|
+
overrides_tag: str = "latest",
|
|
143
|
+
) -> PromptResponse[OutputT]:
|
|
144
|
+
prompt_name = prompt.name or prompt.__class__.__name__
|
|
145
|
+
render_inputs: tuple[SupportsDataclass, ...] = tuple(params)
|
|
146
|
+
|
|
147
|
+
if deadline is not None and deadline.remaining() <= timedelta(0):
|
|
148
|
+
raise PromptEvaluationError(
|
|
149
|
+
"Deadline expired before evaluation started.",
|
|
150
|
+
prompt_name=prompt_name,
|
|
151
|
+
phase=PROMPT_EVALUATION_PHASE_REQUEST,
|
|
152
|
+
provider_payload=deadline_provider_payload(deadline),
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
has_structured_output = prompt.structured_output is not None
|
|
156
|
+
should_disable_instructions = (
|
|
157
|
+
parse_output
|
|
158
|
+
and has_structured_output
|
|
159
|
+
and self._use_native_response_format
|
|
160
|
+
and getattr(prompt, "inject_output_instructions", False)
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
if should_disable_instructions:
|
|
164
|
+
rendered = prompt.render(
|
|
165
|
+
*params,
|
|
166
|
+
overrides_store=overrides_store,
|
|
167
|
+
tag=overrides_tag,
|
|
168
|
+
inject_output_instructions=False,
|
|
169
|
+
)
|
|
170
|
+
else:
|
|
171
|
+
rendered = prompt.render(
|
|
172
|
+
*params,
|
|
173
|
+
overrides_store=overrides_store,
|
|
174
|
+
tag=overrides_tag,
|
|
175
|
+
)
|
|
176
|
+
if deadline is not None:
|
|
177
|
+
rendered = replace(rendered, deadline=deadline)
|
|
178
|
+
response_format: dict[str, Any] | None = None
|
|
179
|
+
should_parse_structured_output = (
|
|
180
|
+
parse_output
|
|
181
|
+
and rendered.output_type is not None
|
|
182
|
+
and rendered.container is not None
|
|
183
|
+
)
|
|
184
|
+
if should_parse_structured_output and self._use_native_response_format:
|
|
185
|
+
response_format = build_json_schema_response_format(rendered, prompt_name)
|
|
186
|
+
|
|
187
|
+
def _call_provider(
|
|
188
|
+
messages: list[dict[str, Any]],
|
|
189
|
+
tool_specs: Sequence[Mapping[str, Any]],
|
|
190
|
+
tool_choice_directive: ToolChoice | None,
|
|
191
|
+
response_format_payload: Mapping[str, Any] | None,
|
|
192
|
+
) -> object:
|
|
193
|
+
request_payload: dict[str, Any] = {
|
|
194
|
+
"model": self._model,
|
|
195
|
+
"messages": messages,
|
|
196
|
+
}
|
|
197
|
+
if tool_specs:
|
|
198
|
+
request_payload["tools"] = list(tool_specs)
|
|
199
|
+
if tool_choice_directive is not None:
|
|
200
|
+
request_payload["tool_choice"] = tool_choice_directive
|
|
201
|
+
if response_format_payload is not None:
|
|
202
|
+
request_payload["response_format"] = response_format_payload
|
|
203
|
+
|
|
204
|
+
try:
|
|
205
|
+
return self._client.chat.completions.create(**request_payload)
|
|
206
|
+
except Exception as error: # pragma: no cover - network/SDK failure
|
|
207
|
+
raise PromptEvaluationError(
|
|
208
|
+
"OpenAI request failed.",
|
|
209
|
+
prompt_name=prompt_name,
|
|
210
|
+
phase=PROMPT_EVALUATION_PHASE_REQUEST,
|
|
211
|
+
) from error
|
|
212
|
+
|
|
213
|
+
def _select_choice(response: object) -> ProviderChoice:
|
|
214
|
+
return cast(
|
|
215
|
+
ProviderChoice,
|
|
216
|
+
first_choice(response, prompt_name=prompt_name),
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
return run_conversation(
|
|
220
|
+
adapter_name=OPENAI_ADAPTER_NAME,
|
|
221
|
+
adapter=cast("ProviderAdapter[OutputT]", self),
|
|
222
|
+
prompt=prompt,
|
|
223
|
+
prompt_name=prompt_name,
|
|
224
|
+
rendered=rendered,
|
|
225
|
+
render_inputs=render_inputs,
|
|
226
|
+
initial_messages=[{"role": "system", "content": rendered.text}],
|
|
227
|
+
parse_output=parse_output,
|
|
228
|
+
bus=bus,
|
|
229
|
+
session=session,
|
|
230
|
+
tool_choice=self._tool_choice,
|
|
231
|
+
response_format=response_format,
|
|
232
|
+
require_structured_output_text=False,
|
|
233
|
+
call_provider=_call_provider,
|
|
234
|
+
select_choice=_select_choice,
|
|
235
|
+
serialize_tool_message_fn=serialize_tool_message,
|
|
236
|
+
format_publish_failures=format_publish_failures,
|
|
237
|
+
parse_arguments=parse_tool_arguments,
|
|
238
|
+
logger_override=logger,
|
|
239
|
+
deadline=deadline,
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
__all__ = [
|
|
244
|
+
"OpenAIAdapter",
|
|
245
|
+
"OpenAIProtocol",
|
|
246
|
+
"extract_parsed_content",
|
|
247
|
+
"message_text_content",
|
|
248
|
+
"parse_schema_constrained_payload",
|
|
249
|
+
]
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
message_text_content = _shared.message_text_content
|
|
253
|
+
extract_parsed_content = _shared.extract_parsed_content
|
|
254
|
+
parse_schema_constrained_payload = _shared.parse_schema_constrained_payload
|