basic.py 3.1 KB

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