1
+ from fastapi import HTTPException
2
+ from fastapi .encoders import jsonable_encoder
3
+ from fastapi .responses import JSONResponse
4
+
5
+ import openai
6
+ from openai .error import APIError , AuthenticationError , RateLimitError , InvalidRequestError , TimeoutError , APIConnectionError
7
+ from typing import Optional , List
8
+
9
+ from dependencies .database import get_db
10
+ from dependencies .auth import get_current_user
11
+ from schemas .openai import OpenAIRequest , OpenAIResponse , OpenAIChoice , OpenAIUsage , OpenAIModel
12
+
13
+ # Load environment variables
14
+ from .config import settings
15
+
16
+ OPENAI_API_KEY = settings .openai_api_key
17
+ openai .api_key = OPENAI_API_KEY
18
+
19
+ class OpenAIService :
20
+ """
21
+ Service class for interacting with the OpenAI API.
22
+ """
23
+
24
+ async def complete_text (self , text : str , model : str = "text-davinci-003" , temperature : float = 0.7 , max_tokens : int = 256 ) -> OpenAIResponse :
25
+ """
26
+ Completes a given text using OpenAI's text completion API.
27
+
28
+ Args:
29
+ text (str): The text to be completed.
30
+ model (str, optional): The OpenAI model to use. Defaults to "text-davinci-003".
31
+ temperature (float, optional): The temperature parameter for controlling the randomness of the generated text. Defaults to 0.7.
32
+ max_tokens (int, optional): The maximum number of tokens to generate. Defaults to 256.
33
+
34
+ Returns:
35
+ OpenAIResponse: The OpenAI API response containing the completed text.
36
+
37
+ Raises:
38
+ HTTPException: If an error occurs during the API call.
39
+ """
40
+
41
+ try :
42
+ response = openai .Completion .create (
43
+ engine = model ,
44
+ prompt = text ,
45
+ temperature = temperature ,
46
+ max_tokens = max_tokens ,
47
+ )
48
+ return OpenAIResponse (response = response .choices [0 ].text )
49
+
50
+ except AuthenticationError :
51
+ raise HTTPException (
52
+ status_code = 401 ,
53
+ detail = "Invalid OpenAI API key. Please check your API key." ,
54
+ )
55
+ except RateLimitError :
56
+ raise HTTPException (
57
+ status_code = 429 ,
58
+ detail = "OpenAI API rate limit exceeded. Please try again later." ,
59
+ )
60
+ except InvalidRequestError :
61
+ raise HTTPException (
62
+ status_code = 400 ,
63
+ detail = "Invalid request to OpenAI API. Please check your input parameters." ,
64
+ )
65
+ except TimeoutError :
66
+ raise HTTPException (
67
+ status_code = 504 ,
68
+ detail = "Request to OpenAI API timed out. Please try again later." ,
69
+ )
70
+ except APIConnectionError :
71
+ raise HTTPException (
72
+ status_code = 500 ,
73
+ detail = "Error connecting to OpenAI API. Please check your internet connection." ,
74
+ )
75
+ except APIError as e :
76
+ raise HTTPException (
77
+ status_code = 500 ,
78
+ detail = f"Error calling OpenAI API: { str (e )} " ,
79
+ )
80
+
81
+ async def translate_text (self , text : str , source_language : str , target_language : str ) -> OpenAIResponse :
82
+ """
83
+ Translates a given text using OpenAI's translation API.
84
+
85
+ Args:
86
+ text (str): The text to be translated.
87
+ source_language (str): The source language of the text.
88
+ target_language (str): The target language to translate to.
89
+
90
+ Returns:
91
+ OpenAIResponse: The OpenAI API response containing the translated text.
92
+
93
+ Raises:
94
+ HTTPException: If an error occurs during the API call.
95
+ """
96
+
97
+ try :
98
+ response = openai .Translation .create (
99
+ model = "gpt-3.5-turbo" ,
100
+ from_language = source_language ,
101
+ to_language = target_language ,
102
+ text = text ,
103
+ )
104
+ return OpenAIResponse (response = response .choices [0 ].text )
105
+
106
+ except AuthenticationError :
107
+ raise HTTPException (
108
+ status_code = 401 ,
109
+ detail = "Invalid OpenAI API key. Please check your API key." ,
110
+ )
111
+ except RateLimitError :
112
+ raise HTTPException (
113
+ status_code = 429 ,
114
+ detail = "OpenAI API rate limit exceeded. Please try again later." ,
115
+ )
116
+ except InvalidRequestError :
117
+ raise HTTPException (
118
+ status_code = 400 ,
119
+ detail = "Invalid request to OpenAI API. Please check your input parameters." ,
120
+ )
121
+ except TimeoutError :
122
+ raise HTTPException (
123
+ status_code = 504 ,
124
+ detail = "Request to OpenAI API timed out. Please try again later." ,
125
+ )
126
+ except APIConnectionError :
127
+ raise HTTPException (
128
+ status_code = 500 ,
129
+ detail = "Error connecting to OpenAI API. Please check your internet connection." ,
130
+ )
131
+ except APIError as e :
132
+ raise HTTPException (
133
+ status_code = 500 ,
134
+ detail = f"Error calling OpenAI API: { str (e )} " ,
135
+ )
136
+
137
+ async def summarize_text (self , text : str , model : str = "text-davinci-003" ) -> OpenAIResponse :
138
+ """
139
+ Summarizes a given text using OpenAI's summarization API.
140
+
141
+ Args:
142
+ text (str): The text to be summarized.
143
+ model (str, optional): The OpenAI model to use. Defaults to "text-davinci-003".
144
+
145
+ Returns:
146
+ OpenAIResponse: The OpenAI API response containing the summarized text.
147
+
148
+ Raises:
149
+ HTTPException: If an error occurs during the API call.
150
+ """
151
+
152
+ try :
153
+ response = openai .Completion .create (
154
+ engine = model ,
155
+ prompt = f"Summarize the following text:\n \n { text } " ,
156
+ temperature = 0.7 ,
157
+ max_tokens = 256 ,
158
+ )
159
+ return OpenAIResponse (response = response .choices [0 ].text )
160
+
161
+ except AuthenticationError :
162
+ raise HTTPException (
163
+ status_code = 401 ,
164
+ detail = "Invalid OpenAI API key. Please check your API key." ,
165
+ )
166
+ except RateLimitError :
167
+ raise HTTPException (
168
+ status_code = 429 ,
169
+ detail = "OpenAI API rate limit exceeded. Please try again later." ,
170
+ )
171
+ except InvalidRequestError :
172
+ raise HTTPException (
173
+ status_code = 400 ,
174
+ detail = "Invalid request to OpenAI API. Please check your input parameters." ,
175
+ )
176
+ except TimeoutError :
177
+ raise HTTPException (
178
+ status_code = 504 ,
179
+ detail = "Request to OpenAI API timed out. Please try again later." ,
180
+ )
181
+ except APIConnectionError :
182
+ raise HTTPException (
183
+ status_code = 500 ,
184
+ detail = "Error connecting to OpenAI API. Please check your internet connection." ,
185
+ )
186
+ except APIError as e :
187
+ raise HTTPException (
188
+ status_code = 500 ,
189
+ detail = f"Error calling OpenAI API: { str (e )} " ,
190
+ )
191
+
192
+ async def get_model (self , model_id : str ) -> OpenAIModel :
193
+ """
194
+ Retrieves information about a specific OpenAI model.
195
+
196
+ Args:
197
+ model_id (str): The ID of the OpenAI model to retrieve.
198
+
199
+ Returns:
200
+ OpenAIModel: The OpenAI model information.
201
+
202
+ Raises:
203
+ HTTPException: If an error occurs during the API call.
204
+ """
205
+ try :
206
+ response = openai .Model .retrieve (model_id )
207
+ return OpenAIModel (** response )
208
+ except AuthenticationError :
209
+ raise HTTPException (
210
+ status_code = 401 ,
211
+ detail = "Invalid OpenAI API key. Please check your API key." ,
212
+ )
213
+ except RateLimitError :
214
+ raise HTTPException (
215
+ status_code = 429 ,
216
+ detail = "OpenAI API rate limit exceeded. Please try again later." ,
217
+ )
218
+ except InvalidRequestError :
219
+ raise HTTPException (
220
+ status_code = 400 ,
221
+ detail = "Invalid request to OpenAI API. Please check your input parameters." ,
222
+ )
223
+ except TimeoutError :
224
+ raise HTTPException (
225
+ status_code = 504 ,
226
+ detail = "Request to OpenAI API timed out. Please try again later." ,
227
+ )
228
+ except APIConnectionError :
229
+ raise HTTPException (
230
+ status_code = 500 ,
231
+ detail = "Error connecting to OpenAI API. Please check your internet connection." ,
232
+ )
233
+ except APIError as e :
234
+ raise HTTPException (
235
+ status_code = 500 ,
236
+ detail = f"Error calling OpenAI API: { str (e )} " ,
237
+ )
238
+
239
+
240
+ openai_service = OpenAIService ()
0 commit comments