-
Notifications
You must be signed in to change notification settings - Fork 103
/
Copy pathfix_openai.py
208 lines (189 loc) · 6.46 KB
/
fix_openai.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
# Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""OpenAI Wrappers for Orchestration."""
import logging
from typing import Any
from tenacity import (
AsyncRetrying,
RetryError,
Retrying,
retry_if_exception_type,
stop_after_attempt,
wait_exponential_jitter,
)
from graphrag.query.llm.base import BaseLLMCallback
from graphrag.query.llm.oai.base import OpenAILLMImpl
from graphrag.query.llm.oai.typing import (
OPENAI_RETRY_ERROR_TYPES,
OpenaiApiType,
)
log = logging.getLogger(__name__)
class OpenAI(OpenAILLMImpl):
"""Wrapper for OpenAI Completion models."""
def __init__(
self,
api_key: str,
model: str,
deployment_name: str | None = None,
api_base: str | None = None,
api_version: str | None = None,
api_type: OpenaiApiType = OpenaiApiType.OpenAI,
organization: str | None = None,
max_retries: int = 10,
retry_error_types: tuple[type[BaseException]] = OPENAI_RETRY_ERROR_TYPES, # type: ignore
):
self.api_key = api_key
self.model = model
self.deployment_name = deployment_name
self.api_base = api_base
self.api_version = api_version
self.api_type = api_type
self.organization = organization
self.max_retries = max_retries
self.retry_error_types = retry_error_types
def generate(
self,
messages: str | list[str],
streaming: bool = True,
callbacks: list[BaseLLMCallback] | None = None,
**kwargs: Any,
) -> str:
"""Generate text"""
try:
retryer = Retrying(
stop=stop_after_attempt(self.max_retries),
wait=wait_exponential_jitter(max=10),
reraise=True,
retry=retry_if_exception_type(self.retry_error_types),
)
for attempt in retryer:
with attempt:
return self._generate(
messages=messages,
streaming=streaming,
callbacks=callbacks,
**kwargs,
)
except RetryError:
log.exception("RetryError at generate(): %s")
return ""
else:
# TODO: why not just throw in this case?
return ""
async def agenerate(
self,
messages: str | list[str],
streaming: bool = True,
callbacks: list[BaseLLMCallback] | None = None,
**kwargs: Any,
) -> str:
"""Generate Text Asynchronously."""
try:
retryer = AsyncRetrying(
stop=stop_after_attempt(self.max_retries),
wait=wait_exponential_jitter(max=10),
reraise=True,
retry=retry_if_exception_type(self.retry_error_types),
)
async for attempt in retryer:
with attempt:
return await self._agenerate(
messages=messages,
streaming=streaming,
callbacks=callbacks,
**kwargs,
)
except RetryError:
log.exception("Error at agenerate()")
return ""
else:
# TODO: why not just throw in this case?
return ""
def _generate(
self,
messages: str | list[str],
streaming: bool = True,
callbacks: list[BaseLLMCallback] | None = None,
**kwargs: Any,
) -> str:
tools = [
{
"type": "web_search",
"web_search": {
"enable": False,
}
}
]
response = self.sync_client.chat.completions.create( # type: ignore
model=self.model,
messages=messages, # type: ignore
stream=streaming,
tools=tools,
**kwargs,
) # type: ignore
if streaming:
full_response = ""
while True:
try:
chunk = response.__next__() # type: ignore
if not chunk or not chunk.choices:
continue
delta = (
chunk.choices[0].delta.content
if chunk.choices[0].delta and chunk.choices[0].delta.content
else ""
) # type: ignore
full_response += delta
if callbacks:
for callback in callbacks:
callback.on_llm_new_token(delta)
if chunk.choices[0].finish_reason == "stop": # type: ignore
break
except StopIteration:
break
return full_response
return response.choices[0].message.content or "" # type: ignore
async def _agenerate(
self,
messages: str | list[str],
streaming: bool = True,
callbacks: list[BaseLLMCallback] | None = None,
**kwargs: Any,
) -> str:
tools = [
{
"type": "web_search",
"web_search": {
"enable": False,
}
}
]
response = await self.async_client.chat.completions.create( # type: ignore
model=self.model,
messages=messages, # type: ignore
stream=streaming,
tools=tools,
**kwargs,
)
if streaming:
full_response = ""
while True:
try:
chunk = await response.__anext__() # type: ignore
if not chunk or not chunk.choices:
continue
delta = (
chunk.choices[0].delta.content
if chunk.choices[0].delta and chunk.choices[0].delta.content
else ""
) # type: ignore
full_response += delta
if callbacks:
for callback in callbacks:
callback.on_llm_new_token(delta)
if chunk.choices[0].finish_reason == "stop": # type: ignore
break
except StopIteration:
break
return full_response
return response.choices[0].message.content or "" # type: ignore