@@ -194,23 +194,46 @@ def generate_text(self, prompt: str, system_prompt: str, model: str = None, chai
194194 except Exception as e :
195195 logger .error (f"get on-chain system_prompt fail { e } " )
196196
197+ stream = self .config ["stream" ]
198+ logger .info (f"call completions api stream { stream } " )
197199 completion = client .chat .completions .create (
198200 model = model ,
199201 messages = [
200202 {"role" : "system" , "content" : system_prompt },
201203 {"role" : "user" , "content" : prompt },
202204 ],
203- extra_body = {"chain_id" : chain_id }
205+ extra_body = {"chain_id" : chain_id },
206+ stream = stream ,
204207 )
205-
206- if completion .choices is None :
207- raise EternalAIAPIError (f"Text generation failed: completion.choices is None" )
208- try :
209- if completion .onchain_data is not None :
210- logger .info (f"response onchain data: { json .dumps (completion .onchain_data , indent = 4 )} " )
211- except :
212- logger .info (f"response onchain data object: { completion .onchain_data } " , )
213- return completion .choices [0 ].message .content
208+ if not stream :
209+ if completion .choices is None :
210+ raise EternalAIAPIError (f"Text generation failed: completion.choices is None" )
211+ try :
212+ if completion .onchain_data is not None :
213+ logger .info (f"response onchain data: { json .dumps (completion .onchain_data , indent = 4 )} " )
214+ except :
215+ logger .info (f"response onchain data object: { completion .onchain_data } " , )
216+ logger .info (
217+ f"end call completions api with content:\n \n { completion .choices [0 ].message .content } \n \n \n \n " )
218+ return completion .choices [0 ].message .content
219+ else :
220+ content = ""
221+ # logger.info(f"completion {str(completion)}")
222+ for chunk in completion :
223+ if chunk .choices is not None :
224+ delta = chunk .choices [0 ].delta
225+ if delta is not None and delta .content is not None :
226+ content += delta .content
227+ # logger.info(f"content -> {delta.content}")
228+ else :
229+ try :
230+ if chunk .onchain_data is not None and chunk .onchain_data .infer_id is not None and chunk .onchain_data .infer_id != "" :
231+ logger .info (f"response onchain data: { json .dumps (chunk .onchain_data , indent = 4 )} " )
232+ except :
233+ logger .info (f"response onchain data object: { chunk .onchain_data } " , )
234+ break
235+ logger .info (f"end call completions api with content:\n \n { content } \n \n \n \n " )
236+ return content
214237
215238 except Exception as e :
216239 raise EternalAIAPIError (f"Text generation failed: { e } " )
0 commit comments