import asyncio
import io
import sys


sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

API_URL = "http://172.16.2.210:3002/v1/chat/completions"
API_KEY = "freellmapi-a858c30561987b8aa2a58343c7fe48a6a52e65cadb9df6d5"

async def main():
    import base64

    import httpx
    async with httpx.AsyncClient() as client:
        r = await client.get("https://raw.githubusercontent.com/octocat/Spoon-Knife/master/README.md") # fallback small image or just an image from github
        r = await client.get("https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png")
        b64 = base64.b64encode(r.content).decode("utf-8")
    
    payload = {
        "model": "gpt-4o",
        "messages": [
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": "What is in this image?"
                    },
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": f"data:image/png;base64,{b64}"
                        }
                    }
                ]
            }
        ],
        "max_tokens": 500
    }
    
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    print(f"Calling {API_URL} ...")
    try:
        async with httpx.AsyncClient(timeout=30) as client:
            resp = await client.post(API_URL, json=payload, headers=headers)
            print("Status Code:", resp.status_code)
            if resp.status_code == 200:
                data = resp.json()
                print("Response:", data["choices"][0]["message"]["content"])
            else:
                print("Error Response:", resp.text)
    except Exception as e:
        print("Exception:", e)

if __name__ == "__main__":
    asyncio.run(main())
