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