chat_base.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import httpx
  2. from pycparser.ply.yacc import token
  3. class ChatBase:
  4. @staticmethod
  5. async def http_stream(url, data, headers, timeout=300):
  6. async with httpx.AsyncClient(timeout=timeout) as client:
  7. async with client.stream("POST", url, json=data, headers=headers) as response:
  8. if response.status_code == 200:
  9. try:
  10. async for answer in response.aiter_text():
  11. yield answer
  12. except GeneratorExit as e:
  13. print(e)
  14. return
  15. else:
  16. yield f"Error: {response.status_code}"
  17. @staticmethod
  18. async def http_post(url, data, headers, timeout=300):
  19. async with httpx.AsyncClient(timeout=timeout) as client:
  20. response = await client.post(url, json=data, headers=headers)
  21. return response
  22. @staticmethod
  23. async def http_get(url, params, headers, timeout=300):
  24. async with httpx.AsyncClient(timeout=timeout) as client:
  25. response = await client.get(url, params=params, headers=headers)
  26. return response
  27. @staticmethod
  28. async def get_headers(token):
  29. return {
  30. 'Content-Type': 'application/json',
  31. 'Authorization': f'Bearer {token}'
  32. }