Niansuh commited on
Commit
64fa2c3
·
verified ·
1 Parent(s): 4eb4812

Update api/utils.py

Browse files
Files changed (1) hide show
  1. api/utils.py +98 -61
api/utils.py CHANGED
@@ -68,8 +68,87 @@ class GizAI:
68
  def is_image_model(cls, model: str) -> bool:
69
  return model in cls.image_models
70
 
71
- async def process_gizai_response(request: ChatRequest, model: str) -> Union[AsyncGenerator[str, None], ImageResponseModel, ChatCompletionResponse]:
72
  async with aiohttp.ClientSession() as session:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  if GizAI.is_image_model(model):
74
  # Image generation logic
75
  prompt = request.messages[-1].content if isinstance(request.messages[-1].content, str) else request.messages[-1].content[0].get("text", "")
@@ -88,22 +167,7 @@ async def process_gizai_response(request: ChatRequest, model: str) -> Union[Asyn
88
  try:
89
  async with session.post(
90
  GIZAI_API_ENDPOINT,
91
- headers={
92
- 'Accept': 'application/json, text/plain, */*',
93
- 'Accept-Language': 'en-US,en;q=0.9',
94
- 'Cache-Control': 'no-cache',
95
- 'Connection': 'keep-alive',
96
- 'Content-Type': 'application/json',
97
- 'Origin': 'https://app.giz.ai',
98
- 'Pragma': 'no-cache',
99
- 'Sec-Fetch-Dest': 'empty',
100
- 'Sec-Fetch-Mode': 'cors',
101
- 'Sec-Fetch-Site': 'same-origin',
102
- 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
103
- 'sec-ch-ua': '"Not?A_Brand";v="99", "Chromium";v="130"',
104
- 'sec-ch-ua-mobile': '?0',
105
- 'sec-ch-ua-platform': '"Linux"'
106
- },
107
  json=data
108
  ) as response:
109
  response.raise_for_status()
@@ -133,57 +197,30 @@ async def process_gizai_response(request: ChatRequest, model: str) -> Union[Asyn
133
  "messages": messages_formatted,
134
  "mode": "plan"
135
  },
136
- "noStream": not request.stream
137
  }
138
  try:
139
  async with session.post(
140
  GIZAI_API_ENDPOINT,
141
- headers={
142
- 'Accept': 'application/json, text/plain, */*',
143
- 'Accept-Language': 'en-US,en;q=0.9',
144
- 'Cache-Control': 'no-cache',
145
- 'Connection': 'keep-alive',
146
- 'Content-Type': 'application/json',
147
- 'Origin': 'https://app.giz.ai',
148
- 'Pragma': 'no-cache',
149
- 'Sec-Fetch-Dest': 'empty',
150
- 'Sec-Fetch-Mode': 'cors',
151
- 'Sec-Fetch-Site': 'same-origin',
152
- 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
153
- 'sec-ch-ua': '"Not?A_Brand";v="99", "Chromium";v="130"',
154
- 'sec-ch-ua-mobile': '?0',
155
- 'sec-ch-ua-platform': '"Linux"'
156
- },
157
  json=data
158
  ) as response:
159
  response.raise_for_status()
160
- if request.stream:
161
- # Handle streaming response
162
- async def stream_response():
163
- async for line in response.content:
164
- if line:
165
- decoded_line = line.decode('utf-8').strip()
166
- if decoded_line.startswith("data:"):
167
- content = decoded_line.replace("data: ", "")
168
- yield f"data: {content}\n\n"
169
- return stream_response()
170
- else:
171
- # Handle non-streaming response
172
- result = await response.json()
173
- return ChatCompletionResponse(
174
- id=f"chatcmpl-{uuid.uuid4()}",
175
- object="chat.completion",
176
- created=int(datetime.now().timestamp()),
177
- model=model,
178
- choices=[
179
- {
180
- "index": 0,
181
- "message": {"role": "assistant", "content": result.get('output', '')},
182
- "finish_reason": "stop",
183
- }
184
- ],
185
- usage=None,
186
- )
187
  except aiohttp.ClientResponseError as e:
188
  logger.error(f"HTTP error occurred: {e.status} - {e.message}")
189
  raise HTTPException(status_code=e.status, detail=str(e))
 
68
  def is_image_model(cls, model: str) -> bool:
69
  return model in cls.image_models
70
 
71
+ async def process_gizai_stream_response(request: ChatRequest, model: str) -> AsyncGenerator[str, None]:
72
  async with aiohttp.ClientSession() as session:
73
+ # Set up headers
74
+ headers = {
75
+ 'Accept': 'application/json, text/plain, */*',
76
+ 'Accept-Language': 'en-US,en;q=0.9',
77
+ 'Cache-Control': 'no-cache',
78
+ 'Connection': 'keep-alive',
79
+ 'Content-Type': 'application/json',
80
+ 'Origin': 'https://app.giz.ai',
81
+ 'Pragma': 'no-cache',
82
+ 'Sec-Fetch-Dest': 'empty',
83
+ 'Sec-Fetch-Mode': 'cors',
84
+ 'Sec-Fetch-Site': 'same-origin',
85
+ 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
86
+ 'sec-ch-ua': '"Not?A_Brand";v="99", "Chromium";v="130"',
87
+ 'sec-ch-ua-mobile': '?0',
88
+ 'sec-ch-ua-platform': '"Linux"'
89
+ }
90
+
91
+ if GizAI.is_image_model(model):
92
+ # Image generation logic (streaming might not make sense here)
93
+ raise HTTPException(status_code=400, detail="Image generation does not support streaming.")
94
+ else:
95
+ # Chat completion logic
96
+ messages_formatted = [
97
+ {
98
+ "type": "human",
99
+ "content": msg.content if isinstance(msg.content, str) else msg.content[0].get("text", "")
100
+ } for msg in request.messages
101
+ ]
102
+ data = {
103
+ "model": model,
104
+ "input": {
105
+ "messages": messages_formatted,
106
+ "mode": "plan"
107
+ },
108
+ "noStream": False # Enable streaming
109
+ }
110
+ try:
111
+ async with session.post(
112
+ GIZAI_API_ENDPOINT,
113
+ headers=headers,
114
+ json=data
115
+ ) as response:
116
+ response.raise_for_status()
117
+ async for line in response.content:
118
+ if line:
119
+ decoded_line = line.decode('utf-8').strip()
120
+ if decoded_line.startswith("data:"):
121
+ content = decoded_line.replace("data: ", "")
122
+ yield f"data: {content}\n\n"
123
+ # Indicate the end of the stream
124
+ yield "data: [DONE]\n\n"
125
+ except aiohttp.ClientResponseError as e:
126
+ logger.error(f"HTTP error occurred: {e.status} - {e.message}")
127
+ raise HTTPException(status_code=e.status, detail=str(e))
128
+ except Exception as e:
129
+ logger.error(f"Unexpected error: {str(e)}")
130
+ raise HTTPException(status_code=500, detail=str(e))
131
+
132
+ async def process_gizai_non_stream_response(request: ChatRequest, model: str) -> Union[ImageResponseModel, ChatCompletionResponse]:
133
+ async with aiohttp.ClientSession() as session:
134
+ # Set up headers
135
+ headers = {
136
+ 'Accept': 'application/json, text/plain, */*',
137
+ 'Accept-Language': 'en-US,en;q=0.9',
138
+ 'Cache-Control': 'no-cache',
139
+ 'Connection': 'keep-alive',
140
+ 'Content-Type': 'application/json',
141
+ 'Origin': 'https://app.giz.ai',
142
+ 'Pragma': 'no-cache',
143
+ 'Sec-Fetch-Dest': 'empty',
144
+ 'Sec-Fetch-Mode': 'cors',
145
+ 'Sec-Fetch-Site': 'same-origin',
146
+ 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
147
+ 'sec-ch-ua': '"Not?A_Brand";v="99", "Chromium";v="130"',
148
+ 'sec-ch-ua-mobile': '?0',
149
+ 'sec-ch-ua-platform': '"Linux"'
150
+ }
151
+
152
  if GizAI.is_image_model(model):
153
  # Image generation logic
154
  prompt = request.messages[-1].content if isinstance(request.messages[-1].content, str) else request.messages[-1].content[0].get("text", "")
 
167
  try:
168
  async with session.post(
169
  GIZAI_API_ENDPOINT,
170
+ headers=headers,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  json=data
172
  ) as response:
173
  response.raise_for_status()
 
197
  "messages": messages_formatted,
198
  "mode": "plan"
199
  },
200
+ "noStream": True # Disable streaming
201
  }
202
  try:
203
  async with session.post(
204
  GIZAI_API_ENDPOINT,
205
+ headers=headers,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  json=data
207
  ) as response:
208
  response.raise_for_status()
209
+ result = await response.json()
210
+ return ChatCompletionResponse(
211
+ id=f"chatcmpl-{uuid.uuid4()}",
212
+ object="chat.completion",
213
+ created=int(datetime.now().timestamp()),
214
+ model=model,
215
+ choices=[
216
+ {
217
+ "index": 0,
218
+ "message": {"role": "assistant", "content": result.get('output', '')},
219
+ "finish_reason": "stop",
220
+ }
221
+ ],
222
+ usage=None,
223
+ )
 
 
 
 
 
 
 
 
 
 
 
 
224
  except aiohttp.ClientResponseError as e:
225
  logger.error(f"HTTP error occurred: {e.status} - {e.message}")
226
  raise HTTPException(status_code=e.status, detail=str(e))