-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrahyana_client.py
More file actions
52 lines (42 loc) · 1.69 KB
/
rahyana_client.py
File metadata and controls
52 lines (42 loc) · 1.69 KB
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations
import os
import json
from typing import Any, Dict, List, Optional
import requests
class RahyanaClient:
def __init__(self, api_key: Optional[str] = None, base_url: Optional[str] = None, timeout: int = 30) -> None:
self.api_key = api_key or os.getenv("API_KEY_OVERRIDE") or "YOUR_API_KEY_HERE"
self.base_url = base_url or os.getenv("BASE_URL_OVERRIDE") or "https://rahyana.ir/api/v1"
self.timeout = timeout
def _headers(self) -> Dict[str, str]:
return {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_key}",
"Accept": "application/json",
}
def post_json(self, path: str, payload: Dict[str, Any]) -> Dict[str, Any]:
url = f"{self.base_url.rstrip('/')}/{path.lstrip('/')}"
try:
resp = requests.post(url, headers=self._headers(), data=json.dumps(payload), timeout=self.timeout)
except Exception as e:
return {"error": {"message": str(e), "type": "network_error"}}
try:
return resp.json()
except Exception:
return {"status": resp.status_code, "text": resp.text}
def chat_completions(
client: RahyanaClient,
*,
model: str,
messages: List[Dict[str, Any]],
max_tokens: Optional[int] = None,
temperature: Optional[float] = None,
) -> Dict[str, Any]:
payload: Dict[str, Any] = {"model": model, "messages": messages}
if max_tokens is not None:
payload["max_tokens"] = max_tokens
if temperature is not None:
payload["temperature"] = temperature
return client.post_json("chat/completions", payload)