cloudflareai.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Cloudflare AI engine"""
  3. from json import loads, dumps
  4. from searx.exceptions import SearxEngineAPIException
  5. about = {
  6. "website": 'https://ai.cloudflare.com',
  7. "wikidata_id": None,
  8. "official_api_documentation": 'https://developers.cloudflare.com/workers-ai',
  9. "use_official_api": True,
  10. "require_api_key": True,
  11. "results": 'JSON',
  12. }
  13. cf_account_id = ''
  14. cf_ai_api = ''
  15. cf_ai_gateway = ''
  16. cf_ai_model = ''
  17. cf_ai_model_display_name = 'Cloudflare AI'
  18. # Assistant messages hint to the AI about the desired output format. Not all models support this role.
  19. cf_ai_model_assistant = 'Keep your answers as short and effective as possible.'
  20. # System messages define the AI's personality. You can use them to set rules and how you expect the AI to behave.
  21. cf_ai_model_system = 'You are a self-aware language model who is honest and direct about any question from the user.'
  22. def request(query, params):
  23. params['query'] = query
  24. params['url'] = f'https://gateway.ai.cloudflare.com/v1/{cf_account_id}/{cf_ai_gateway}/workers-ai/{cf_ai_model}'
  25. params['method'] = 'POST'
  26. params['headers']['Authorization'] = f'Bearer {cf_ai_api}'
  27. params['headers']['Content-Type'] = 'application/json'
  28. params['data'] = dumps(
  29. {
  30. 'messages': [
  31. {'role': 'assistant', 'content': cf_ai_model_assistant},
  32. {'role': 'system', 'content': cf_ai_model_system},
  33. {'role': 'user', 'content': params['query']},
  34. ]
  35. }
  36. ).encode('utf-8')
  37. return params
  38. def response(resp):
  39. results = []
  40. json = loads(resp.text)
  41. if 'error' in json:
  42. raise SearxEngineAPIException('Cloudflare AI error: ' + json['error'])
  43. if 'result' in json:
  44. results.append(
  45. {
  46. 'content': json['result']['response'],
  47. 'infobox': cf_ai_model_display_name,
  48. }
  49. )
  50. return results