File size: 1,265 Bytes
b171cab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import os,time,requests,json
from utils.constants import CHAT_ENDPOINT,MAX_RETRIES_DEFAULT,RETRY_BACKOFF_SECONDS_DEFAULT,REQUEST_TIMEOUT_SECONDS_DEFAULT

def call_endpoint(prompt,endpoint=None,token=None,max_retries=None,backoff=None,timeout=None,logs=None):
    url=endpoint or os.getenv("CHAT_ENDPOINT") or CHAT_ENDPOINT
    tok=token or os.getenv("HF_API_TOKEN")
    if not tok:return "❌ Missing HF_API_TOKEN.",{}
    mr=max_retries or MAX_RETRIES_DEFAULT
    bf=backoff or RETRY_BACKOFF_SECONDS_DEFAULT
    to=timeout or REQUEST_TIMEOUT_SECONDS_DEFAULT

    h={"Authorization":f"Bearer {tok}","Content-Type":"application/json"}
    for a in range(1,mr+1):
        try:
            r=requests.post(url,headers=h,json={"inputs":prompt},timeout=to)
            try:data=r.json()
            except:return "⚠️ Non-JSON:\n"+r.text,{}
            if isinstance(data,list) and data and "generated_text" in data[0]:
                return data[0]["generated_text"],{}
            if isinstance(data,dict) and "generated_text" in data:
                return data["generated_text"],{}
            return "⚠️ Unexpected:"+json.dumps(data)[:500],{}
        except:
            time.sleep(bf*a)
    return "❌ Endpoint unavailable",{}