pydantic-ai-slim 0.0.6__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.

Potentially problematic release.


This version of pydantic-ai-slim might be problematic. Click here for more details.

@@ -0,0 +1,379 @@
1
+ from __future__ import annotations as _annotations
2
+
3
+ from collections.abc import AsyncIterator, Iterable, Mapping, Sequence
4
+ from contextlib import asynccontextmanager
5
+ from dataclasses import dataclass, field
6
+ from datetime import datetime, timezone
7
+ from typing import Literal, overload
8
+
9
+ from httpx import AsyncClient as AsyncHTTPClient
10
+ from typing_extensions import assert_never
11
+
12
+ from .. import UnexpectedModelBehavior, _utils, result
13
+ from ..messages import (
14
+ ArgsJson,
15
+ Message,
16
+ ModelAnyResponse,
17
+ ModelStructuredResponse,
18
+ ModelTextResponse,
19
+ RetryPrompt,
20
+ ToolCall,
21
+ ToolReturn,
22
+ )
23
+ from ..result import Cost
24
+ from . import (
25
+ AbstractToolDefinition,
26
+ AgentModel,
27
+ EitherStreamedResponse,
28
+ Model,
29
+ StreamStructuredResponse,
30
+ StreamTextResponse,
31
+ cached_async_http_client,
32
+ check_allow_model_requests,
33
+ )
34
+
35
+ try:
36
+ from openai import NOT_GIVEN, AsyncOpenAI, AsyncStream
37
+ from openai.types import ChatModel, chat
38
+ from openai.types.chat import ChatCompletionChunk
39
+ from openai.types.chat.chat_completion_chunk import ChoiceDeltaToolCall
40
+ except ImportError as e:
41
+ raise ImportError(
42
+ 'Please install `openai` to use the OpenAI model, '
43
+ "you can use the `openai` optional group — `pip install 'pydantic-ai[openai]'`"
44
+ ) from e
45
+
46
+
47
+ @dataclass(init=False)
48
+ class OpenAIModel(Model):
49
+ """A model that uses the OpenAI API.
50
+
51
+ Internally, this uses the [OpenAI Python client](https://github.com/openai/openai-python) to interact with the API.
52
+
53
+ Apart from `__init__`, all methods are private or match those of the base class.
54
+ """
55
+
56
+ model_name: ChatModel
57
+ client: AsyncOpenAI = field(repr=False)
58
+
59
+ def __init__(
60
+ self,
61
+ model_name: ChatModel,
62
+ *,
63
+ api_key: str | None = None,
64
+ openai_client: AsyncOpenAI | None = None,
65
+ http_client: AsyncHTTPClient | None = None,
66
+ ):
67
+ """Initialize an OpenAI model.
68
+
69
+ Args:
70
+ model_name: The name of the OpenAI model to use. List of model names available
71
+ [here](https://github.com/openai/openai-python/blob/v1.54.3/src/openai/types/chat_model.py#L7)
72
+ (Unfortunately, despite being ask to do so, OpenAI do not provide `.inv` files for their API).
73
+ api_key: The API key to use for authentication, if not provided, the `OPENAI_API_KEY` environment variable
74
+ will be used if available.
75
+ openai_client: An existing
76
+ [`AsyncOpenAI`](https://github.com/openai/openai-python?tab=readme-ov-file#async-usage)
77
+ client to use, if provided, `api_key` and `http_client` must be `None`.
78
+ http_client: An existing `httpx.AsyncClient` to use for making HTTP requests.
79
+ """
80
+ self.model_name: ChatModel = model_name
81
+ if openai_client is not None:
82
+ assert http_client is None, 'Cannot provide both `openai_client` and `http_client`'
83
+ assert api_key is None, 'Cannot provide both `openai_client` and `api_key`'
84
+ self.client = openai_client
85
+ elif http_client is not None:
86
+ self.client = AsyncOpenAI(api_key=api_key, http_client=http_client)
87
+ else:
88
+ self.client = AsyncOpenAI(api_key=api_key, http_client=cached_async_http_client())
89
+
90
+ async def agent_model(
91
+ self,
92
+ retrievers: Mapping[str, AbstractToolDefinition],
93
+ allow_text_result: bool,
94
+ result_tools: Sequence[AbstractToolDefinition] | None,
95
+ ) -> AgentModel:
96
+ check_allow_model_requests()
97
+ tools = [self._map_tool_definition(r) for r in retrievers.values()]
98
+ if result_tools is not None:
99
+ tools += [self._map_tool_definition(r) for r in result_tools]
100
+ return OpenAIAgentModel(
101
+ self.client,
102
+ self.model_name,
103
+ allow_text_result,
104
+ tools,
105
+ )
106
+
107
+ def name(self) -> str:
108
+ return f'openai:{self.model_name}'
109
+
110
+ @staticmethod
111
+ def _map_tool_definition(f: AbstractToolDefinition) -> chat.ChatCompletionToolParam:
112
+ return {
113
+ 'type': 'function',
114
+ 'function': {
115
+ 'name': f.name,
116
+ 'description': f.description,
117
+ 'parameters': f.json_schema,
118
+ },
119
+ }
120
+
121
+
122
+ @dataclass
123
+ class OpenAIAgentModel(AgentModel):
124
+ """Implementation of `AgentModel` for OpenAI models."""
125
+
126
+ client: AsyncOpenAI
127
+ model_name: ChatModel
128
+ allow_text_result: bool
129
+ tools: list[chat.ChatCompletionToolParam]
130
+
131
+ async def request(self, messages: list[Message]) -> tuple[ModelAnyResponse, result.Cost]:
132
+ response = await self._completions_create(messages, False)
133
+ return self._process_response(response), _map_cost(response)
134
+
135
+ @asynccontextmanager
136
+ async def request_stream(self, messages: list[Message]) -> AsyncIterator[EitherStreamedResponse]:
137
+ response = await self._completions_create(messages, True)
138
+ async with response:
139
+ yield await self._process_streamed_response(response)
140
+
141
+ @overload
142
+ async def _completions_create(
143
+ self, messages: list[Message], stream: Literal[True]
144
+ ) -> AsyncStream[ChatCompletionChunk]:
145
+ pass
146
+
147
+ @overload
148
+ async def _completions_create(self, messages: list[Message], stream: Literal[False]) -> chat.ChatCompletion:
149
+ pass
150
+
151
+ async def _completions_create(
152
+ self, messages: list[Message], stream: bool
153
+ ) -> chat.ChatCompletion | AsyncStream[ChatCompletionChunk]:
154
+ # standalone function to make it easier to override
155
+ if not self.tools:
156
+ tool_choice: Literal['none', 'required', 'auto'] | None = None
157
+ elif not self.allow_text_result:
158
+ tool_choice = 'required'
159
+ else:
160
+ tool_choice = 'auto'
161
+
162
+ openai_messages = [self._map_message(m) for m in messages]
163
+ return await self.client.chat.completions.create(
164
+ model=self.model_name,
165
+ messages=openai_messages,
166
+ n=1,
167
+ parallel_tool_calls=True if self.tools else NOT_GIVEN,
168
+ tools=self.tools or NOT_GIVEN,
169
+ tool_choice=tool_choice or NOT_GIVEN,
170
+ stream=stream,
171
+ stream_options={'include_usage': True} if stream else NOT_GIVEN,
172
+ )
173
+
174
+ @staticmethod
175
+ def _process_response(response: chat.ChatCompletion) -> ModelAnyResponse:
176
+ """Process a non-streamed response, and prepare a message to return."""
177
+ timestamp = datetime.fromtimestamp(response.created, tz=timezone.utc)
178
+ choice = response.choices[0]
179
+ if choice.message.tool_calls is not None:
180
+ return ModelStructuredResponse(
181
+ [ToolCall.from_json(c.function.name, c.function.arguments, c.id) for c in choice.message.tool_calls],
182
+ timestamp=timestamp,
183
+ )
184
+ else:
185
+ assert choice.message.content is not None, choice
186
+ return ModelTextResponse(choice.message.content, timestamp=timestamp)
187
+
188
+ @staticmethod
189
+ async def _process_streamed_response(response: AsyncStream[ChatCompletionChunk]) -> EitherStreamedResponse:
190
+ """Process a streamed response, and prepare a streaming response to return."""
191
+ try:
192
+ first_chunk = await response.__anext__()
193
+ except StopAsyncIteration as e: # pragma: no cover
194
+ raise UnexpectedModelBehavior('Streamed response ended without content or tool calls') from e
195
+ timestamp = datetime.fromtimestamp(first_chunk.created, tz=timezone.utc)
196
+ delta = first_chunk.choices[0].delta
197
+ start_cost = _map_cost(first_chunk)
198
+
199
+ # the first chunk may only contain `role`, so we iterate until we get either `tool_calls` or `content`
200
+ while delta.tool_calls is None and delta.content is None:
201
+ try:
202
+ next_chunk = await response.__anext__()
203
+ except StopAsyncIteration as e:
204
+ raise UnexpectedModelBehavior('Streamed response ended without content or tool calls') from e
205
+ delta = next_chunk.choices[0].delta
206
+ start_cost += _map_cost(next_chunk)
207
+
208
+ if delta.content is not None:
209
+ return OpenAIStreamTextResponse(delta.content, response, timestamp, start_cost)
210
+ else:
211
+ assert delta.tool_calls is not None, f'Expected delta with tool_calls, got {delta}'
212
+ return OpenAIStreamStructuredResponse(
213
+ response,
214
+ {c.index: c for c in delta.tool_calls},
215
+ timestamp,
216
+ start_cost,
217
+ )
218
+
219
+ @staticmethod
220
+ def _map_message(message: Message) -> chat.ChatCompletionMessageParam:
221
+ """Just maps a `pydantic_ai.Message` to a `openai.types.ChatCompletionMessageParam`."""
222
+ if message.role == 'system':
223
+ # SystemPrompt ->
224
+ return chat.ChatCompletionSystemMessageParam(role='system', content=message.content)
225
+ elif message.role == 'user':
226
+ # UserPrompt ->
227
+ return chat.ChatCompletionUserMessageParam(role='user', content=message.content)
228
+ elif message.role == 'tool-return':
229
+ # ToolReturn ->
230
+ return chat.ChatCompletionToolMessageParam(
231
+ role='tool',
232
+ tool_call_id=_guard_tool_id(message),
233
+ content=message.model_response_str(),
234
+ )
235
+ elif message.role == 'retry-prompt':
236
+ # RetryPrompt ->
237
+ if message.tool_name is None:
238
+ return chat.ChatCompletionUserMessageParam(role='user', content=message.model_response())
239
+ else:
240
+ return chat.ChatCompletionToolMessageParam(
241
+ role='tool',
242
+ tool_call_id=_guard_tool_id(message),
243
+ content=message.model_response(),
244
+ )
245
+ elif message.role == 'model-text-response':
246
+ # ModelTextResponse ->
247
+ return chat.ChatCompletionAssistantMessageParam(role='assistant', content=message.content)
248
+ elif message.role == 'model-structured-response':
249
+ assert (
250
+ message.role == 'model-structured-response'
251
+ ), f'Expected role to be "llm-tool-calls", got {message.role}'
252
+ # ModelStructuredResponse ->
253
+ return chat.ChatCompletionAssistantMessageParam(
254
+ role='assistant',
255
+ tool_calls=[_map_tool_call(t) for t in message.calls],
256
+ )
257
+ else:
258
+ assert_never(message)
259
+
260
+
261
+ @dataclass
262
+ class OpenAIStreamTextResponse(StreamTextResponse):
263
+ """Implementation of `StreamTextResponse` for OpenAI models."""
264
+
265
+ _first: str | None
266
+ _response: AsyncStream[ChatCompletionChunk]
267
+ _timestamp: datetime
268
+ _cost: result.Cost
269
+ _buffer: list[str] = field(default_factory=list, init=False)
270
+
271
+ async def __anext__(self) -> None:
272
+ if self._first is not None:
273
+ self._buffer.append(self._first)
274
+ self._first = None
275
+ return None
276
+
277
+ chunk = await self._response.__anext__()
278
+ self._cost += _map_cost(chunk)
279
+ try:
280
+ choice = chunk.choices[0]
281
+ except IndexError:
282
+ raise StopAsyncIteration()
283
+
284
+ # we don't raise StopAsyncIteration on the last chunk because usage comes after this
285
+ if choice.finish_reason is None:
286
+ assert choice.delta.content is not None, f'Expected delta with content, invalid chunk: {chunk!r}'
287
+ if choice.delta.content is not None:
288
+ self._buffer.append(choice.delta.content)
289
+
290
+ def get(self, *, final: bool = False) -> Iterable[str]:
291
+ yield from self._buffer
292
+ self._buffer.clear()
293
+
294
+ def cost(self) -> Cost:
295
+ return self._cost
296
+
297
+ def timestamp(self) -> datetime:
298
+ return self._timestamp
299
+
300
+
301
+ @dataclass
302
+ class OpenAIStreamStructuredResponse(StreamStructuredResponse):
303
+ """Implementation of `StreamStructuredResponse` for OpenAI models."""
304
+
305
+ _response: AsyncStream[ChatCompletionChunk]
306
+ _delta_tool_calls: dict[int, ChoiceDeltaToolCall]
307
+ _timestamp: datetime
308
+ _cost: result.Cost
309
+
310
+ async def __anext__(self) -> None:
311
+ chunk = await self._response.__anext__()
312
+ self._cost += _map_cost(chunk)
313
+ try:
314
+ choice = chunk.choices[0]
315
+ except IndexError:
316
+ raise StopAsyncIteration()
317
+
318
+ if choice.finish_reason is not None:
319
+ raise StopAsyncIteration()
320
+
321
+ assert choice.delta.content is None, f'Expected tool calls, got content instead, invalid chunk: {chunk!r}'
322
+
323
+ for new in choice.delta.tool_calls or []:
324
+ if current := self._delta_tool_calls.get(new.index):
325
+ if current.function is None:
326
+ current.function = new.function
327
+ elif new.function is not None:
328
+ current.function.name = _utils.add_optional(current.function.name, new.function.name)
329
+ current.function.arguments = _utils.add_optional(current.function.arguments, new.function.arguments)
330
+ else:
331
+ self._delta_tool_calls[new.index] = new
332
+
333
+ def get(self, *, final: bool = False) -> ModelStructuredResponse:
334
+ calls: list[ToolCall] = []
335
+ for c in self._delta_tool_calls.values():
336
+ if f := c.function:
337
+ if f.name is not None and f.arguments is not None:
338
+ calls.append(ToolCall.from_json(f.name, f.arguments, c.id))
339
+
340
+ return ModelStructuredResponse(calls, timestamp=self._timestamp)
341
+
342
+ def cost(self) -> Cost:
343
+ return self._cost
344
+
345
+ def timestamp(self) -> datetime:
346
+ return self._timestamp
347
+
348
+
349
+ def _guard_tool_id(t: ToolCall | ToolReturn | RetryPrompt) -> str:
350
+ """Type guard that checks a `tool_id` is not None both for static typing and runtime."""
351
+ assert t.tool_id is not None, f'OpenAI requires `tool_id` to be set: {t}'
352
+ return t.tool_id
353
+
354
+
355
+ def _map_tool_call(t: ToolCall) -> chat.ChatCompletionMessageToolCallParam:
356
+ assert isinstance(t.args, ArgsJson), f'Expected ArgsJson, got {t.args}'
357
+ return chat.ChatCompletionMessageToolCallParam(
358
+ id=_guard_tool_id(t),
359
+ type='function',
360
+ function={'name': t.tool_name, 'arguments': t.args.args_json},
361
+ )
362
+
363
+
364
+ def _map_cost(response: chat.ChatCompletion | ChatCompletionChunk) -> result.Cost:
365
+ usage = response.usage
366
+ if usage is None:
367
+ return result.Cost()
368
+ else:
369
+ details: dict[str, int] = {}
370
+ if usage.completion_tokens_details is not None:
371
+ details.update(usage.completion_tokens_details.model_dump(exclude_none=True))
372
+ if usage.prompt_tokens_details is not None:
373
+ details.update(usage.prompt_tokens_details.model_dump(exclude_none=True))
374
+ return result.Cost(
375
+ request_tokens=usage.prompt_tokens,
376
+ response_tokens=usage.completion_tokens,
377
+ total_tokens=usage.total_tokens,
378
+ details=details,
379
+ )