forked from stacklok/codegate
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
200 lines (179 loc) · 5.35 KB
/
cli.py
File metadata and controls
200 lines (179 loc) · 5.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
"""Command-line interface for codegate."""
import sys
from pathlib import Path
from typing import Dict, Optional
import click
import structlog
from codegate.codegate_logging import LogFormat, LogLevel, setup_logging
from codegate.config import Config, ConfigurationError
from codegate.db.connection import init_db_sync
from codegate.server import init_app
def validate_port(ctx: click.Context, param: click.Parameter, value: int) -> int:
"""Validate the port number is in valid range."""
if value is not None and not (1 <= value <= 65535):
raise click.BadParameter("Port must be between 1 and 65535")
return value
@click.group()
@click.version_option()
def cli() -> None:
"""Codegate - A configurable service gateway."""
pass
@cli.command()
@click.option(
"--prompts",
type=click.Path(exists=True, dir_okay=False, path_type=Path),
required=False,
help="Path to YAML prompts file (optional, shows default prompts if not provided)",
)
def show_prompts(prompts: Optional[Path]) -> None:
"""Display prompts from the specified file or default if no file specified."""
try:
cfg = Config.load(prompts_path=prompts)
click.echo("Loaded prompts:")
click.echo("-" * 40)
for name, content in cfg.prompts.prompts.items():
click.echo(f"\n{name}:")
click.echo(f"{content}")
click.echo("-" * 40)
except ConfigurationError as e:
click.echo(f"Configuration error: {e}", err=True)
sys.exit(1)
except Exception as e:
click.echo(f"Error: {e}", err=True)
sys.exit(1)
@cli.command()
@click.option(
"--port",
type=int,
default=None,
callback=validate_port,
help="Port to listen on (default: 8989)",
)
@click.option(
"--host",
type=str,
default=None,
help="Host to bind to (default: localhost)",
)
@click.option(
"--log-level",
type=click.Choice([level.value for level in LogLevel]),
default=None,
help="Set the log level (default: INFO)",
)
@click.option(
"--log-format",
type=click.Choice([fmt.value for fmt in LogFormat], case_sensitive=False),
default=None,
help="Set the log format (default: JSON)",
)
@click.option(
"--config",
type=click.Path(exists=True, dir_okay=False, path_type=Path),
default=None,
help="Path to YAML config file",
)
@click.option(
"--prompts",
type=click.Path(exists=True, dir_okay=False, path_type=Path),
default=None,
help="Path to YAML prompts file",
)
@click.option(
"--vllm-url",
type=str,
default=None,
help="vLLM provider URL (default: http://localhost:8000/v1)",
)
@click.option(
"--openai-url",
type=str,
default=None,
help="OpenAI provider URL (default: https://api.openai.com/v1)",
)
@click.option(
"--anthropic-url",
type=str,
default=None,
help="Anthropic provider URL (default: https://api.anthropic.com/v1)",
)
@click.option(
"--ollama-url",
type=str,
default=None,
help="Ollama provider URL (default: http://localhost:11434/api)",
)
def serve(
port: Optional[int],
host: Optional[str],
log_level: Optional[str],
log_format: Optional[str],
config: Optional[Path],
prompts: Optional[Path],
vllm_url: Optional[str],
openai_url: Optional[str],
anthropic_url: Optional[str],
ollama_url: Optional[str],
) -> None:
"""Start the codegate server."""
logger = None
try:
# Create provider URLs dict from CLI options
cli_provider_urls: Dict[str, str] = {}
if vllm_url:
cli_provider_urls["vllm"] = vllm_url
if openai_url:
cli_provider_urls["openai"] = openai_url
if anthropic_url:
cli_provider_urls["anthropic"] = anthropic_url
if ollama_url:
cli_provider_urls["ollama"] = ollama_url
# Load configuration with priority resolution
cfg = Config.load(
config_path=config,
prompts_path=prompts,
cli_port=port,
cli_host=host,
cli_log_level=log_level,
cli_log_format=log_format,
cli_provider_urls=cli_provider_urls,
)
setup_logging(cfg.log_level, cfg.log_format)
logger = structlog.get_logger("codegate")
logger.info(
"Starting server",
extra={
"host": cfg.host,
"port": cfg.port,
"log_level": cfg.log_level.value,
"log_format": cfg.log_format.value,
"prompts_loaded": len(cfg.prompts.prompts),
"provider_urls": cfg.provider_urls,
},
)
init_db_sync()
app = init_app()
import uvicorn
uvicorn.run(
app,
host=cfg.host,
port=cfg.port,
log_level=cfg.log_level.value.lower(),
log_config=None, # Default logging configuration
)
except KeyboardInterrupt:
if logger:
logger.info("Shutting down server")
except ConfigurationError as e:
click.echo(f"Configuration error: {e}", err=True)
sys.exit(1)
except Exception as e:
if logger:
logger.exception("Unexpected error occurred")
click.echo(f"Error: {e}", err=True)
sys.exit(1)
def main() -> None:
"""Main entry point for the CLI."""
cli()
if __name__ == "__main__":
main()