Skip to content

Commit 420f278

Browse files
committed
Refactor ask2api to use Config dataclass for API configuration
- Introduced a `Config` dataclass to manage API settings, including base URL, model, and temperature. - Updated the main function to retrieve configuration from environment variables using the new dataclass. - Replaced hardcoded values with dataclass attributes for improved maintainability and flexibility.
1 parent df7eff7 commit 420f278

File tree

1 file changed

+37
-5
lines changed

1 file changed

+37
-5
lines changed

ask2api.py

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,36 @@
66
import requests
77
from importlib.metadata import version, PackageNotFoundError
88
from urllib.parse import urlparse
9+
from dataclasses import dataclass
910

1011
API_KEY = os.getenv("OPENAI_API_KEY")
11-
OPENAI_URL = "https://api.openai.com/v1/chat/completions"
12+
ENV_VAR_PREFIX = "ASK2API_"
13+
14+
15+
@dataclass
16+
class Config:
17+
base_url: str = "https://api.openai.com/v1"
18+
model: str = "gpt-4.1"
19+
temperature: float = 0
20+
21+
def __post_init__(self):
22+
self.openai_url = f"{self.base_url}/chat/completions"
23+
24+
@classmethod
25+
def from_env(cls, prefix: str = ENV_VAR_PREFIX):
26+
"""Get the configuration from the environment variables."""
27+
return cls(
28+
**dict(
29+
filter(
30+
lambda x: x[1] is not None,
31+
dict(
32+
base_url=os.getenv(f"{prefix}BASE_URL"),
33+
model=os.getenv(f"{prefix}MODEL"),
34+
temperature=os.getenv(f"{prefix}TEMPERATURE"),
35+
).items(),
36+
),
37+
)
38+
)
1239

1340

1441
def is_url(path):
@@ -97,8 +124,10 @@ def main():
97124
# Text-only content
98125
user_content = args.prompt
99126

127+
config = Config.from_env()
128+
100129
payload = {
101-
"model": "gpt-4.1",
130+
"model": config.model,
102131
"messages": [
103132
{"role": "system", "content": system_prompt},
104133
{"role": "user", "content": user_content},
@@ -107,12 +136,15 @@ def main():
107136
"type": "json_schema",
108137
"json_schema": {"name": "ask2api_schema", "schema": schema},
109138
},
110-
"temperature": 0,
139+
"temperature": config.temperature,
111140
}
112141

113-
headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}
142+
headers = {
143+
"Authorization": f"Bearer {API_KEY}",
144+
"Content-Type": "application/json",
145+
}
114146

115-
r = requests.post(OPENAI_URL, headers=headers, json=payload)
147+
r = requests.post(config.openai_url, headers=headers, json=payload)
116148
r.raise_for_status()
117149

118150
result = r.json()["choices"][0]["message"]["content"]

0 commit comments

Comments
 (0)