"""Python 3.11+. Each item makes one paid call. No automatic retries."""
import asyncio
import json
import os
import urllib.request
from urllib.error import HTTPError, URLError
from http.client import HTTPException

def request_one(prompt, key, model, opener=urllib.request.urlopen):
    request=urllib.request.Request(
        'https://uncensuredai.com/v1/chat/completions',
        data=json.dumps({'model':model,'messages':[{'role':'user','content':prompt}],'stream':False}).encode(),
        headers={'Authorization':f'Bearer {key}','Content-Type':'application/json'},
    )
    with opener(request, timeout=90) as response:
        result=json.load(response)
    return result['choices'][0]['message']['content']

async def batch(prompts, key, model='glm-5.3-flash-abliterated', concurrency=2, sender=request_one):
    if not key:
        raise ValueError('Set UNCENSUREDAI_API_KEY in the server environment.')
    if isinstance(concurrency,bool) or not isinstance(concurrency,int) or concurrency<1:
        raise ValueError('Concurrency must be a positive integer.')
    semaphore=asyncio.Semaphore(concurrency)
    async def run(index,prompt):
        async with semaphore:
            try:
                text=await asyncio.to_thread(sender,prompt,key,model)
                return {'index':index,'ok':True,'text':text}
            except HTTPError as error:
                return {'index':index,'ok':False,'error':f'HTTP {error.code}; no automatic retry'}
            except (URLError,OSError,HTTPException):
                return {'index':index,'ok':False,'error':'Network failure or timeout; outcome may be unknown; no automatic retry'}
            except (KeyError,IndexError,TypeError,ValueError):
                return {'index':index,'ok':False,'error':'Unexpected response; inspect locally without logging credentials'}
    return await asyncio.gather(*(run(i,p) for i,p in enumerate(prompts)))

if __name__=='__main__':
    results=asyncio.run(batch(['Summarize what an API is.','Explain input versus output tokens.'],os.environ.get('UNCENSUREDAI_API_KEY'),model=os.environ.get('MODEL','glm-5.3-flash-abliterated')))
    # Prints model outputs locally. Choose your own retention policy before using real customer prompts.
    print(json.dumps(results,indent=2))
