File size: 13,101 Bytes
4609499 b26e69c 4609499 aefe056 4609499 aefe056 4609499 aefe056 | 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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 | import gradio as gr
import requests
import json
import os
from typing import List, Dict, Optional
class BinericAPI:
def __init__(self):
self.api_key = os.environ.get("Key")
if not self.api_key or self.api_key == "YOUR_API_KEY":
raise ValueError("API Key not found. Please add your API key in the 'Secrets' tab (Key = 'YOUR_API_KEY')")
self.base_url = "https://api.bineric.com/api/v1"
self.headers = {'api-key': self.api_key}
def get_balance(self):
"""Fetch balance from Bineric API"""
try:
response = requests.get(
f'{self.base_url}/monitoring/balance',
headers=self.headers
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
return {"error": f"API request failed: {str(e)}"}
def chat_completion(self, model: str, messages: List[Dict],
stream: bool = False, temperature: float = 0.7,
max_response_length: Optional[int] = None,
top_p: float = 0.95):
"""Get chat completion from various AI models"""
try:
# Prepare request payload
payload = {
"model": model,
"messages": messages,
"options": {
"stream": stream,
"temperature": temperature,
"top_p": top_p
}
}
# Add max_response_length if provided
if max_response_length:
payload["options"]["max_response_length"] = max_response_length
# Make API request
response = requests.post(
f'{self.base_url}/ai/chat/completions',
headers=self.headers,
json=payload
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
return {"error": f"Chat completion failed: {str(e)}"}
# Initialize API client
try:
api_client = BinericAPI()
except ValueError as e:
api_client = None
# Available models organized by provider
MODELS = {
"OpenAI": [
"gpt-5",
"gpt-5-nano",
"gpt-4",
"o1",
"o3-mini",
"gpt-oss-120b",
"gpt-oss-20b"
],
"Google": [
"gemini-2.0-flash",
"gemini-2.5-flash",
"gemini-2.5-pro",
"gemini-3-pro-preview"
],
"Anthropic": [
"claude-3.7-sonnet",
"claude-sonnet-4",
"claude-haiku-4-5"
],
"DeepSeek": [
"deepseek-v3.1-terminus",
"deepseek-r1-0528"
],
"Meta": [
"meta-llama-3.1-8b",
"meta-llama-3.1-405b",
"meta-llama-3.3-70b"
],
"Other": [
"norskgpt",
"qwen-3-coder-480b",
"qwen-3-235b",
"mistral_large_24_02",
"llama4-maverick",
"llama4-scout"
]
}
def get_balance():
"""Fetch and display balance"""
if not api_client:
return "❌ API Key not found. Please add your API key in the 'Secrets' tab (Key = 'YOUR_API_KEY')"
balance_data = api_client.get_balance()
if "error" in balance_data:
return f"❌ Error: {balance_data['error']}"
# Format the JSON response for better readability
formatted_response = json.dumps(balance_data, indent=2)
return f"✅ Balance retrieved successfully:\n\n{formatted_response}"
def chat_complete(model, system_prompt, user_message, temperature, max_tokens, top_p, history=None):
"""Generate chat completion"""
if not api_client:
return "", history, "❌ API Key not found. Please add your API key in the 'Secrets' tab"
# Prepare messages
messages = []
# Add system prompt if provided
if system_prompt.strip():
messages.append({"role": "system", "content": system_prompt})
# Add conversation history
if history:
for entry in history:
messages.append({"role": "user", "content": entry["user"]})
if entry["assistant"]:
messages.append({"role": "assistant", "content": entry["assistant"]})
# Add current user message
messages.append({"role": "user", "content": user_message})
# Get completion
result = api_client.chat_completion(
model=model,
messages=messages,
temperature=temperature,
max_response_length=max_tokens if max_tokens > 0 else None,
top_p=top_p
)
if "error" in result:
return "", history, f"❌ Error: {result['error']}"
# Extract response text
if "choices" in result and len(result["choices"]) > 0:
response_text = result["choices"][0].get("message", {}).get("content", "No response generated")
# Update history
if history is None:
history = []
history.append({
"user": user_message,
"assistant": response_text
})
# Format usage info if available
usage_info = ""
if "usage" in result:
usage = result["usage"]
usage_info = f"\n\n**Usage:**\n- Prompt tokens: {usage.get('prompt_tokens', 'N/A')}\n- Completion tokens: {usage.get('completion_tokens', 'N/A')}\n- Total tokens: {usage.get('total_tokens', 'N/A')}"
return "", history, response_text + usage_info
else:
return "", history, "❌ No response generated from the model"
def clear_chat():
"""Clear chat history"""
return [], "", ""
# Create Gradio interface
with gr.Blocks(title="Bineric AI Dashboard") as demo:
gr.Markdown("# 🤖 Bineric AI Dashboard")
gr.Markdown("Balance checking and AI chat completion using Bineric API")
# Tabs for different functionalities
with gr.Tabs():
# Tab 1: Balance Checker
with gr.Tab("💰 Balance"):
gr.Markdown("### Check your API balance")
with gr.Accordion("ℹ️ Setup Instructions", open=False):
gr.Markdown("""
1. **Add your API key in Gradio Secrets:**
- Go to the "Secrets" tab
- Add a new secret with:
- Key: `Key`
- Value: `YOUR_API_KEY_HERE`
2. **Click the button below to fetch balance**
""")
balance_output = gr.Textbox(
label="Balance Information",
placeholder="Click 'Get Balance' to see your balance...",
lines=15
)
with gr.Row():
get_balance_btn = gr.Button("🔄 Get Balance", variant="primary")
clear_balance_btn = gr.Button("🗑️ Clear")
get_balance_btn.click(get_balance, outputs=balance_output)
clear_balance_btn.click(lambda: "", outputs=balance_output)
# Tab 2: Chat Completion
with gr.Tab("💬 AI Chat"):
gr.Markdown("### Chat with various AI models")
with gr.Row():
# Left column: Settings and input
with gr.Column(scale=1):
# Model selection with groups
model_selector = gr.Dropdown(
label="Select AI Model",
choices=[model for models in MODELS.values() for model in models],
value="gpt-5",
interactive=True
)
# Add model provider filter
provider_filter = gr.Dropdown(
label="Filter by Provider",
choices=list(MODELS.keys()),
value="OpenAI",
interactive=True
)
# System prompt
system_prompt = gr.Textbox(
label="System Prompt (optional)",
placeholder="You are a helpful assistant...",
lines=3
)
# Generation parameters
with gr.Accordion("⚙️ Advanced Parameters", open=False):
temperature = gr.Slider(
label="Temperature",
minimum=0.0,
maximum=2.0,
value=0.7,
step=0.1
)
max_tokens = gr.Slider(
label="Max Tokens (0 = unlimited)",
minimum=0,
maximum=10000,
value=0,
step=100
)
top_p = gr.Slider(
label="Top-p",
minimum=0.0,
maximum=1.0,
value=0.95,
step=0.05
)
# Right column: Chat interface
with gr.Column(scale=2):
# Chat history
chatbot = gr.Chatbot(
label="Conversation",
height=400
)
# Hidden state for chat history
chat_state = gr.State([])
# User input
user_input = gr.Textbox(
label="Your Message",
placeholder="Type your message here...",
lines=3
)
# Response info
response_info = gr.Markdown("")
# Buttons
with gr.Row():
send_btn = gr.Button("📤 Send", variant="primary")
clear_chat_btn = gr.Button("🗑️ Clear Chat")
with gr.Row():
gr.Markdown("**Tip:** Press Shift+Enter for new line, Enter to send")
# Update model list based on provider filter
def update_model_list(provider):
return gr.Dropdown(choices=MODELS[provider], value=MODELS[provider][0])
provider_filter.change(
update_model_list,
inputs=provider_filter,
outputs=model_selector
)
# Chat functions
def send_message(model, system, message, temp, tokens, top, history):
return chat_complete(model, system, message, temp, tokens, top, history)
# Connect send button
send_btn.click(
send_message,
inputs=[model_selector, system_prompt, user_input, temperature, max_tokens, top_p, chat_state],
outputs=[user_input, chat_state, response_info]
)
# Allow Enter to send
user_input.submit(
send_message,
inputs=[model_selector, system_prompt, user_input, temperature, max_tokens, top_p, chat_state],
outputs=[user_input, chat_state, response_info]
)
# Clear chat
clear_chat_btn.click(
clear_chat,
outputs=[chat_state, user_input, response_info]
)
# Tab 3: Model Information
with gr.Tab("📚 Model Info"):
gr.Markdown("### Available AI Models")
for provider, models in MODELS.items():
with gr.Accordion(f"🔹 {provider}", open=False):
model_table = []
for model in models:
model_table.append(f"- **{model}**")
gr.Markdown("\n".join(model_table))
gr.Markdown("""
---
**API Documentation:**
- All models use the same chat completion endpoint
- Request format: JSON with messages array
- Support for system prompts and conversation history
- Token usage tracking available in responses
""")
# Footer
gr.Markdown("""
---
**Note:** This dashboard uses the Bineric API. Make sure your API key has access to the models you want to use.
Balance information is fetched from the monitoring endpoint.
""")
# Launch the app
if __name__ == "__main__":
demo.launch(
theme=gr.themes.Soft(),
share=True
) |