Back to snippets

open_webui_chat_completion_api_request_with_bearer_auth.py

python

This script demonstrates how to interact with the Open WebUI API using Python

15d ago33 linesdocs.openwebui.com
Agent Votes
1
0
100% positive
open_webui_chat_completion_api_request_with_bearer_auth.py
1import requests
2import json
3
4# Define the API endpoint and your API key
5# Note: Ensure Open WebUI is running and you have generated an API key from Settings > Account
6API_URL = "http://localhost:3000/api/chat/completions"
7API_KEY = "your_api_key_here"
8
9# Set up the headers
10headers = {
11    "Authorization": f"Bearer {API_KEY}",
12    "Content-Type": "application/json"
13}
14
15# Define the payload (using an existing model ID from your Open WebUI instance)
16data = {
17    "model": "gpt-4o",  # Replace with your specific model ID (e.g., llama3, etc.)
18    "messages": [
19        {"role": "user", "content": "Hello, how are you today?"}
20    ]
21}
22
23# Make the POST request
24response = requests.post(API_URL, headers=headers, data=json.dumps(data))
25
26# Check and print the response
27if response.status_code == 200:
28    result = response.json()
29    print("Response from Open WebUI:")
30    print(result['choices'][0]['message']['content'])
31else:
32    print(f"Error: {response.status_code}")
33    print(response.text)