-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllm_utils.py
More file actions
59 lines (48 loc) · 2.43 KB
/
Copy pathllm_utils.py
File metadata and controls
59 lines (48 loc) · 2.43 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
51
52
53
54
55
56
57
58
59
# Copyright (c) 2019-2020, INESC TEC (https://www.inesctec.pt)
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from datetime import datetime
import requests, time, urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
import warnings
warnings.filterwarnings("ignore")
def call_llm(prompt,role="Actor", temperature=0, model="gpt-5.4", retries=2, sleep_time=2):
"""
Unified LLM caller for local/org deployment (plain text output).
Handles retries and logging, but does NOT require JSON.
"""
API_KEY = 'Replace your OPENAI API_key'
API_URL = "https://api.openai.com/v1/chat/completions"
organization_ID= "Replace your Organization ID in OPEN AI (if applicable)"
for attempt in range(retries):
timestamp = datetime.now().strftime("%H:%M:%S")
print(f"\n[{timestamp}] 🧠 [{role}] Attempt {attempt+1}/{retries} — model={model}")
# Compose system+user messages
messages = [
{
"role": "system",
"content": (
"You are a power system reasoning assistant. "
"Respond in clear, structured, and concise text. "
"Do NOT produce JSON."
),
},
{"role": "user", "content": prompt},
]
payload = {"model": model, "messages": messages, "temperature": temperature, "stream": False}
headers = {"Authorization": f"Bearer {API_KEY}", "OpenAI-Organization": organization_ID,"Content-Type": "application/json"}
try:
response = requests.post(API_URL, headers=headers, json=payload, verify=False, timeout=180)
response.raise_for_status()
data = response.json()
text = data["choices"][0]["message"]["content"].strip()
print(f"📤 [{role}] Response preview:\n{text[:400]}{'...' if len(text) > 400 else ''}")
return text
except Exception as e:
print(f"⚠️ [{role}] Error: {e}")
if attempt < retries - 1:
print(f"🔁 [{role}] Retrying after {sleep_time}s...")
time.sleep(sleep_time)
else:
raise RuntimeError(f"❌ [{role}] Failed after {retries} attempts: {e}")