agentforge-openai 0.2.3__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.
@@ -0,0 +1,16 @@
1
+ """`agentforge-openai` — OpenAI LLM + embedding provider."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from agentforge_openai._runner import OpenAIRunner
6
+ from agentforge_openai.client import OpenAIClient
7
+ from agentforge_openai.embedding import OpenAIEmbeddingClient
8
+
9
+ __version__ = "0.2.3"
10
+
11
+ __all__ = [
12
+ "OpenAIClient",
13
+ "OpenAIEmbeddingClient",
14
+ "OpenAIRunner",
15
+ "__version__",
16
+ ]
@@ -0,0 +1,141 @@
1
+ """In-memory `OpenAIRunner` for unit tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import AsyncIterator
6
+ from dataclasses import dataclass, field
7
+ from typing import Any
8
+
9
+
10
+ @dataclass
11
+ class _ChatCall:
12
+ model: str
13
+ messages: list[dict[str, Any]]
14
+ tools: list[dict[str, Any]] | None
15
+ timeout_s: float
16
+ extra: dict[str, Any] = field(default_factory=dict)
17
+
18
+
19
+ @dataclass
20
+ class _EmbedCall:
21
+ model: str
22
+ inputs: list[str]
23
+ timeout_s: float
24
+ dimensions: int | None
25
+
26
+
27
+ def _default_chat_response() -> dict[str, Any]:
28
+ return {
29
+ "id": "chatcmpl_test",
30
+ "model": "gpt-test",
31
+ "choices": [
32
+ {
33
+ "index": 0,
34
+ "message": {"role": "assistant", "content": ""},
35
+ "finish_reason": "stop",
36
+ },
37
+ ],
38
+ "usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0},
39
+ }
40
+
41
+
42
+ def _default_embedding_response(model: str, inputs: list[str], dims: int) -> dict[str, Any]:
43
+ return {
44
+ "model": model,
45
+ "data": [{"index": i, "embedding": [0.0] * dims} for i in range(len(inputs))],
46
+ "usage": {"prompt_tokens": sum(len(t) for t in inputs), "total_tokens": 0},
47
+ }
48
+
49
+
50
+ class FakeOpenAIRunner:
51
+ """In-memory recorder for unit tests."""
52
+
53
+ def __init__(self) -> None:
54
+ self._chat_response: dict[str, Any] = _default_chat_response()
55
+ self._stream_chunks: list[dict[str, Any]] = []
56
+ self._embedding_dims: int = 1536
57
+ self._embedding_response: dict[str, Any] | None = None
58
+ self.chat_calls: list[_ChatCall] = []
59
+ self.stream_calls: list[_ChatCall] = []
60
+ self.embedding_calls: list[_EmbedCall] = []
61
+ self.closed = False
62
+
63
+ def set_chat_response(self, response: dict[str, Any]) -> None:
64
+ self._chat_response = response
65
+
66
+ def set_stream_chunks(self, chunks: list[dict[str, Any]]) -> None:
67
+ self._stream_chunks = list(chunks)
68
+
69
+ def set_embedding_dims(self, dims: int) -> None:
70
+ self._embedding_dims = dims
71
+
72
+ def set_embedding_response(self, response: dict[str, Any]) -> None:
73
+ self._embedding_response = response
74
+
75
+ async def chat_completions_create(
76
+ self,
77
+ *,
78
+ model: str,
79
+ messages: list[dict[str, Any]],
80
+ tools: list[dict[str, Any]] | None,
81
+ timeout_s: float,
82
+ extra: dict[str, Any] | None = None,
83
+ ) -> dict[str, Any]:
84
+ self.chat_calls.append(
85
+ _ChatCall(
86
+ model=model,
87
+ messages=[dict(m) for m in messages],
88
+ tools=[dict(t) for t in tools] if tools else None,
89
+ timeout_s=timeout_s,
90
+ extra=dict(extra or {}),
91
+ ),
92
+ )
93
+ return self._chat_response
94
+
95
+ async def chat_completions_stream(
96
+ self,
97
+ *,
98
+ model: str,
99
+ messages: list[dict[str, Any]],
100
+ tools: list[dict[str, Any]] | None,
101
+ timeout_s: float,
102
+ extra: dict[str, Any] | None = None,
103
+ ) -> AsyncIterator[dict[str, Any]]:
104
+ self.stream_calls.append(
105
+ _ChatCall(
106
+ model=model,
107
+ messages=[dict(m) for m in messages],
108
+ tools=[dict(t) for t in tools] if tools else None,
109
+ timeout_s=timeout_s,
110
+ extra=dict(extra or {}),
111
+ ),
112
+ )
113
+ return _stream_iter(self._stream_chunks)
114
+
115
+ async def embeddings_create(
116
+ self,
117
+ *,
118
+ model: str,
119
+ inputs: list[str],
120
+ timeout_s: float,
121
+ dimensions: int | None = None,
122
+ ) -> dict[str, Any]:
123
+ self.embedding_calls.append(
124
+ _EmbedCall(
125
+ model=model, inputs=list(inputs), timeout_s=timeout_s, dimensions=dimensions
126
+ ),
127
+ )
128
+ if self._embedding_response is not None:
129
+ return self._embedding_response
130
+ return _default_embedding_response(model, inputs, dimensions or self._embedding_dims)
131
+
132
+ async def close(self) -> None:
133
+ self.closed = True
134
+
135
+
136
+ async def _stream_iter(chunks: list[dict[str, Any]]) -> AsyncIterator[dict[str, Any]]:
137
+ for c in chunks:
138
+ yield c
139
+
140
+
141
+ __all__ = ["FakeOpenAIRunner"]
@@ -0,0 +1,66 @@
1
+ """Per-model price table for OpenAI models.
2
+
3
+ Prices are USD per 1M tokens, snapshotted 2026-05-14 from
4
+ OpenAI's public pricing page. Embedding models use the same
5
+ shape but only `input` is meaningful.
6
+
7
+ A model not in the table returns `0.0` and we log a debug
8
+ message — callers see `cost_usd=0.0` rather than crashing.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+
15
+ log = logging.getLogger(__name__)
16
+
17
+ _CHAT_PRICES: dict[str, tuple[float, float]] = {
18
+ # Each entry: input / output USD per 1M tokens.
19
+ "gpt-4o": (2.50, 10.0),
20
+ "gpt-4o-mini": (0.15, 0.60),
21
+ "gpt-4.1": (3.0, 12.0),
22
+ "gpt-4.1-mini": (0.40, 1.60),
23
+ "gpt-4.1-nano": (0.10, 0.40),
24
+ "o3": (10.0, 40.0),
25
+ "o3-mini": (1.10, 4.40),
26
+ "o4-mini": (1.10, 4.40),
27
+ }
28
+
29
+ _EMBED_PRICES: dict[str, float] = {
30
+ # Each entry: USD per 1M input tokens (embeddings have no output).
31
+ "text-embedding-3-small": 0.02,
32
+ "text-embedding-3-large": 0.13,
33
+ "text-embedding-ada-002": 0.10,
34
+ }
35
+
36
+
37
+ def chat_cost_usd(model: str, *, input_tokens: int, output_tokens: int) -> float:
38
+ canonical = _canonical_chat(model)
39
+ prices = _CHAT_PRICES.get(canonical)
40
+ if prices is None:
41
+ log.debug("agentforge-openai: no chat-price entry for %r; cost_usd=0.0", model)
42
+ return 0.0
43
+ in_p, out_p = prices
44
+ return (input_tokens / 1_000_000) * in_p + (output_tokens / 1_000_000) * out_p
45
+
46
+
47
+ def embedding_cost_usd(model: str, *, input_tokens: int) -> float:
48
+ price = _EMBED_PRICES.get(model)
49
+ if price is None:
50
+ log.debug("agentforge-openai: no embedding-price entry for %r; cost_usd=0.0", model)
51
+ return 0.0
52
+ return (input_tokens / 1_000_000) * price
53
+
54
+
55
+ def _canonical_chat(model: str) -> str:
56
+ """Strip dated suffixes (`-2026-03-01`, `-20260301`) for lookup."""
57
+ # OpenAI uses `-YYYY-MM-DD` style suffixes; chop after the model
58
+ # family if a date-like tail is present.
59
+ for suffix_prefix in ("-2025", "-2026", "-2027", "-2028", "-2029", "-2030"):
60
+ idx = model.find(suffix_prefix)
61
+ if idx > 0:
62
+ return model[:idx]
63
+ return model
64
+
65
+
66
+ __all__ = ["chat_cost_usd", "embedding_cost_usd"]
@@ -0,0 +1,133 @@
1
+ """OpenAI runner Protocol + production SDK wrapper.
2
+
3
+ Protocol abstracts the three SDK calls we make (chat completions,
4
+ chat completions stream, embeddings) so unit tests don't need
5
+ `openai` in the dev venv. Production `_OpenAISDKRunner` wraps
6
+ `openai.AsyncOpenAI` under `# pragma: no cover`.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any, Protocol, cast
12
+
13
+
14
+ class OpenAIRunner(Protocol):
15
+ """Lifecycle Protocol for OpenAI API calls."""
16
+
17
+ async def chat_completions_create(
18
+ self,
19
+ *,
20
+ model: str,
21
+ messages: list[dict[str, Any]],
22
+ tools: list[dict[str, Any]] | None,
23
+ timeout_s: float,
24
+ extra: dict[str, Any] | None = None,
25
+ ) -> dict[str, Any]: # pragma: no cover
26
+ """Issue a non-streaming chat.completions.create call."""
27
+ ...
28
+
29
+ async def chat_completions_stream(
30
+ self,
31
+ *,
32
+ model: str,
33
+ messages: list[dict[str, Any]],
34
+ tools: list[dict[str, Any]] | None,
35
+ timeout_s: float,
36
+ extra: dict[str, Any] | None = None,
37
+ ) -> Any: # pragma: no cover
38
+ """Open a streaming chat.completions.create call.
39
+
40
+ Returns an async iterator over per-event chunks.
41
+ """
42
+ ...
43
+
44
+ async def embeddings_create(
45
+ self,
46
+ *,
47
+ model: str,
48
+ inputs: list[str],
49
+ timeout_s: float,
50
+ dimensions: int | None = None,
51
+ ) -> dict[str, Any]: # pragma: no cover
52
+ """Issue an embeddings.create call."""
53
+ ...
54
+
55
+ async def close(self) -> None: # pragma: no cover
56
+ """Release the underlying HTTP client."""
57
+ ...
58
+
59
+
60
+ class _OpenAISDKRunner: # pragma: no cover — exercised only with `-m live`.
61
+ """Production runner wrapping ``openai.AsyncOpenAI``."""
62
+
63
+ def __init__(self, client: Any) -> None:
64
+ self._client = client
65
+
66
+ async def chat_completions_create(
67
+ self,
68
+ *,
69
+ model: str,
70
+ messages: list[dict[str, Any]],
71
+ tools: list[dict[str, Any]] | None,
72
+ timeout_s: float,
73
+ extra: dict[str, Any] | None = None,
74
+ ) -> dict[str, Any]:
75
+ kwargs: dict[str, Any] = {
76
+ "model": model,
77
+ "messages": messages,
78
+ "timeout": timeout_s,
79
+ }
80
+ if tools:
81
+ kwargs["tools"] = tools
82
+ if extra:
83
+ kwargs.update(extra)
84
+ result = await self._client.chat.completions.create(**kwargs)
85
+ return cast("dict[str, Any]", result.model_dump(mode="python", exclude_none=False))
86
+
87
+ async def chat_completions_stream(
88
+ self,
89
+ *,
90
+ model: str,
91
+ messages: list[dict[str, Any]],
92
+ tools: list[dict[str, Any]] | None,
93
+ timeout_s: float,
94
+ extra: dict[str, Any] | None = None,
95
+ ) -> Any:
96
+ kwargs: dict[str, Any] = {
97
+ "model": model,
98
+ "messages": messages,
99
+ "stream": True,
100
+ "timeout": timeout_s,
101
+ "stream_options": {"include_usage": True},
102
+ }
103
+ if tools:
104
+ kwargs["tools"] = tools
105
+ if extra:
106
+ kwargs.update(extra)
107
+ return await self._client.chat.completions.create(**kwargs)
108
+
109
+ async def embeddings_create(
110
+ self,
111
+ *,
112
+ model: str,
113
+ inputs: list[str],
114
+ timeout_s: float,
115
+ dimensions: int | None = None,
116
+ ) -> dict[str, Any]:
117
+ kwargs: dict[str, Any] = {
118
+ "model": model,
119
+ "input": inputs,
120
+ "timeout": timeout_s,
121
+ }
122
+ if dimensions is not None:
123
+ kwargs["dimensions"] = dimensions
124
+ result = await self._client.embeddings.create(**kwargs)
125
+ return cast("dict[str, Any]", result.model_dump(mode="python", exclude_none=False))
126
+
127
+ async def close(self) -> None:
128
+ close = getattr(self._client, "close", None)
129
+ if callable(close):
130
+ await close()
131
+
132
+
133
+ __all__ = ["OpenAIRunner"]
@@ -0,0 +1,356 @@
1
+ """`OpenAIClient` — `LLMClient` over OpenAI's chat.completions API.
2
+
3
+ Maps framework shapes onto OpenAI's request/response model:
4
+
5
+ - System prompt → first `{"role": "system", ...}` element in messages.
6
+ - Messages → `[{"role": ..., "content": ...}]`.
7
+ Tool result messages encode with `role="tool"` + `tool_call_id`.
8
+ - Tools → `[{"type": "function", "function": {...}}]`.
9
+
10
+ Finish reasons normalised:
11
+ stop / length / tool_calls / function_call / content_filter →
12
+ end_turn / max_tokens / tool_use / tool_use / other
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from collections.abc import AsyncIterator
18
+ from typing import TYPE_CHECKING, Any
19
+
20
+ from agentforge_core.contracts.llm import LLMClient
21
+ from agentforge_core.production.exceptions import ModuleError
22
+ from agentforge_core.resolver import register_provider
23
+ from agentforge_core.values.messages import (
24
+ LLMResponse,
25
+ Message,
26
+ StopReason,
27
+ StreamChunk,
28
+ TokenUsage,
29
+ ToolCall,
30
+ ToolSpec,
31
+ )
32
+
33
+ from agentforge_openai._pricing import chat_cost_usd
34
+
35
+ if TYPE_CHECKING:
36
+ from agentforge_openai._runner import OpenAIRunner
37
+
38
+
39
+ _PROVIDER_NAME = "openai"
40
+ _DEFAULT_TIMEOUT_SECONDS = 60.0
41
+
42
+ _FINISH_REASON_MAP: dict[str, StopReason] = {
43
+ "stop": "end_turn",
44
+ "length": "max_tokens",
45
+ "tool_calls": "tool_use",
46
+ "function_call": "tool_use",
47
+ "content_filter": "other",
48
+ }
49
+
50
+ _VISION_MODELS = frozenset({"gpt-4o", "gpt-4o-mini", "gpt-4.1", "gpt-4.1-mini", "gpt-4.1-nano"})
51
+
52
+
53
+ @register_provider("openai")
54
+ class OpenAIClient(LLMClient):
55
+ """`LLMClient` over OpenAI's chat.completions API."""
56
+
57
+ def __init__(
58
+ self,
59
+ *,
60
+ model_id: str,
61
+ runner: OpenAIRunner | None = None,
62
+ api_key: str | None = None,
63
+ base_url: str | None = None,
64
+ organization: str | None = None,
65
+ timeout_seconds: float = _DEFAULT_TIMEOUT_SECONDS,
66
+ json_mode: bool = False,
67
+ ) -> None:
68
+ if not model_id:
69
+ raise ValueError("model_id must be a non-empty string")
70
+ if timeout_seconds <= 0:
71
+ raise ValueError("timeout_seconds must be > 0")
72
+ self._runner = (
73
+ runner
74
+ if runner is not None
75
+ else _build_sdk_runner(
76
+ api_key=api_key,
77
+ base_url=base_url,
78
+ organization=organization,
79
+ )
80
+ )
81
+ self._model = model_id
82
+ self._timeout_seconds = timeout_seconds
83
+ self._json_mode = json_mode
84
+
85
+ @classmethod
86
+ def from_config(
87
+ cls,
88
+ *,
89
+ model: str,
90
+ api_key: str | None = None,
91
+ base_url: str | None = None,
92
+ organization: str | None = None,
93
+ timeout_seconds: float = _DEFAULT_TIMEOUT_SECONDS,
94
+ json_mode: bool = False,
95
+ ) -> OpenAIClient: # pragma: no cover — exercised only with `-m live`.
96
+ """Build an `OpenAIClient` backed by a real `openai.AsyncOpenAI`."""
97
+ return cls(
98
+ model_id=model,
99
+ api_key=api_key,
100
+ base_url=base_url,
101
+ organization=organization,
102
+ timeout_seconds=timeout_seconds,
103
+ json_mode=json_mode,
104
+ )
105
+
106
+ def capabilities(self) -> set[str]:
107
+ caps = {"tools", "json_mode", "streaming"}
108
+ if _canonical_chat(self._model) in _VISION_MODELS:
109
+ caps.add("vision")
110
+ return caps
111
+
112
+ async def call(
113
+ self,
114
+ system: str,
115
+ messages: list[Message],
116
+ tools: list[ToolSpec] | None = None,
117
+ ) -> LLMResponse:
118
+ raw = await self._runner.chat_completions_create(
119
+ model=self._model,
120
+ messages=_build_messages(system, messages),
121
+ tools=_tools_to_openai(tools),
122
+ timeout_s=self._timeout_seconds,
123
+ extra=self._extra_kwargs(),
124
+ )
125
+ return self._normalise_response(raw)
126
+
127
+ def stream(
128
+ self,
129
+ system: str,
130
+ messages: list[Message],
131
+ tools: list[ToolSpec] | None = None,
132
+ ) -> AsyncIterator[StreamChunk]:
133
+ return self._stream_request(system=system, messages=messages, tools=tools)
134
+
135
+ async def close(self) -> None:
136
+ await self._runner.close()
137
+
138
+ # ------------------------------------------------------------------
139
+ # Internal
140
+ # ------------------------------------------------------------------
141
+
142
+ def _extra_kwargs(self) -> dict[str, Any] | None:
143
+ if self._json_mode:
144
+ return {"response_format": {"type": "json_object"}}
145
+ return None
146
+
147
+ async def _stream_request(
148
+ self,
149
+ *,
150
+ system: str,
151
+ messages: list[Message],
152
+ tools: list[ToolSpec] | None,
153
+ ) -> AsyncIterator[StreamChunk]:
154
+ stream = await self._runner.chat_completions_stream(
155
+ model=self._model,
156
+ messages=_build_messages(system, messages),
157
+ tools=_tools_to_openai(tools),
158
+ timeout_s=self._timeout_seconds,
159
+ extra=self._extra_kwargs(),
160
+ )
161
+ tool_buffers: dict[int, dict[str, Any]] = {}
162
+ stop_reason: StopReason = "end_turn"
163
+ usage = TokenUsage(input_tokens=0, output_tokens=0)
164
+
165
+ async for event in stream:
166
+ for choice in event.get("choices", []) or []:
167
+ delta = choice.get("delta") or {}
168
+ text = delta.get("content")
169
+ if text:
170
+ yield StreamChunk(kind="text", delta=text)
171
+ for tc in delta.get("tool_calls") or []:
172
+ idx = int(tc.get("index", 0))
173
+ buf = tool_buffers.setdefault(
174
+ idx,
175
+ {"id": "", "name": "", "input_json": ""},
176
+ )
177
+ if tc.get("id"):
178
+ buf["id"] = tc["id"]
179
+ fn = tc.get("function") or {}
180
+ if fn.get("name"):
181
+ buf["name"] = fn["name"]
182
+ if fn.get("arguments"):
183
+ buf["input_json"] += fn["arguments"]
184
+ finish_raw = choice.get("finish_reason")
185
+ if finish_raw:
186
+ stop_reason = _FINISH_REASON_MAP.get(finish_raw, "other")
187
+ usage_raw = event.get("usage")
188
+ if usage_raw:
189
+ usage = TokenUsage(
190
+ input_tokens=int(usage_raw.get("prompt_tokens", 0)),
191
+ output_tokens=int(usage_raw.get("completion_tokens", 0)),
192
+ )
193
+
194
+ for buf in tool_buffers.values():
195
+ import json as _json # noqa: PLC0415
196
+
197
+ try:
198
+ args = _json.loads(buf["input_json"]) if buf["input_json"] else {}
199
+ except _json.JSONDecodeError:
200
+ args = {}
201
+ if not isinstance(args, dict):
202
+ args = {}
203
+ yield StreamChunk(
204
+ kind="tool_call",
205
+ tool_call=ToolCall(id=buf["id"], name=buf["name"], arguments=args),
206
+ )
207
+
208
+ cost = chat_cost_usd(
209
+ self._model,
210
+ input_tokens=usage.input_tokens,
211
+ output_tokens=usage.output_tokens,
212
+ )
213
+ yield StreamChunk(
214
+ kind="stop",
215
+ stop_reason=stop_reason,
216
+ usage=usage,
217
+ cost_usd=cost,
218
+ )
219
+
220
+ def _normalise_response(self, raw: dict[str, Any]) -> LLMResponse:
221
+ choices = raw.get("choices") or []
222
+ choice0 = choices[0] if choices else {}
223
+ msg = choice0.get("message") or {}
224
+
225
+ content = msg.get("content") or ""
226
+ if isinstance(content, list):
227
+ # gpt-4o may return content as a list of parts; flatten text parts.
228
+ content = "".join(
229
+ part.get("text", "")
230
+ for part in content
231
+ if isinstance(part, dict) and part.get("type") == "text"
232
+ )
233
+
234
+ tool_calls: list[ToolCall] = []
235
+ for tc in msg.get("tool_calls") or []:
236
+ fn = tc.get("function") or {}
237
+ args_raw = fn.get("arguments") or "{}"
238
+ import json as _json # noqa: PLC0415
239
+
240
+ try:
241
+ args = _json.loads(args_raw)
242
+ except _json.JSONDecodeError:
243
+ args = {}
244
+ if not isinstance(args, dict):
245
+ args = {}
246
+ tool_calls.append(
247
+ ToolCall(id=tc.get("id", ""), name=fn.get("name", ""), arguments=args)
248
+ )
249
+
250
+ usage_raw = raw.get("usage") or {}
251
+ usage = TokenUsage(
252
+ input_tokens=int(usage_raw.get("prompt_tokens", 0)),
253
+ output_tokens=int(usage_raw.get("completion_tokens", 0)),
254
+ )
255
+
256
+ finish_raw = choice0.get("finish_reason") or "stop"
257
+ stop_reason: StopReason = _FINISH_REASON_MAP.get(finish_raw, "other")
258
+
259
+ cost = chat_cost_usd(
260
+ self._model,
261
+ input_tokens=usage.input_tokens,
262
+ output_tokens=usage.output_tokens,
263
+ )
264
+
265
+ return LLMResponse(
266
+ content=content,
267
+ tool_calls=tuple(tool_calls),
268
+ stop_reason=stop_reason,
269
+ usage=usage,
270
+ cost_usd=cost,
271
+ model=raw.get("model", self._model),
272
+ provider=_PROVIDER_NAME,
273
+ )
274
+
275
+
276
+ # ----------------------------------------------------------------------
277
+ # Helpers
278
+ # ----------------------------------------------------------------------
279
+
280
+
281
+ def _build_messages(system: str, messages: list[Message]) -> list[dict[str, Any]]:
282
+ """Build the OpenAI messages list. System prompt becomes the first
283
+ element when non-empty."""
284
+ out: list[dict[str, Any]] = []
285
+ if system:
286
+ out.append({"role": "system", "content": system})
287
+ out.extend(_message_to_openai(m) for m in messages)
288
+ return out
289
+
290
+
291
+ def _message_to_openai(message: Message) -> dict[str, Any]:
292
+ if message.role == "tool":
293
+ return {
294
+ "role": "tool",
295
+ "tool_call_id": message.tool_call_id or "",
296
+ "content": message.content,
297
+ }
298
+ if message.role == "system":
299
+ # Should be hoisted by the caller; defensive passthrough.
300
+ return {"role": "system", "content": message.content}
301
+ return {"role": message.role, "content": message.content}
302
+
303
+
304
+ def _tools_to_openai(tools: list[ToolSpec] | None) -> list[dict[str, Any]] | None:
305
+ if not tools:
306
+ return None
307
+ return [
308
+ {
309
+ "type": "function",
310
+ "function": {
311
+ "name": t.name,
312
+ "description": t.description,
313
+ "parameters": t.schema_,
314
+ },
315
+ }
316
+ for t in tools
317
+ ]
318
+
319
+
320
+ def _canonical_chat(model: str) -> str:
321
+ for suffix_prefix in ("-2025", "-2026", "-2027", "-2028", "-2029", "-2030"):
322
+ idx = model.find(suffix_prefix)
323
+ if idx > 0:
324
+ return model[:idx]
325
+ return model
326
+
327
+
328
+ def _build_sdk_runner( # pragma: no cover — `-m live` only.
329
+ *,
330
+ api_key: str | None,
331
+ base_url: str | None,
332
+ organization: str | None,
333
+ ) -> OpenAIRunner:
334
+ try:
335
+ import openai # noqa: PLC0415
336
+ except ImportError as exc:
337
+ msg = (
338
+ "openai is not installed. Install via "
339
+ "`pip install agentforge-openai[openai]` to use the production runner."
340
+ )
341
+ raise ModuleError(msg) from exc
342
+
343
+ from agentforge_openai._runner import _OpenAISDKRunner # noqa: PLC0415
344
+
345
+ kwargs: dict[str, Any] = {}
346
+ if api_key:
347
+ kwargs["api_key"] = api_key
348
+ if base_url:
349
+ kwargs["base_url"] = base_url
350
+ if organization:
351
+ kwargs["organization"] = organization
352
+ client = openai.AsyncOpenAI(**kwargs)
353
+ return _OpenAISDKRunner(client)
354
+
355
+
356
+ __all__ = ["OpenAIClient"]
@@ -0,0 +1,169 @@
1
+ """`OpenAIEmbeddingClient` — `EmbeddingClient` over OpenAI's
2
+ `embeddings.create()` API.
3
+
4
+ Supports `text-embedding-3-small` (1536 dims), `text-embedding-3-large`
5
+ (3072 dims), and the legacy `text-embedding-ada-002` (1536 dims).
6
+ The `text-embedding-3-*` models support Matryoshka-style truncation
7
+ via the `dimensions=` API parameter; declaring that capability lets
8
+ callers ask for a shorter vector at construction time.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import TYPE_CHECKING
14
+
15
+ from agentforge_core.contracts.embedding import EmbeddingClient
16
+ from agentforge_core.production.exceptions import ModuleError
17
+ from agentforge_core.resolver import register_embedding_provider
18
+ from agentforge_core.values.messages import EmbeddingResponse, TokenUsage
19
+
20
+ from agentforge_openai._pricing import embedding_cost_usd
21
+
22
+ if TYPE_CHECKING:
23
+ from agentforge_openai._runner import OpenAIRunner
24
+
25
+
26
+ _PROVIDER_NAME = "openai"
27
+ _DEFAULT_TIMEOUT_SECONDS = 30.0
28
+
29
+ _MODEL_DIMS: dict[str, int] = {
30
+ "text-embedding-3-small": 1536,
31
+ "text-embedding-3-large": 3072,
32
+ "text-embedding-ada-002": 1536,
33
+ }
34
+
35
+ _MATRYOSHKA_MODELS = frozenset({"text-embedding-3-small", "text-embedding-3-large"})
36
+
37
+
38
+ @register_embedding_provider("openai")
39
+ class OpenAIEmbeddingClient(EmbeddingClient):
40
+ """`EmbeddingClient` over OpenAI's embeddings API."""
41
+
42
+ def __init__(
43
+ self,
44
+ *,
45
+ runner: OpenAIRunner,
46
+ model: str,
47
+ dimensions: int | None = None,
48
+ timeout_seconds: float = _DEFAULT_TIMEOUT_SECONDS,
49
+ ) -> None:
50
+ if not model:
51
+ raise ValueError("model must be a non-empty string")
52
+ if timeout_seconds <= 0:
53
+ raise ValueError("timeout_seconds must be > 0")
54
+ native = _MODEL_DIMS.get(model)
55
+ if dimensions is not None:
56
+ if dimensions < 1:
57
+ raise ValueError("dimensions must be >= 1")
58
+ if native is not None and dimensions > native:
59
+ raise ValueError(
60
+ f"dimensions={dimensions} exceeds native={native} for {model}",
61
+ )
62
+ if dimensions != native and model not in _MATRYOSHKA_MODELS:
63
+ raise ValueError(
64
+ f"{model} does not support dimension override (Matryoshka)",
65
+ )
66
+ self._runner = runner
67
+ self._model = model
68
+ self._dimensions = dimensions if dimensions is not None else native or 1536
69
+ self._dim_arg: int | None = dimensions if dimensions != native else None
70
+ self._timeout_seconds = timeout_seconds
71
+
72
+ @classmethod
73
+ def from_config(
74
+ cls,
75
+ *,
76
+ model: str,
77
+ api_key: str | None = None,
78
+ base_url: str | None = None,
79
+ organization: str | None = None,
80
+ dimensions: int | None = None,
81
+ timeout_seconds: float = _DEFAULT_TIMEOUT_SECONDS,
82
+ ) -> OpenAIEmbeddingClient: # pragma: no cover — exercised only with `-m live`.
83
+ runner = _build_sdk_runner(
84
+ api_key=api_key,
85
+ base_url=base_url,
86
+ organization=organization,
87
+ )
88
+ return cls(
89
+ runner=runner,
90
+ model=model,
91
+ dimensions=dimensions,
92
+ timeout_seconds=timeout_seconds,
93
+ )
94
+
95
+ def dimensions(self) -> int:
96
+ return self._dimensions
97
+
98
+ def capabilities(self) -> set[str]:
99
+ if self._model in _MATRYOSHKA_MODELS:
100
+ return {"matryoshka"}
101
+ return set()
102
+
103
+ async def embed(self, texts: list[str]) -> EmbeddingResponse:
104
+ if not texts:
105
+ raise ValueError("texts must contain at least one item")
106
+ raw = await self._runner.embeddings_create(
107
+ model=self._model,
108
+ inputs=texts,
109
+ timeout_s=self._timeout_seconds,
110
+ dimensions=self._dim_arg,
111
+ )
112
+ data = raw.get("data") or []
113
+ vectors = tuple(tuple(float(v) for v in item.get("embedding") or []) for item in data)
114
+ if any(len(v) != self._dimensions for v in vectors):
115
+ raise ValueError(
116
+ f"OpenAI returned vector with unexpected dimensionality; "
117
+ f"expected {self._dimensions}, got "
118
+ f"{[len(v) for v in vectors]}",
119
+ )
120
+ usage_raw = raw.get("usage") or {}
121
+ usage = TokenUsage(
122
+ input_tokens=int(usage_raw.get("prompt_tokens", 0)),
123
+ output_tokens=0,
124
+ )
125
+ cost = embedding_cost_usd(self._model, input_tokens=usage.input_tokens)
126
+ return EmbeddingResponse(
127
+ vectors=vectors,
128
+ dimensions=self._dimensions,
129
+ usage=usage,
130
+ cost_usd=cost,
131
+ model=self._model,
132
+ provider=_PROVIDER_NAME,
133
+ )
134
+
135
+ async def close(self) -> None:
136
+ await self._runner.close()
137
+
138
+
139
+ def _build_sdk_runner( # pragma: no cover — `-m live` only.
140
+ *,
141
+ api_key: str | None,
142
+ base_url: str | None,
143
+ organization: str | None,
144
+ ) -> OpenAIRunner:
145
+ try:
146
+ import openai # noqa: PLC0415
147
+ except ImportError as exc:
148
+ msg = (
149
+ "openai is not installed. Install via "
150
+ "`pip install agentforge-openai[openai]` to use the production runner."
151
+ )
152
+ raise ModuleError(msg) from exc
153
+
154
+ from typing import Any # noqa: PLC0415
155
+
156
+ from agentforge_openai._runner import _OpenAISDKRunner # noqa: PLC0415
157
+
158
+ kwargs: dict[str, Any] = {}
159
+ if api_key:
160
+ kwargs["api_key"] = api_key
161
+ if base_url:
162
+ kwargs["base_url"] = base_url
163
+ if organization:
164
+ kwargs["organization"] = organization
165
+ client = openai.AsyncOpenAI(**kwargs)
166
+ return _OpenAISDKRunner(client)
167
+
168
+
169
+ __all__ = ["OpenAIEmbeddingClient"]
File without changes
@@ -0,0 +1,72 @@
1
+ Metadata-Version: 2.4
2
+ Name: agentforge-openai
3
+ Version: 0.2.3
4
+ Summary: OpenAI LLM + embeddings provider for AgentForge — gpt-4o / o-series + text-embedding-3-*
5
+ Project-URL: Homepage, https://github.com/Scaffoldic/agentforge-py
6
+ Project-URL: Repository, https://github.com/Scaffoldic/agentforge-py
7
+ Project-URL: Documentation, https://github.com/Scaffoldic/agentforge-py
8
+ Project-URL: Changelog, https://github.com/Scaffoldic/agentforge-py/blob/main/CHANGELOG.md
9
+ Project-URL: Issues, https://github.com/Scaffoldic/agentforge-py/issues
10
+ Author: The AgentForge Authors
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ Keywords: agent,ai,embeddings,gpt,llm,openai
14
+ Classifier: Development Status :: 2 - Pre-Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: Apache Software License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.13
22
+ Requires-Dist: agentforge-core~=0.2.3
23
+ Provides-Extra: openai
24
+ Requires-Dist: openai>=1.50; extra == 'openai'
25
+ Description-Content-Type: text/markdown
26
+
27
+ # agentforge-openai
28
+
29
+ OpenAI native LLM + embedding provider for
30
+ [AgentForge](https://github.com/Scaffoldic/agentforge-py).
31
+
32
+ Implements both `LLMClient` and `EmbeddingClient` against
33
+ OpenAI's `chat.completions.create()` (gpt-4o / o-series) and
34
+ `embeddings.create()` (text-embedding-3-small / -large).
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ pip install "agentforge-openai[openai]"
40
+ ```
41
+
42
+ The bare `pip install agentforge-openai` install keeps the
43
+ package importable for tests; the production runner needs the
44
+ `openai` SDK, which the `[openai]` extra pulls in.
45
+
46
+ ## Use
47
+
48
+ ```python
49
+ from agentforge import Agent
50
+ from agentforge_openai import OpenAIClient, OpenAIEmbeddingClient
51
+
52
+ # Chat
53
+ agent = Agent(model="openai:gpt-4o-mini")
54
+
55
+ # Embeddings (direct construction)
56
+ emb = OpenAIEmbeddingClient.from_config(
57
+ model="text-embedding-3-small",
58
+ api_key="sk-...",
59
+ )
60
+ ```
61
+
62
+ ## Capabilities
63
+
64
+ `OpenAIClient.capabilities()` declares: `tools`, `json_mode`,
65
+ `streaming`, `vision` (for `gpt-4o*` variants). Caching and
66
+ extended thinking are not surfaced (OpenAI handles caching
67
+ transparently; o-series internal reasoning is not exposed as a
68
+ budget-able knob through the public API today).
69
+
70
+ ## License
71
+
72
+ Apache-2.0. See [LICENSE](./LICENSE).
@@ -0,0 +1,12 @@
1
+ agentforge_openai/__init__.py,sha256=0ixKj61sA2M49A5gGw34gKK1dSRbviHY56tlGNNRAVA,389
2
+ agentforge_openai/_inmem_runner.py,sha256=YVUPOA6vb-iNmhtSZxNfEo2BHXyqOcKNg8Yob8cdF4Y,4185
3
+ agentforge_openai/_pricing.py,sha256=05SCZQBefyMEtCispe8272iVZo4MUbtS0D1uU6syFNc,2130
4
+ agentforge_openai/_runner.py,sha256=2Qe1PCiH5tl2RkdjN5Rgh96XxGA1lK4h01GNqlDUtNU,3908
5
+ agentforge_openai/client.py,sha256=KKXHOhgT36avFOA8ehTG64p5R4HX1FIEWA3WcBHYHho,11584
6
+ agentforge_openai/embedding.py,sha256=z3e_ZBs6sJyGSbjZnJH1YfsF1T-vxm8dRriLpwpiQXU,5680
7
+ agentforge_openai/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ agentforge_openai-0.2.3.dist-info/METADATA,sha256=5J1zTOJQ8iDbWMHAfEK40zbEfRCKItoqO0y3tgfNebA,2393
9
+ agentforge_openai-0.2.3.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
10
+ agentforge_openai-0.2.3.dist-info/entry_points.txt,sha256=mReMRyQTZw8JHBXBrYf7B2uzGbbugQNZ_M21FOThkKk,137
11
+ agentforge_openai-0.2.3.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
12
+ agentforge_openai-0.2.3.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,5 @@
1
+ [agentforge.embeddings]
2
+ openai = agentforge_openai:OpenAIEmbeddingClient
3
+
4
+ [agentforge.providers]
5
+ openai = agentforge_openai:OpenAIClient
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.