basic.py 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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, params=None):
  15. async with httpx.AsyncClient() as client:
  16. async with client.stream('GET', url, params=params) as response:
  17. if response.status_code == 200:
  18. # 获取文件名
  19. content_disposition = response.headers.get('Content-Disposition')
  20. if content_disposition:
  21. filename = content_disposition.split('filename=')[1].strip('"')
  22. else:
  23. filename = 'unknown_filename'
  24. # 获取内容类型
  25. content_type = response.headers.get('Content-Type')
  26. # 读取文件内容
  27. content = await response.aread()
  28. return content, filename, content_type
  29. else:
  30. raise Exception(f"Failed to download: {response.status_code}")
  31. async def excel_talk_image_download(self, file_id: str):
  32. url = f"{self.base_url}/exceltalk/download/image"
  33. return await self.download_from_url(url, params={'images_name': file_id})
  34. async def excel_talk_excel_download(self, file_id: str):
  35. url = f"{self.base_url}/exceltalk/download/excel"
  36. return await self.download_from_url(url, params={'excel_name': file_id})
  37. async def excel_talk_upload(self, chat_id: str, filename: str, file_content: bytes):
  38. url = f"{self.base_url}/exceltalk/upload/files"
  39. params = {'chat_id': chat_id, 'is_col': '0'}
  40. # 创建 FormData 对象
  41. files = [('files', (filename, file_content, 'application/octet-stream'))]
  42. async with httpx.AsyncClient() as client:
  43. response = await client.post(
  44. url,
  45. files=files,
  46. params=params
  47. )
  48. return await self._check_response(response)
  49. async def excel_talk(self, question: str, chat_id: str):
  50. url = f"{self.base_url}/exceltalk/talk"
  51. params = {'chat_id': chat_id}
  52. data = {"query": question}
  53. headers = {'Content-Type': 'application/json'}
  54. async with httpx.AsyncClient(timeout=300.0) as client:
  55. async with client.stream("POST", url, params=params, json=data, headers=headers) as response:
  56. if response.status_code == 200:
  57. try:
  58. async for answer in response.aiter_text():
  59. print(f"response of ragflow chat: {answer}")
  60. yield answer
  61. except GeneratorExit as e:
  62. print(e)
  63. return
  64. else:
  65. yield f"Error: {response.status_code}"