Spaces:
Runtime error
Runtime error
File size: 8,096 Bytes
c0658b2 cb0bf83 f88a286 69eed4a cb0bf83 e1d21ef cb0bf83 ad93aea cb0bf83 f88a286 cb0bf83 69eed4a cb0bf83 c0658b2 cb0bf83 f88a286 cb0bf83 c0658b2 cb0bf83 ad93aea 69eed4a ad93aea cb0bf83 69eed4a 79aceed 69eed4a c0658b2 69eed4a c0658b2 69eed4a c0658b2 0cef40a 69eed4a ad93aea 79aceed 69eed4a cb0bf83 f88a286 cb0bf83 f88a286 c0658b2 69eed4a c0658b2 f88a286 cb0bf83 f88a286 cb0bf83 f88a286 cb0bf83 69eed4a f88a286 e1d21ef f88a286 e1d21ef 69eed4a 79aceed |
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 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 |
# # app.py
# import os
# import logging
# from fastapi import FastAPI, HTTPException
# from fastapi.responses import JSONResponse
# from pydantic import BaseModel
# from huggingface_hub import InferenceClient
# from typing import Optional
# # Set up logging
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)
# # Initialize FastAPI app
# app = FastAPI(
# title="LLM Chat API",
# description="API for getting chat responses from Llama model",
# version="1.0.0"
# )
# class ChatRequest(BaseModel):
# text: str
# class ChatResponse(BaseModel):
# response: str
# status: str
# def llm_chat_response(text: str) -> str:
# try:
# HF_TOKEN = os.getenv("HF_TOKEN")
# logger.info("Checking HF_TOKEN...")
# if not HF_TOKEN:
# logger.error("HF_TOKEN not found in environment variables")
# raise HTTPException(status_code=500, detail="HF_TOKEN not configured")
# logger.info("Initializing InferenceClient...")
# client = InferenceClient(
# provider="sambanova",
# api_key=HF_TOKEN
# )
# messages = [
# {
# "role": "user",
# "content": [
# {
# "type": "text",
# "text": text + " describe in one line only"
# }
# ]
# }
# ]
# logger.info("Sending request to model...")
# completion = client.chat.completions.create(
# model="meta-llama/Llama-3.2-11B-Vision-Instruct",
# messages=messages,
# max_tokens=500
# )
# return completion.choices[0].message['content']
# except Exception as e:
# logger.error(f"Error in llm_chat_response: {str(e)}")
# raise HTTPException(status_code=500, detail=str(e))
# @app.post("/chat", response_model=ChatResponse)
# async def chat(request: ChatRequest):
# try:
# logger.info(f"Received chat request with text: {request.text}")
# response = llm_chat_response(request.text)
# return ChatResponse(response=response, status="success")
# except HTTPException as he:
# logger.error(f"HTTP Exception in chat endpoint: {str(he)}")
# raise he
# except Exception as e:
# logger.error(f"Unexpected error in chat endpoint: {str(e)}")
# raise HTTPException(status_code=500, detail=str(e))
# @app.get("/")
# async def root():
# return {"message": "Welcome to the LLM Chat API. Use POST /chat endpoint to get responses."}
# @app.exception_handler(404)
# async def not_found_handler(request, exc):
# return JSONResponse(
# status_code=404,
# content={"error": "Endpoint not found. Please use POST /chat for queries."}
# )
# @app.exception_handler(405)
# async def method_not_allowed_handler(request, exc):
# return JSONResponse(
# status_code=405,
# content={"error": "Method not allowed. Please check the API documentation."}
# )
# app.py
import os
import logging
from typing import Optional
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from huggingface_hub import InferenceClient
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Initialize FastAPI app
app = FastAPI(
title="LLM Chat API",
description="API for getting chat responses from Llama model (supports text and image input)",
version="1.0.0"
)
class ChatRequest(BaseModel):
text: str
image_url: Optional[str] = None
class ChatResponse(BaseModel):
response: str
status: str
def llm_chat_response(text: str, image_url: Optional[str] = None) -> str:
try:
HF_TOKEN = os.getenv("HF_TOKEN")
logger.info("Checking HF_TOKEN...")
if not HF_TOKEN:
logger.error("HF_TOKEN not found in environment variables")
raise HTTPException(status_code=500, detail="HF_TOKEN not configured")
logger.info("Initializing InferenceClient...")
client = InferenceClient(
provider="sambanova",
api_key=HF_TOKEN
)
# Build the messages payload dynamically.
# If only text is provided, we append a default instruction.
message_content = [{
"type": "text",
"text": text + ("" if image_url else " describe in one line only")
}]
if image_url:
message_content.append({
"type": "image_url",
"image_url": {"url": image_url}
})
messages = [{
"role": "user",
"content": message_content
}]
logger.info("Sending request to model...")
completion = client.chat.completions.create(
model="meta-llama/Llama-3.2-11B-Vision-Instruct",
messages=messages,
max_tokens=500
)
# Debug log the raw response for troubleshooting.
logger.info(f"Raw model response: {completion}")
# Ensure we have a valid response.
if not completion.choices or len(completion.choices) == 0:
logger.error("No choices returned from model.")
raise HTTPException(status_code=500, detail="Model returned no choices.")
# Extract the message; use dict get to avoid NoneType errors.
response_message = None
# Some responses may be dicts or objects; try both approaches.
choice = completion.choices[0]
if hasattr(choice, "message"):
response_message = choice.message
elif isinstance(choice, dict):
response_message = choice.get("message")
if not response_message:
logger.error(f"Response message is empty: {choice}")
raise HTTPException(status_code=500, detail="Model response did not include a message.")
# Extract the content from the message.
content = None
if isinstance(response_message, dict):
content = response_message.get("content")
# If for some reason it's not a dict, try attribute access.
if content is None and hasattr(response_message, "content"):
content = response_message.content
if not content:
logger.error(f"Message content is missing: {response_message}")
raise HTTPException(status_code=500, detail="Model message did not include content.")
return content
except Exception as e:
logger.error(f"Error in llm_chat_response: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/chat", response_model=ChatResponse)
async def chat(request: ChatRequest):
try:
logger.info(f"Received chat request with text: {request.text}")
if request.image_url:
logger.info(f"Image URL provided: {request.image_url}")
response = llm_chat_response(request.text, request.image_url)
return ChatResponse(response=response, status="success")
except HTTPException as he:
logger.error(f"HTTP Exception in chat endpoint: {str(he)}")
raise he
except Exception as e:
logger.error(f"Unexpected error in chat endpoint: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@app.get("/")
async def root():
return {"message": "Welcome to the LLM Chat API. Use POST /chat endpoint with 'text' and optionally 'image_url' for queries."}
@app.exception_handler(404)
async def not_found_handler(request, exc):
return JSONResponse(
status_code=404,
content={"error": "Endpoint not found. Please use POST /chat for queries."}
)
@app.exception_handler(405)
async def method_not_allowed_handler(request, exc):
return JSONResponse(
status_code=405,
content={"error": "Method not allowed. Please check the API documentation."}
)
|