-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy pathopenai_client.py
More file actions
135 lines (111 loc) · 4.9 KB
/
openai_client.py
File metadata and controls
135 lines (111 loc) · 4.9 KB
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
"""
Copyright 2024, Zep Software, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import typing
from openai import AsyncOpenAI
from openai.types.chat import ChatCompletionMessageParam
from pydantic import BaseModel
from .config import DEFAULT_MAX_TOKENS, LLMConfig
from .openai_base_client import DEFAULT_REASONING, DEFAULT_VERBOSITY, BaseOpenAIClient
class OpenAIClient(BaseOpenAIClient):
"""
OpenAIClient is a client class for interacting with OpenAI's language models.
This class extends the BaseOpenAIClient and provides OpenAI-specific implementation
for creating completions.
Attributes:
client (AsyncOpenAI): The OpenAI client used to interact with the API.
"""
def __init__(
self,
config: LLMConfig | None = None,
cache: bool = False,
client: typing.Any = None,
max_tokens: int = DEFAULT_MAX_TOKENS,
reasoning: str = DEFAULT_REASONING,
verbosity: str = DEFAULT_VERBOSITY,
):
"""
Initialize the OpenAIClient with the provided configuration, cache setting, and client.
Args:
config (LLMConfig | None): The configuration for the LLM client, including API key, model, base URL, temperature, and max tokens.
cache (bool): Whether to use caching for responses. Defaults to False.
client (Any | None): An optional async client instance to use. If not provided, a new AsyncOpenAI client is created.
"""
super().__init__(config, cache, max_tokens, reasoning, verbosity)
if config is None:
config = LLMConfig()
if client is None:
self.client = AsyncOpenAI(api_key=config.api_key, base_url=config.base_url)
else:
self.client = client
async def _create_structured_completion(
self,
model: str,
messages: list[ChatCompletionMessageParam],
temperature: float | None,
max_tokens: int,
response_model: type[BaseModel],
reasoning: str | None = None,
verbosity: str | None = None,
):
"""Create a structured completion using OpenAI's beta parse API."""
# Reasoning models (gpt-5 family) don't support temperature
is_reasoning_model = (
model.startswith('gpt-5') or model.startswith('o1') or model.startswith('o3')
)
request_kwargs = {
'model': model,
'input': messages, # type: ignore
'max_output_tokens': max_tokens,
'text_format': response_model, # type: ignore
}
temperature_value = temperature if not is_reasoning_model else None
if temperature_value is not None:
request_kwargs['temperature'] = temperature_value
# Only include reasoning and verbosity parameters for reasoning models
# Map legacy reasoning effort values to current OpenAI API values
_REASONING_MAP = {'minimal': 'low', 'default': 'medium', 'maximum': 'high'}
if is_reasoning_model and reasoning is not None:
effort = _REASONING_MAP.get(reasoning, reasoning)
request_kwargs['reasoning'] = {'effort': effort} # type: ignore
if is_reasoning_model and verbosity is not None:
request_kwargs['text'] = {'verbosity': verbosity} # type: ignore
response = await self.client.responses.parse(**request_kwargs)
return response
async def _create_completion(
self,
model: str,
messages: list[ChatCompletionMessageParam],
temperature: float | None,
max_tokens: int,
response_model: type[BaseModel] | None = None,
reasoning: str | None = None,
verbosity: str | None = None,
):
"""Create a regular completion with JSON format."""
# Reasoning models (gpt-5 family) don't support temperature
is_reasoning_model = (
model.startswith('gpt-5') or model.startswith('o1') or model.startswith('o3')
)
# gpt-5 family requires max_completion_tokens instead of max_tokens
token_kwargs = (
{'max_completion_tokens': max_tokens}
if is_reasoning_model
else {'max_tokens': max_tokens}
)
return await self.client.chat.completions.create(
model=model,
messages=messages,
temperature=temperature if not is_reasoning_model else None,
response_format={'type': 'json_object'},
**token_kwargs,
)