basic.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import httpx
  2. class BasicService:
  3. def __init__(self, base_url: str):
  4. self.base_url = base_url
  5. def _check_response(self, response: httpx.Response):
  6. """检查响应并处理错误"""
  7. if response.status_code not in [200, 201]:
  8. raise Exception(f"Failed to fetch data from API: {response.text}")
  9. response_data = response.json()
  10. status_code = response_data.get("status_code", 0)
  11. if status_code != 200:
  12. raise Exception(f"Failed to fetch data from API: {response.text}")
  13. return response_data.get("data", {})
  14. async def download_from_url(self, url: str, params: dict):
  15. async with httpx.AsyncClient() as client:
  16. response = await client.get(url, params=params, stream=True)
  17. if response.status_code == 200:
  18. content_disposition = response.headers.get('Content-Disposition')
  19. filename = content_disposition.split('filename=')[-1].strip(
  20. '"') if content_disposition else 'unknown_filename'
  21. return response.content, filename, response.headers.get('Content-Type')
  22. else:
  23. return None, None, None
  24. async def excel_talk_image_download(self, file_id: str):
  25. url = f"{self.base_url}/exceltalk/download/image"
  26. return await self.download_from_url(url, params={'images_name': file_id})
  27. async def excel_talk_excel_download(self, file_id: str):
  28. url = f"{self.base_url}/exceltalk/download/excel"
  29. return await self.download_from_url(url, params={'excel_name': file_id})
  30. async def excel_talk_upload(self, chat_id: str, filename: str, file_content: bytes):
  31. url = f"{self.base_url}/exceltalk/upload/files"
  32. params = {'chat_id': chat_id, 'is_col': '0'}
  33. # 创建 FormData 对象
  34. files = [('files', (filename, file_content, 'application/octet-stream'))]
  35. async with httpx.AsyncClient() as client:
  36. response = await client.post(
  37. url,
  38. files=files,
  39. params=params
  40. )
  41. return await self._check_response(response)
  42. async def excel_talk(self, question: str, chat_id: str):
  43. url = f"{self.base_url}/exceltalk/talk"
  44. params = {'chat_id': chat_id}
  45. data = {"query": question}
  46. headers = {'Content-Type': 'application/json'}
  47. async with httpx.AsyncClient(timeout=300.0) as client:
  48. async with client.stream("POST", url, params=params, json=data, headers=headers) as response:
  49. if response.status_code == 200:
  50. try:
  51. async for answer in response.aiter_text():
  52. print(f"response of ragflow chat: {answer}")
  53. yield answer
  54. except GeneratorExit as e:
  55. print(e)
  56. return
  57. else:
  58. yield f"Error: {response.status_code}"