|
1 | 1 | import logging |
2 | | -from typing import Union |
3 | | -from fastapi import APIRouter |
| 2 | +from typing import Union, List, Dict, Any |
| 3 | +from fastapi import APIRouter, HTTPException |
4 | 4 | from sse_starlette.sse import EventSourceResponse |
5 | 5 |
|
6 | 6 | from app.ai.aimo import AIMO |
| 7 | +from app.clients.llm_client import llm_client |
7 | 8 |
|
8 | 9 | logger = logging.getLogger(__name__) |
9 | 10 | from app.models.openai import ( |
|
12 | 13 | ChatChoice, |
13 | 14 | Message |
14 | 15 | ) |
| 16 | +from app.models.llm import LLMChatRequest, LLMChatResponse, LLMChoice, LLMMessage, LLMUsage |
15 | 17 |
|
16 | 18 | """ |
17 | 19 | Author: Jack Pan, Wesley Xu |
@@ -52,3 +54,116 @@ async def create_chat_completion(request: ChatCompletionRequest) -> Union[ChatCo |
52 | 54 | max_new_tokens=request.max_tokens |
53 | 55 | ) |
54 | 56 | ) |
| 57 | + |
| 58 | + |
| 59 | +@router.post("/completions_proxy", response_model=LLMChatResponse) |
| 60 | +async def create_chat_completion_proxy(request: LLMChatRequest) -> Union[LLMChatResponse, EventSourceResponse]: |
| 61 | + """ |
| 62 | + LiteLLM Proxy chat completion endpoint. |
| 63 | + |
| 64 | + This route demonstrates using the new LLM client to interact with LiteLLM Proxy, |
| 65 | + which can route to multiple LLM providers (OpenAI, Anthropic, local models, etc.). |
| 66 | + """ |
| 67 | + try: |
| 68 | + # Convert pydantic models to dict format expected by openai client |
| 69 | + messages = [{"role": msg.role, "content": msg.content} for msg in request.messages] |
| 70 | + |
| 71 | + if not request.stream: |
| 72 | + # Non-streaming response |
| 73 | + response = await llm_client.chat( |
| 74 | + messages=messages, |
| 75 | + model=request.model, |
| 76 | + temperature=request.temperature, |
| 77 | + max_tokens=request.max_tokens, |
| 78 | + tools=request.tools, |
| 79 | + tool_choice=request.tool_choice, |
| 80 | + presence_penalty=request.presence_penalty, |
| 81 | + frequency_penalty=request.frequency_penalty, |
| 82 | + top_p=request.top_p, |
| 83 | + user=request.user |
| 84 | + ) |
| 85 | + |
| 86 | + # Convert OpenAI response to our LLM response format |
| 87 | + choices = [] |
| 88 | + for choice in response.choices: |
| 89 | + llm_choice = LLMChoice( |
| 90 | + index=choice.index, |
| 91 | + message=LLMMessage( |
| 92 | + role=choice.message.role, |
| 93 | + content=choice.message.content or "" |
| 94 | + ), |
| 95 | + finish_reason=choice.finish_reason |
| 96 | + ) |
| 97 | + choices.append(llm_choice) |
| 98 | + |
| 99 | + usage = None |
| 100 | + if response.usage: |
| 101 | + usage = LLMUsage( |
| 102 | + prompt_tokens=response.usage.prompt_tokens, |
| 103 | + completion_tokens=response.usage.completion_tokens, |
| 104 | + total_tokens=response.usage.total_tokens |
| 105 | + ) |
| 106 | + |
| 107 | + return LLMChatResponse( |
| 108 | + id=response.id, |
| 109 | + model=response.model, |
| 110 | + choices=choices, |
| 111 | + usage=usage |
| 112 | + ) |
| 113 | + else: |
| 114 | + # Streaming response |
| 115 | + async def stream_generator(): |
| 116 | + async for chunk in await llm_client.chat( |
| 117 | + messages=messages, |
| 118 | + model=request.model, |
| 119 | + temperature=request.temperature, |
| 120 | + max_tokens=request.max_tokens, |
| 121 | + stream=True, |
| 122 | + tools=request.tools, |
| 123 | + tool_choice=request.tool_choice, |
| 124 | + presence_penalty=request.presence_penalty, |
| 125 | + frequency_penalty=request.frequency_penalty, |
| 126 | + top_p=request.top_p, |
| 127 | + user=request.user |
| 128 | + ): |
| 129 | + if chunk.choices: |
| 130 | + choice = chunk.choices[0] |
| 131 | + if choice.delta and choice.delta.get('content'): |
| 132 | + yield f"data: {choice.delta['content']}\n\n" |
| 133 | + |
| 134 | + yield "data: [DONE]\n\n" |
| 135 | + |
| 136 | + return EventSourceResponse(stream_generator()) |
| 137 | + |
| 138 | + except Exception as e: |
| 139 | + logger.error(f"Error in chat_proxy: {e}") |
| 140 | + raise HTTPException(status_code=500, detail=f"LLM service error: {str(e)}") |
| 141 | + |
| 142 | + |
| 143 | +@router.get("/models") |
| 144 | +async def list_available_models() -> Dict[str, List[str]]: |
| 145 | + """Get available models from LiteLLM Proxy.""" |
| 146 | + try: |
| 147 | + models = await llm_client.get_available_models() |
| 148 | + return {"models": models} |
| 149 | + except Exception as e: |
| 150 | + logger.error(f"Error getting models: {e}") |
| 151 | + raise HTTPException(status_code=500, detail=f"Error fetching models: {str(e)}") |
| 152 | + |
| 153 | + |
| 154 | +@router.get("/health") |
| 155 | +async def health_check() -> Dict[str, Any]: |
| 156 | + """Health check for LiteLLM Proxy connection.""" |
| 157 | + try: |
| 158 | + is_healthy = await llm_client.health_check() |
| 159 | + return { |
| 160 | + "status": "healthy" if is_healthy else "unhealthy", |
| 161 | + "llm_proxy_connected": is_healthy |
| 162 | + } |
| 163 | + except Exception as e: |
| 164 | + logger.error(f"Health check error: {e}") |
| 165 | + return { |
| 166 | + "status": "unhealthy", |
| 167 | + "llm_proxy_connected": False, |
| 168 | + "error": str(e) |
| 169 | + } |
0 commit comments