-
Notifications
You must be signed in to change notification settings - Fork 23
/
types.py
292 lines (234 loc) · 10.1 KB
/
types.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
"""Types for interacting with OpenAI models using Mirascope."""
from typing import Any, Callable, Literal, Optional, Type, Union
from httpx import Timeout
from openai import AsyncOpenAI, OpenAI
from openai._types import Body, Headers, Query
from openai.types import Embedding
from openai.types.chat import (
ChatCompletion,
ChatCompletionChunk,
ChatCompletionMessageToolCall,
ChatCompletionToolChoiceOptionParam,
)
from openai.types.chat.chat_completion import Choice
from openai.types.chat.chat_completion_chunk import Choice as ChunkChoice
from openai.types.chat.chat_completion_chunk import ChoiceDelta, ChoiceDeltaToolCall
from openai.types.chat.chat_completion_message import ChatCompletionMessage
from openai.types.chat.chat_completion_message_tool_call import Function
from openai.types.chat.completion_create_params import ResponseFormat
from openai.types.create_embedding_response import CreateEmbeddingResponse
from pydantic import ConfigDict
from ..base import (
BaseCallParams,
BaseCallResponse,
BaseCallResponseChunk,
)
from ..rag import BaseEmbeddingParams, BaseEmbeddingResponse
from .tools import OpenAITool
class OpenAICallParams(BaseCallParams[OpenAITool]):
"""The parameters to use when calling the OpenAI API."""
model: str = "gpt-3.5-turbo-0125"
frequency_penalty: Optional[float] = None
logit_bias: Optional[dict[str, int]] = None
logprobs: Optional[bool] = None
max_tokens: Optional[int] = None
n: Optional[int] = None
presence_penalty: Optional[float] = None
response_format: Optional[ResponseFormat] = None
seed: Optional[int] = None
stop: Union[Optional[str], list[str]] = None
temperature: Optional[float] = None
tool_choice: Optional[ChatCompletionToolChoiceOptionParam] = None
top_logprobs: Optional[int] = None
top_p: Optional[float] = None
user: Optional[str] = None
# Values defined below take precedence over values defined elsewhere. Use these
# params to pass additional parameters to the API if necessary that aren't already
# available as params.
extra_headers: Optional[Headers] = None
extra_query: Optional[Query] = None
extra_body: Optional[Body] = None
timeout: Optional[Union[float, Timeout]] = None
wrapper: Optional[Callable[[OpenAI], OpenAI]] = None
wrapper_async: Optional[Callable[[AsyncOpenAI], AsyncOpenAI]] = None
model_config = ConfigDict(arbitrary_types_allowed=True)
def kwargs(
self,
tool_type: Optional[Type[OpenAITool]] = OpenAITool,
exclude: Optional[set[str]] = None,
) -> dict[str, Any]:
"""Returns the keyword argument call parameters."""
extra_exclude = {"wrapper", "wrapper_async"}
exclude = extra_exclude if exclude is None else exclude.union(extra_exclude)
return super().kwargs(tool_type, exclude)
class OpenAICallResponse(BaseCallResponse[ChatCompletion, OpenAITool]):
"""A convenience wrapper around the OpenAI `ChatCompletion` response.
When using Mirascope's convenience wrappers to interact with OpenAI models via
`OpenAICall`, responses using `OpenAICall.call()` will return a
`OpenAICallResponse`, whereby the implemented properties allow for simpler syntax
and a convenient developer experience.
Example:
```python
from mirascope.openai import OpenAICall
class BookRecommender(OpenAICall):
prompt_template = "Please recommend a {genre} book"
genre: str
response = Bookrecommender(genre="fantasy").call()
print(response.content)
#> The Name of the Wind
print(response.message)
#> ChatCompletionMessage(content='The Name of the Wind', role='assistant',
# function_call=None, tool_calls=None)
print(response.choices)
#> [Choice(finish_reason='stop', index=0, logprobs=None,
# message=ChatCompletionMessage(content='The Name of the Wind', role='assistant',
# function_call=None, tool_calls=None))]
```
"""
response_format: Optional[ResponseFormat] = None
@property
def choices(self) -> list[Choice]:
"""Returns the array of chat completion choices."""
return self.response.choices
@property
def choice(self) -> Choice:
"""Returns the 0th choice."""
return self.choices[0]
@property
def message(self) -> ChatCompletionMessage:
"""Returns the message of the chat completion for the 0th choice."""
return self.choice.message
@property
def content(self) -> str:
"""Returns the content of the chat completion for the 0th choice."""
return self.message.content if self.message.content is not None else ""
@property
def tool_calls(self) -> Optional[list[ChatCompletionMessageToolCall]]:
"""Returns the tool calls for the 0th choice message."""
return self.message.tool_calls
@property
def tools(self) -> Optional[list[OpenAITool]]:
"""Returns the tools for the 0th choice message.
Raises:
ValidationError: if a tool call doesn't match the tool's schema.
"""
if not self.tool_types:
return None
if self.response_format != ResponseFormat(type="json_object"):
if not self.tool_calls:
return None
if self.choices[0].finish_reason not in ["tool_calls", "function_call"]:
raise RuntimeError(
"Finish reason was not `tool_calls` or `function_call`, indicating "
"no or failed tool use. This is likely due to a limit on output "
"tokens that is too low. Note that this could also indicate no "
"tool is beind called, so we recommend that you check the output "
"of the call to confirm. "
f"Finish Reason: {self.choices[0].finish_reason}"
)
else:
# Note: we only handle single tool calls in JSON mode.
tool_type = self.tool_types[0]
return [
tool_type.from_tool_call(
ChatCompletionMessageToolCall(
id="id",
function=Function(
name=tool_type.__name__, arguments=self.content
),
type="function",
)
)
]
extracted_tools = []
for tool_call in self.tool_calls:
for tool_type in self.tool_types:
if tool_call.function.name == tool_type.__name__:
extracted_tools.append(tool_type.from_tool_call(tool_call))
break
return extracted_tools
@property
def tool(self) -> Optional[OpenAITool]:
"""Returns the 0th tool for the 0th choice message.
Raises:
ValidationError: if the tool call doesn't match the tool's schema.
"""
tools = self.tools
if tools:
return tools[0]
return None
def dump(self) -> dict[str, Any]:
"""Dumps the response to a dictionary."""
return {
"start_time": self.start_time,
"end_time": self.end_time,
"output": self.response.model_dump(),
"cost": self.cost,
}
class OpenAICallResponseChunk(BaseCallResponseChunk[ChatCompletionChunk, OpenAITool]):
"""Convenience wrapper around chat completion streaming chunks.
When using Mirascope's convenience wrappers to interact with OpenAI models via
`OpenAICall.stream`, responses will return an `OpenAICallResponseChunk`, whereby
the implemented properties allow for simpler syntax and a convenient developer
experience.
Example:
```python
from mirascope.openai import OpenAICall
class Math(OpenAICall):
prompt_template = "What is 1 + 2?"
for chunk in OpenAICall().stream():
print(chunk.content)
#> 1
# +
# 2
# equals
#
# 3
# .
"""
response_format: Optional[ResponseFormat] = None
@property
def choices(self) -> list[ChunkChoice]:
"""Returns the array of chat completion choices."""
return self.chunk.choices
@property
def choice(self) -> ChunkChoice:
"""Returns the 0th choice."""
return self.chunk.choices[0]
@property
def delta(self) -> ChoiceDelta:
"""Returns the delta for the 0th choice."""
return self.choices[0].delta
@property
def content(self) -> str:
"""Returns the content for the 0th choice delta."""
return self.delta.content if self.delta.content is not None else ""
@property
def tool_calls(self) -> Optional[list[ChoiceDeltaToolCall]]:
"""Returns the partial tool calls for the 0th choice message.
The first `list[ChoiceDeltaToolCall]` will contain the name of the tool and
index, and subsequent `list[ChoiceDeltaToolCall]`s will contain the arguments
which will be strings that need to be concatenated with future
`list[ChoiceDeltaToolCall]`s to form a complete JSON tool calls. The last
`list[ChoiceDeltaToolCall]` will be None indicating end of stream.
"""
return self.delta.tool_calls
class OpenAIEmbeddingResponse(BaseEmbeddingResponse[CreateEmbeddingResponse]):
"""A convenience wrapper around the OpenAI `CreateEmbeddingResponse` response."""
@property
def embeddings(self) -> list[list[float]]:
"""Returns the raw embeddings."""
embeddings_model: list[Embedding] = [
embedding for embedding in self.response.data
]
return [embedding.embedding for embedding in embeddings_model]
class OpenAIEmbeddingParams(BaseEmbeddingParams):
model: str = "text-embedding-3-small"
encoding_format: Optional[Literal["float", "base64"]] = None
user: Optional[str] = None
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Optional[Headers] = None
extra_query: Optional[Query] = None
extra_body: Optional[Body] = None
timeout: Optional[Union[float, Timeout]] = None