安全地执行异步代码,兼容已有事件循环(如 httpx/openai 遗留的)
(self, coro)
| 165 | return json.dumps({"error": "无返回结果"}) |
| 166 | |
| 167 | def _run_async(self, coro): |
| 168 | """安全地执行异步代码,兼容已有事件循环(如 httpx/openai 遗留的)""" |
| 169 | try: |
| 170 | loop = asyncio.get_running_loop() |
| 171 | except RuntimeError: |
| 172 | loop = None |
| 173 | |
| 174 | if loop and loop.is_running(): |
| 175 | with concurrent.futures.ThreadPoolExecutor() as pool: |
| 176 | return pool.submit(asyncio.run, coro).result() |
| 177 | else: |
| 178 | return asyncio.run(coro) |
| 179 | |
| 180 | def query(self, question: str, max_retries: int = 3) -> Dict[str, Any]: |
| 181 | """执行查询,失败时自动纠错并重试(Reflection 循环) |