Skip to content

Commit 6784cb2

Browse files
authored
Chore dangling changes cleanup (#200)
* commonized and clean up logging in all places, not just most places * one more that is out of place * move to dynamical generating these - might be a better way * more cleanup of envs
1 parent b62b5f3 commit 6784cb2

File tree

8 files changed

+68
-73
lines changed

8 files changed

+68
-73
lines changed

api/api.py

Lines changed: 24 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -10,17 +10,12 @@
1010
import google.generativeai as genai
1111
import asyncio
1212

13-
# Get a logger for this module
14-
logger = logging.getLogger(__name__)
13+
# Configure logging
14+
from api.logging_config import setup_logging
1515

16-
# Get API keys from environment variables
17-
google_api_key = os.environ.get('GOOGLE_API_KEY')
16+
setup_logging()
17+
logger = logging.getLogger(__name__)
1818

19-
# Configure Google Generative AI
20-
if google_api_key:
21-
genai.configure(api_key=google_api_key)
22-
else:
23-
logger.warning("GOOGLE_API_KEY not found in environment variables")
2419

2520
# Initialize FastAPI app
2621
app = FastAPI(
@@ -528,29 +523,29 @@ async def health_check():
528523

529524
@app.get("/")
530525
async def root():
531-
"""Root endpoint to check if the API is running"""
526+
"""Root endpoint to check if the API is running and list available endpoints dynamically."""
527+
# Collect routes dynamically from the FastAPI app
528+
endpoints = {}
529+
for route in app.routes:
530+
if hasattr(route, "methods") and hasattr(route, "path"):
531+
# Skip docs and static routes
532+
if route.path in ["/openapi.json", "/docs", "/redoc", "/favicon.ico"]:
533+
continue
534+
# Group endpoints by first path segment
535+
path_parts = route.path.strip("/").split("/")
536+
group = path_parts[0].capitalize() if path_parts[0] else "Root"
537+
method_list = list(route.methods - {"HEAD", "OPTIONS"})
538+
for method in method_list:
539+
endpoints.setdefault(group, []).append(f"{method} {route.path}")
540+
541+
# Optionally, sort endpoints for readability
542+
for group in endpoints:
543+
endpoints[group].sort()
544+
532545
return {
533546
"message": "Welcome to Streaming API",
534547
"version": "1.0.0",
535-
"endpoints": {
536-
"Chat": [
537-
"POST /chat/completions/stream - Streaming chat completion (HTTP)",
538-
"WebSocket /ws/chat - WebSocket chat completion",
539-
],
540-
"Wiki": [
541-
"POST /export/wiki - Export wiki content as Markdown or JSON",
542-
"GET /api/wiki_cache - Retrieve cached wiki data",
543-
"POST /api/wiki_cache - Store wiki data to cache",
544-
"GET /auth/status - Check if wiki authentication is enabled",
545-
"POST /auth/validate - Check if wiki authentication is valid"
546-
],
547-
"LocalRepo": [
548-
"GET /local_repo/structure - Get structure of a local repository (with path parameter)",
549-
],
550-
"Health": [
551-
"GET /health - Health check endpoint"
552-
]
553-
}
548+
"endpoints": endpoints
554549
}
555550

556551
# --- Processed Projects Endpoint --- (New Endpoint)

api/bedrock_client.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@
1111
from adalflow.core.model_client import ModelClient
1212
from adalflow.core.types import ModelType, GeneratorOutput
1313

14+
# Configure logging
15+
from api.logging_config import setup_logging
16+
17+
setup_logging()
1418
log = logging.getLogger(__name__)
1519

1620
class BedrockClient(ModelClient):
@@ -49,10 +53,12 @@ def __init__(
4953
aws_role_arn: AWS IAM role ARN for role-based authentication. If not provided, will use environment variable AWS_ROLE_ARN.
5054
"""
5155
super().__init__(*args, **kwargs)
52-
self.aws_access_key_id = aws_access_key_id or os.environ.get("AWS_ACCESS_KEY_ID")
53-
self.aws_secret_access_key = aws_secret_access_key or os.environ.get("AWS_SECRET_ACCESS_KEY")
54-
self.aws_region = aws_region or os.environ.get("AWS_REGION", "us-east-1")
55-
self.aws_role_arn = aws_role_arn or os.environ.get("AWS_ROLE_ARN")
56+
from api.config import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION, AWS_ROLE_ARN
57+
58+
self.aws_access_key_id = aws_access_key_id or AWS_ACCESS_KEY_ID
59+
self.aws_secret_access_key = aws_secret_access_key or AWS_SECRET_ACCESS_KEY
60+
self.aws_region = aws_region or AWS_REGION or "us-east-1"
61+
self.aws_role_arn = aws_role_arn or AWS_ROLE_ARN
5662

5763
self.sync_client = self.init_sync_client()
5864
self.async_client = None # Initialize async client only when needed

api/logging_config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ def setup_logging(format: str = None):
3434
# Configure logging handlers and format
3535
logging.basicConfig(
3636
level=log_level,
37-
format=format or "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
37+
format = format or "%(asctime)s - %(levelname)s - %(name)s - %(filename)s:%(lineno)d - %(message)s",
3838
handlers=[
3939
logging.FileHandler(resolved_path),
4040
logging.StreamHandler()

api/main.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@
99

1010
from api.logging_config import setup_logging
1111

12-
# Setup logging with detailed format for main
13-
setup_logging(format="%(asctime)s - %(lineno)d %(filename)s:%(funcName)s - %(levelname)s - %(message)s")
12+
# Configure logging
13+
setup_logging()
1414
logger = logging.getLogger(__name__)
1515

1616
# Add the current directory to the path so we can import the api package
@@ -23,6 +23,15 @@
2323
logger.warning(f"Missing environment variables: {', '.join(missing_vars)}")
2424
logger.warning("Some functionality may not work correctly without these variables.")
2525

26+
# Configure Google Generative AI
27+
import google.generativeai as genai
28+
from api.config import GOOGLE_API_KEY
29+
30+
if GOOGLE_API_KEY:
31+
genai.configure(api_key=GOOGLE_API_KEY)
32+
else:
33+
logger.warning("GOOGLE_API_KEY not configured")
34+
2635
if __name__ == "__main__":
2736
# Get port from environment variable or use default
2837
port = int(os.environ.get("PORT", 8001))

api/ollama_patch.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from adalflow.core.types import Document
77
from adalflow.core.component import DataComponent
88

9-
# Unified logging setup
9+
# Configure logging
1010
from api.logging_config import setup_logging
1111

1212
setup_logging()

api/openrouter_client.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
"""OpenRouter ModelClient integration."""
22

3-
import os
43
from typing import Dict, Sequence, Optional, Any, List
54
import logging
65
import json
@@ -45,9 +44,10 @@ def __init__(self, *args, **kwargs) -> None:
4544

4645
def init_sync_client(self):
4746
"""Initialize the synchronous OpenRouter client."""
48-
api_key = os.environ.get("OPENROUTER_API_KEY")
47+
from api.config import OPENROUTER_API_KEY
48+
api_key = OPENROUTER_API_KEY
4949
if not api_key:
50-
log.warning("OPENROUTER_API_KEY not found in environment variables")
50+
log.warning("OPENROUTER_API_KEY not configured")
5151

5252
# OpenRouter doesn't have a dedicated client library, so we'll use requests directly
5353
return {
@@ -57,9 +57,10 @@ def init_sync_client(self):
5757

5858
def init_async_client(self):
5959
"""Initialize the asynchronous OpenRouter client."""
60-
api_key = os.environ.get("OPENROUTER_API_KEY")
60+
from api.config import OPENROUTER_API_KEY
61+
api_key = OPENROUTER_API_KEY
6162
if not api_key:
62-
log.warning("OPENROUTER_API_KEY not found in environment variables")
63+
log.warning("OPENROUTER_API_KEY not configured")
6364

6465
# For async, we'll use aiohttp
6566
return {
@@ -115,7 +116,7 @@ async def acall(self, api_kwargs: Dict = None, model_type: ModelType = None) ->
115116

116117
# Check if API key is set
117118
if not self.async_client.get("api_key"):
118-
error_msg = "OPENROUTER_API_KEY not found in environment variables. Please set this environment variable to use OpenRouter."
119+
error_msg = "OPENROUTER_API_KEY not configured. Please set this environment variable to use OpenRouter."
119120
log.error(error_msg)
120121
# Instead of raising an exception, return a generator that yields the error message
121122
# This allows the error to be displayed to the user in the streaming response

api/simple_chat.py

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -11,27 +11,19 @@
1111
from fastapi.responses import StreamingResponse
1212
from pydantic import BaseModel, Field
1313

14-
from api.config import get_model_config, configs
14+
from api.config import get_model_config, configs, OPENROUTER_API_KEY, OPENAI_API_KEY, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
1515
from api.data_pipeline import count_tokens, get_file_content
1616
from api.openai_client import OpenAIClient
1717
from api.openrouter_client import OpenRouterClient
1818
from api.bedrock_client import BedrockClient
1919
from api.rag import RAG
2020

21-
# Unified logging setup
21+
# Configure logging
2222
from api.logging_config import setup_logging
2323

2424
setup_logging()
2525
logger = logging.getLogger(__name__)
2626

27-
# Get API keys from environment variables
28-
google_api_key = os.environ.get('GOOGLE_API_KEY')
29-
30-
# Configure Google Generative AI
31-
if google_api_key:
32-
genai.configure(api_key=google_api_key)
33-
else:
34-
logger.warning("GOOGLE_API_KEY not found in environment variables")
3527

3628
# Initialize FastAPI app
3729
app = FastAPI(
@@ -455,8 +447,8 @@ async def chat_completions_stream(request: ChatCompletionRequest):
455447
logger.info(f"Using OpenRouter with model: {request.model}")
456448

457449
# Check if OpenRouter API key is set
458-
if not os.environ.get("OPENROUTER_API_KEY"):
459-
logger.warning("OPENROUTER_API_KEY environment variable is not set, but continuing with request")
450+
if not OPENROUTER_API_KEY:
451+
logger.warning("OPENROUTER_API_KEY not configured, but continuing with request")
460452
# We'll let the OpenRouterClient handle this and return a friendly error message
461453

462454
model = OpenRouterClient()
@@ -476,8 +468,8 @@ async def chat_completions_stream(request: ChatCompletionRequest):
476468
logger.info(f"Using Openai protocol with model: {request.model}")
477469

478470
# Check if an API key is set for Openai
479-
if not os.environ.get("OPENAI_API_KEY"):
480-
logger.warning("OPENAI_API_KEY environment variable is not set, but continuing with request")
471+
if not OPENAI_API_KEY:
472+
logger.warning("OPENAI_API_KEY not configured, but continuing with request")
481473
# We'll let the OpenAIClient handle this and return an error message
482474

483475
# Initialize Openai client
@@ -498,8 +490,8 @@ async def chat_completions_stream(request: ChatCompletionRequest):
498490
logger.info(f"Using AWS Bedrock with model: {request.model}")
499491

500492
# Check if AWS credentials are set
501-
if not os.environ.get("AWS_ACCESS_KEY_ID") or not os.environ.get("AWS_SECRET_ACCESS_KEY"):
502-
logger.warning("AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY environment variables are not set, but continuing with request")
493+
if not AWS_ACCESS_KEY_ID or not AWS_SECRET_ACCESS_KEY:
494+
logger.warning("AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY not configured, but continuing with request")
503495
# We'll let the BedrockClient handle this and return an error message
504496

505497
# Initialize Bedrock client

api/websocket_wiki.py

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,26 +9,18 @@
99
from fastapi import WebSocket, WebSocketDisconnect, HTTPException
1010
from pydantic import BaseModel, Field
1111

12-
from api.config import get_model_config, configs
12+
from api.config import get_model_config, configs, OPENROUTER_API_KEY, OPENAI_API_KEY
1313
from api.data_pipeline import count_tokens, get_file_content
1414
from api.openai_client import OpenAIClient
1515
from api.openrouter_client import OpenRouterClient
1616
from api.rag import RAG
1717

18-
# Unified logging setup
18+
# Configure logging
1919
from api.logging_config import setup_logging
2020

2121
setup_logging()
2222
logger = logging.getLogger(__name__)
2323

24-
# Get API keys from environment variables
25-
google_api_key = os.environ.get('GOOGLE_API_KEY')
26-
27-
# Configure Google Generative AI
28-
if google_api_key:
29-
genai.configure(api_key=google_api_key)
30-
else:
31-
logger.warning("GOOGLE_API_KEY not found in environment variables")
3224

3325
# Models for the API
3426
class ChatMessage(BaseModel):
@@ -455,8 +447,8 @@ async def handle_websocket_chat(websocket: WebSocket):
455447
logger.info(f"Using OpenRouter with model: {request.model}")
456448

457449
# Check if OpenRouter API key is set
458-
if not os.environ.get("OPENROUTER_API_KEY"):
459-
logger.warning("OPENROUTER_API_KEY environment variable is not set, but continuing with request")
450+
if not OPENROUTER_API_KEY:
451+
logger.warning("OPENROUTER_API_KEY not configured, but continuing with request")
460452
# We'll let the OpenRouterClient handle this and return a friendly error message
461453

462454
model = OpenRouterClient()
@@ -476,8 +468,8 @@ async def handle_websocket_chat(websocket: WebSocket):
476468
logger.info(f"Using Openai protocol with model: {request.model}")
477469

478470
# Check if an API key is set for Openai
479-
if not os.environ.get("OPENAI_API_KEY"):
480-
logger.warning("OPENAI_API_KEY environment variable is not set, but continuing with request")
471+
if not OPENAI_API_KEY:
472+
logger.warning("OPENAI_API_KEY not configured, but continuing with request")
481473
# We'll let the OpenAIClient handle this and return an error message
482474

483475
# Initialize Openai client

0 commit comments

Comments
 (0)