1- import click
21import json
3- from http .server import HTTPServer , BaseHTTPRequestHandler
4- from urllib .parse import urlparse
5- from urllib .request import Request , urlopen
6- from urllib .error import URLError , HTTPError
72import re
3+ from http .server import BaseHTTPRequestHandler
4+ from http .server import HTTPServer
5+ from urllib .error import HTTPError
6+ from urllib .error import URLError
7+ from urllib .parse import urlparse
8+ from urllib .request import Request
9+ from urllib .request import urlopen
10+
11+ import click
812
913
1014@click .group (name = "knowledge" )
@@ -13,17 +17,19 @@ def cli():
1317
1418
1519@cli .command ()
16- @click .option (' --port' , default = 4000 , help = ' Port to run the server on' )
20+ @click .option (" --port" , default = 4000 , help = " Port to run the server on" )
1721@click .pass_context
1822def serve (ctx , port ):
1923 """Serve knowledge bases via HTTP server."""
2024 # Get configuration from parent context
21- token = ctx .parent .obj .get (' token' )
22- instance_name = ctx .parent .obj .get (' instance_name' )
23- backend_url = ctx .parent .obj .get (' backend_url' )
25+ token = ctx .parent .obj .get (" token" )
26+ instance_name = ctx .parent .obj .get (" instance_name" )
27+ backend_url = ctx .parent .obj .get (" backend_url" )
2428
2529 if not token or not instance_name :
26- click .echo ("Error: API token and instance name are required. Use --token and --instance-name options or set them in config." , err = True )
30+ click .echo (
31+ "Error: API token and instance name are required. Use --token and --instance-name options or set them in config." , err = True
32+ )
2733 ctx .exit (1 )
2834
2935 class KnowledgeBaseHandler (BaseHTTPRequestHandler ):
@@ -32,12 +38,12 @@ def do_GET(self):
3238 path = urlparse (self .path ).path
3339
3440 # Match /knowledge_bases/{uuid} pattern
35- match = re .match (r' ^/knowledge_bases/([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})$' , path )
41+ match = re .match (r" ^/knowledge_bases/([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})$" , path )
3642
3743 if match :
3844 public_id = match .group (1 )
3945 self .handle_knowledge_base (public_id )
40- elif path == ' /health' :
46+ elif path == " /health" :
4147 self .handle_health ()
4248 else :
4349 self .send_error (404 , "Not Found" )
@@ -46,46 +52,42 @@ def handle_knowledge_base(self, public_id):
4652 """Fetch and return knowledge base data."""
4753 url = f"{ backend_url } /knowledge_bases/public/{ public_id } "
4854
49- headers = {
50- 'Authorization' : f'Bearer { token } ' ,
51- 'X-Tenant' : instance_name ,
52- 'Content-Type' : 'application/json'
53- }
55+ headers = {"Authorization" : f"Bearer { token } " , "X-Tenant" : instance_name , "Content-Type" : "application/json" }
5456
5557 req = Request (url , headers = headers )
5658
5759 try :
5860 with urlopen (req ) as response :
5961 data = response .read ()
6062 self .send_response (200 )
61- self .send_header (' Content-Type' , ' application/json' )
63+ self .send_header (" Content-Type" , " application/json" )
6264 self .end_headers ()
6365 self .wfile .write (data )
6466 except HTTPError as e :
65- error_data = e .read ().decode (' utf-8' ) if e .read () else '{"error": "HTTP Error"}'
67+ error_data = e .read ().decode (" utf-8" ) if e .read () else '{"error": "HTTP Error"}'
6668 self .send_response (e .code )
67- self .send_header (' Content-Type' , ' application/json' )
69+ self .send_header (" Content-Type" , " application/json" )
6870 self .end_headers ()
69- self .wfile .write (error_data .encode (' utf-8' ))
71+ self .wfile .write (error_data .encode (" utf-8" ))
7072 except URLError as e :
7173 self .send_response (500 )
72- self .send_header (' Content-Type' , ' application/json' )
74+ self .send_header (" Content-Type" , " application/json" )
7375 self .end_headers ()
74- error_msg = json .dumps ({' error' : str (e )})
75- self .wfile .write (error_msg .encode (' utf-8' ))
76+ error_msg = json .dumps ({" error" : str (e )})
77+ self .wfile .write (error_msg .encode (" utf-8" ))
7678
7779 def handle_health (self ):
7880 """Handle health check endpoint."""
7981 self .send_response (200 )
80- self .send_header (' Content-Type' , ' application/json' )
82+ self .send_header (" Content-Type" , " application/json" )
8183 self .end_headers ()
82- self .wfile .write (json .dumps ({' status' : 'ok' }).encode (' utf-8' ))
84+ self .wfile .write (json .dumps ({" status" : "ok" }).encode (" utf-8" ))
8385
8486 def log_message (self , format , * args ):
8587 """Override to use click.echo for logging."""
8688 click .echo (f"{ self .address_string ()} - { format % args } " )
8789
88- server_address = ('' , port )
90+ server_address = ("" , port )
8991 httpd = HTTPServer (server_address , KnowledgeBaseHandler )
9092
9193 click .echo (f"Starting knowledge base server on port { port } ..." )
@@ -98,4 +100,3 @@ def log_message(self, format, *args):
98100 except KeyboardInterrupt :
99101 click .echo ("\n Shutting down server..." )
100102 httpd .shutdown ()
101-
0 commit comments