Skip to content

Commit f1bd135

Browse files
committed
publish next version
1 parent ffe752d commit f1bd135

File tree

9 files changed

+587
-15
lines changed

9 files changed

+587
-15
lines changed

CHANGELOG.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
11
# Changelogs
22

3+
#### v0.0.53 (2024-05-31)
4+
5+
- Added support for new `gpt-4-o` model
6+
- Added support for external providers
7+
- Update certain validation behavior of Functions
8+
9+
- TODO: Add batch create support
10+
311
#### v0.0.52 (2024-02-28)
412

513
- Added support for the following parameters in `model_configurations` in `OpenAIManager`:

async_openai/manager.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -765,9 +765,21 @@ def register_client_endpoints(self): # sourcery skip: low-code-quality
765765
config['api_base'] = self.settings.proxy.endpoint
766766
_has_proxy = True
767767
c = self.init_api_client(name, is_azure = is_azure, set_as_default = is_default, **config)
768-
msg = f'Registered: `|g|{c.name}|e|` @ `{source_endpoint or c.base_url}` (Azure: {c.is_azure}, Px: {_has_proxy}'
769-
if has_weights: msg += f', Weight: {client_weight}'
770-
msg += ')'
768+
msg = f'Registered: `|g|{c.name}|e|` @ `{source_endpoint or c.base_url}`'
769+
extra_msgs = []
770+
if has_weights:
771+
if isinstance(client_weight, float):
772+
_wp, _wsfx = '|g|', '|e|'
773+
if client_weight <= 0.0:
774+
_wp, _wsfx = '', ''
775+
elif client_weight <= 0.25: _wp = '|r|'
776+
elif client_weight <= 0.45: _wp = '|y|'
777+
extra_msgs.append(f'Weight: {_wp}{client_weight}{_wsfx}')
778+
else:
779+
extra_msgs.append(f'Weight: {client_weight}')
780+
if c.is_azure: extra_msgs.append('Azure')
781+
if _has_proxy: extra_msgs.append('Proxied')
782+
if extra_msgs: msg += f' ({", ".join(extra_msgs)})'
771783
logger.info(msg, colored = True)
772784

773785
# Set the models for inclusion

async_openai/types/functions.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -524,7 +524,7 @@ def parse_response(
524524
"""
525525
schema = schema or self.schema
526526
try:
527-
result = schema.model_validate(response.function_results[0].arguments, from_attributes = True)
527+
result = schema.model_validate(response.function_results[0].arguments, from_attributes = True, context = {'source': 'function'})
528528
result._set_values_from_response(response, name = self.name if include_name else None, client_name = client_name)
529529
return result
530530
except IndexError as e:
@@ -533,7 +533,7 @@ def parse_response(
533533
except Exception as e:
534534
self.autologger.error(f"[{self.name} - {response.model} - {response.usage}] Failed to parse object: {e}\n{response.text}\n{response.function_results[0].arguments}")
535535
try:
536-
result = schema.model_validate(resolve_json(response.function_results[0].arguments), from_attributes = True)
536+
result = schema.model_validate(resolve_json(response.function_results[0].arguments), from_attributes = True, context = {'source': 'function'})
537537
result._set_values_from_response(response, name = self.name if include_name else None)
538538
return result
539539
except Exception as e:

async_openai/types/options.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,7 @@ class FilePurpose(str, Enum):
194194
fine_tune = "fine-tune"
195195
train = "fine-tune-train"
196196
search = "search"
197+
batch = "batch"
197198

198199
@classmethod
199200
def parse_str(cls, value: Union[str, 'FilePurpose'], raise_error: bool = True):
@@ -206,6 +207,8 @@ def parse_str(cls, value: Union[str, 'FilePurpose'], raise_error: bool = True):
206207
return cls.fine_tune
207208
elif "search" in value:
208209
return cls.search
210+
elif "batch" in value:
211+
return cls.batch
209212
if not raise_error: return None
210213
raise ValueError(f"Cannot convert {value} to FilePurpose")
211214

async_openai/types/pricing.yaml

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,32 @@ gpt-4-0125-preview:
2424
endpoints:
2525
- chat
2626

27+
gpt-4-turbo-2024-04-09:
28+
aliases:
29+
- gpt-4-turbo-2024
30+
- gpt-4-turbo-2024-04-09
31+
- gpt-4-2024-preview
32+
context_length: 128000
33+
costs:
34+
unit: 1_000_000
35+
input: 10.00
36+
output: 30.00
37+
endpoints:
38+
- chat
39+
40+
gpt-4o:
41+
aliases:
42+
- gpt-4-o
43+
- gpt4o
44+
- gpt-4o-2024-05-13
45+
context_length: 128000
46+
costs:
47+
unit: 1_000_000
48+
input: 5.00
49+
output: 15.00
50+
endpoints:
51+
- chat
52+
2753
gpt-4:
2854
aliases:
2955
- gpt-4-0613

async_openai/types/resources.py

Lines changed: 68 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@
22
import json
33
import aiohttpx
44
import datetime
5+
import tempfile
6+
import pathlib
57
from pydantic import ConfigDict
68
from pydantic.types import ByteSize
79
from lazyops.types import BaseModel, validator, lazyproperty
810
from lazyops.types.models import get_pyd_field_names, pyd_parse_obj, get_pyd_dict, _BaseModel
9-
from lazyops.utils import ObjectDecoder
11+
from lazyops.utils import ObjectDecoder, ObjectEncoder
1012
from async_openai.utils.logs import logger
1113
from async_openai.utils.helpers import aparse_stream, parse_stream
1214

@@ -156,6 +158,29 @@ def create_resource(
156158
resource_obj = resource.parse_obj(resource_kwargs)
157159
return resource_obj, return_kwargs
158160

161+
162+
@staticmethod
163+
def create_batch_resource(
164+
resource: Type['BaseResource'],
165+
batch: List[Union[Dict[str, Any], Any]],
166+
**kwargs
167+
) -> Tuple[List['BaseResource'], Dict]:
168+
"""
169+
Extracts the resource from the kwargs and returns the resource
170+
and the remaining kwargs
171+
"""
172+
resource_fields = get_pyd_field_names(resource)
173+
resource_kwargs = {k: v for k, v in kwargs.items() if k in resource_fields}
174+
return_kwargs = {k: v for k, v in kwargs.items() if k not in resource_fields}
175+
resource_objs = []
176+
for item in batch:
177+
if isinstance(item, dict):
178+
item.update(resource_kwargs)
179+
resource_objs.append(resource.parse_obj(item))
180+
else:
181+
resource_objs.append(item)
182+
return resource_objs, return_kwargs
183+
159184
@classmethod
160185
def create_many(cls, data: List[Dict]) -> List['BaseResource']:
161186
"""
@@ -267,7 +292,7 @@ class FileResource(BaseResource):
267292
file_id: Optional[str]
268293
filename: Optional[str] = None
269294
purpose: FilePurpose = FilePurpose.fine_tune
270-
model: Optional[str]
295+
model: Optional[str] = None
271296

272297
@validator("purpose")
273298
def validate_purpose(cls, value):
@@ -299,4 +324,44 @@ async def async_get_params(self, **kwargs) -> List:
299324
files.append(
300325
("file", (self.filename or file.name, (await file.async_read_bytes() if _has_fileio else file.read_bytes()), "application/octet-stream"))
301326
)
302-
return files
327+
return files
328+
329+
@classmethod
330+
def create_from_batch(
331+
cls,
332+
batch: List[Union[Dict[str, Any], str]],
333+
output_path: Optional[str] = None,
334+
file_id: Optional[str] = None,
335+
filename: Optional[str] = None,
336+
purpose: Optional[FilePurpose] = None,
337+
**kwargs,
338+
) -> Tuple['FileObject', Dict[str, Any]]:
339+
"""
340+
Creates a file object from a batch in jsonl format
341+
"""
342+
for n, b in enumerate(batch):
343+
if isinstance(b, dict):
344+
batch[n] = json.dumps(b, cls = ObjectEncoder)
345+
if output_path:
346+
output = pathlib.Path(output_path)
347+
else:
348+
tmp = tempfile.NamedTemporaryFile(delete = False)
349+
tmp.close()
350+
output = pathlib.Path(tmp.name)
351+
352+
with output.open('w') as f:
353+
for b in batch:
354+
f.write(f'{b}\n')
355+
resource_fields = get_pyd_field_names(cls)
356+
resource_kwargs = {k: v for k, v in kwargs.items() if k in resource_fields}
357+
return_kwargs = {k: v for k, v in kwargs.items() if k not in resource_fields}
358+
return cls(
359+
file = output,
360+
purpose = purpose,
361+
filename = filename,
362+
file_id = file_id,
363+
**resource_kwargs
364+
), return_kwargs
365+
366+
367+

0 commit comments

Comments
 (0)