welcom ! Handel home

2025年3月31日 星期一

ollama api upload image file python demo

 import requests

import json

import base64



# 讀取本地圖片並轉 base64

with open("demo.jpg", "rb") as image_file:

    base64_image = base64.b64encode(image_file.read()).decode('utf-8')


url = "http://192.168.5.53:11434/v1/chat/completions"

headers = {'Content-Type': 'application/json'}

data = {

    "model": "gemma3:4b",

"messages": [

        {

            "role": "user",

            "content": [

                {"type": "text", "text": "請幫我描述這張圖:"},

                {

                    "type": "image_url",

                    "image_url": {

                        "url": f"data:image/jpeg;base64,{base64_image}"

                    }

                }

            ]

        }

    ],

    "max_tokens": 1000

}


try:

    response = requests.post(url, headers=headers, data=json.dumps(data))

    response.raise_for_status()  # Raise HTTPError for bad responses (4xx or 5xx)

    print(response.json())  # Print the JSON response

except requests.exceptions.RequestException as e:

    print(f"Error: {e}")

except json.JSONDecodeError as e:

    print(f"Error decoding JSON: {e}")

    print(f"Raw response text: {response.text}")


沒有留言: