File size: 1,314 Bytes
72f07a7
fb20156
 
6848db9
 
 
810b499
8a133ff
 
72f07a7
8a133ff
 
fb20156
 
 
 
6848db9
8a133ff
 
 
6848db9
 
 
 
 
 
8a133ff
 
fb20156
 
8a133ff
 
 
 
 
fb20156
8a133ff
 
fb20156
8a133ff
fb20156
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
import os
import requests
from fastapi import FastAPI, HTTPException

app = FastAPI()

HF_TOKEN = os.getenv("HF_API_TOKEN")
if not HF_TOKEN:
    raise RuntimeError("❌ HF_API_TOKEN n'est pas défini comme secret dans ton Space !")

HF_MODEL = "google/flan-t5-base"
HF_API_URL = f"https://api-inference.huggingface.co/models/{HF_MODEL}"
HEADERS = {
    "Authorization": f"Bearer {HF_TOKEN}",
    "Content-Type": "application/json"
}

from pydantic import BaseModel
from typing import Dict

class AgentInput(BaseModel):
    prompt: str
    data: Dict = {}

@app.post("/analyze")
async def analyze(input: AgentInput):
    full_prompt = f"Voici des données JSON : {input.data}\n\nQuestion : {input.prompt}\nRéponse :"
    resp = requests.post(HF_API_URL, headers=HEADERS, json={
        "inputs": full_prompt,
        "parameters": {"max_new_tokens": 200}
    }, timeout=30)

    if resp.status_code == 404:
        # On intercepte le 404 pour te donner plus de contexte
        raise HTTPException(status_code=404, detail=f"Inference API Not Found. URL={HF_API_URL}")
    if resp.status_code != 200:
        raise HTTPException(status_code=500, detail=f"HF Inference error ({resp.status_code}): {resp.text}")

    data = resp.json()
    generated = data[0].get("generated_text")
    return {"response": generated}