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