Spaces:
Runtime error
Runtime error
File size: 7,363 Bytes
c0658b2 cb0bf83 f88a286 cb0bf83 e1d21ef cb0bf83 ad93aea cb0bf83 f88a286 cb0bf83 c0658b2 cb0bf83 c0658b2 cb0bf83 f88a286 cb0bf83 c0658b2 cb0bf83 ad93aea c0658b2 ad93aea cb0bf83 c0658b2 ad93aea c0658b2 ad93aea c0658b2 ad93aea 0cef40a ad93aea 0cef40a cb0bf83 f88a286 cb0bf83 f88a286 c0658b2 f88a286 cb0bf83 f88a286 cb0bf83 f88a286 cb0bf83 c0658b2 f88a286 e1d21ef f88a286 e1d21ef |
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 |
# # 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 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 with image support",
version="1.1.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
)
# Prepare content list for the message
content = [
{
"type": "text",
"text": text + " describe in one line only"
}
]
# Add image to content if provided
if image_url:
logger.info(f"Adding image URL to request: {image_url}")
content.append({
"type": "image_url",
"image_url": {
"url": image_url
}
})
messages = [
{
"role": "user",
"content": content
}
]
logger.info("Sending request to model...")
logger.info(f"Request payload: {messages}")
completion = client.chat.completions.create(
model="meta-llama/Llama-3.2-11B-Vision-Instruct",
messages=messages,
max_tokens=500
)
logger.info(f"Response received: {completion}")
# Check the structure of the response and extract content
if hasattr(completion, 'choices') and len(completion.choices) > 0:
message = completion.choices[0].message
# Handle different response formats
if isinstance(message, dict) and 'content' in message:
return message['content']
elif hasattr(message, 'content'):
return message.content
else:
logger.error(f"Unexpected message format: {message}")
return str(message)
else:
logger.error(f"Unexpected completion format: {completion}")
return str(completion)
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 included: {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 with image support. 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."}
) |