环境:
Ubuntu20.04
问题描述:
如何统一从一个共享的配置文件(比如 config.yaml 和 config.py)加载配置信息,避免硬编码?
解决方案:
希望本地模型和线上模型两块代码完全分开,但它们都统一从一个**共享的配置文件(比如 config.yaml
和 config.py
)**加载配置信息,避免硬编码。
提供三份文件示范:
config/config.yaml
:统一配置文件config/config.py
:统一读取配置并做环境变量覆盖local_model.py
:独立文件,调用本地模型,配置从config
读取online_model.py
:独立文件,调用线上模型,配置从config
读取
1. core/server/config/config.yaml
# 线上模型配置
api_key: "d3112f3e479"
base_url: "https://ark.cn-beijing.volces.com/api/v3"
model_name: "ep-20250602174215-fw5hx"
# 本地模型配置
local_model_api: "http://192.168.1.9:11434/v1/chat/completions"
local_model_name: "qwen2.5-3bnsfwny"
local_model_max_tokens: 512
local_model_temperature: 0.25
local_model_timeout: 10
2. core/server/config/config.py
import os
import yaml
CONFIG_PATH = os.path.join(os.path.dirname(__file__), "config.yaml")
class Config:
def __init__(self):
with open(CONFIG_PATH, "r", encoding="utf-8") as f:
data = yaml.safe_load(f)
for k, v in data.items():
env_val = os.getenv(k.upper())
setattr(self, k, env_val if env_val is not None else v)
config = Config()
3. local_model.py
import requests
from loguru import logger
from typing import Optional
import time
from core.server.config.config import config # 根据你的实际包结构调整导入路径
def summarize_with_model(text: str) -> Optional[str]:
headers = {"Content-Type": "application/json"}
payload = {
"model": config.local_model_name,
"messages": [{"role": "user", "content": text}],
"max_tokens": int(config.local_model_max_tokens),
"temperature": float(config.local_model_temperature),
"stream": False
}
try:
logger.info("调用本地大模型接口,准备发送请求")
start_time = time.time()
r = requests.post(config.local_model_api, headers=headers, json=payload, timeout=int(config.local_model_timeout))
r.raise_for_status()
logger.info(f"接口响应状态码:{r.status_code},耗时:{time.time() - start_time:.2f}秒")
resp_json = r.json()
content = resp_json.get("choices", [{}])[0].get("message", {}).get("content")
logger.info(f"模型返回内容长度:{len(content) if content else 0}")
logger.info(f"模型返回具体内容:{content}")
return content
except requests.exceptions.Timeout:
logger.error("调用本地大模型失败: 请求超时")
return None
except Exception as e:
logger.error(f"调用本地大模型失败: {e}")
return None
if __name__ == "__main__":
test_text = "请帮我总结一下这段文字的内容。"
logger.info("=== 测试本地模型 ===")
result = summarize_with_model(test_text)
logger.info(f"本地模型返回结果:{result}")
4. online_model.py
from openai import OpenAI
from loguru import logger
from typing import Optional
from core.server.config.config import config # 根据你的实际包结构调整导入路径
client = OpenAI(
api_key=config.api_key,
base_url=config.base_url,
)
def summarize_with_model(text: str) -> Optional[str]:
try:
logger.info("调用线上DeepSeek模型接口,准备发送请求")
messages = [
{"role": "system", "content": ""},
{"role": "user", "content": text},
]
completion = client.chat.completions.create(
model=config.model_name,
messages=messages,
stream=False
)
content = completion.choices[0].message.content
logger.info(f"线上模型返回内容长度:{len(content) if content else 0}")
logger.info(f"线上模型返回内容:{content}")
return content
except Exception as e:
logger.error(f"调用线上模型失败: {e}")
return None
if __name__ == "__main__":
test_text = "请帮我总结一下这段文字的内容。"
logger.info("=== 测试线上模型 ===")
result = summarize_with_model(test_text)
logger.info(f"线上模型返回结果:{result}")
5. 包结构示例及运行说明
core\
server\
config\
__init__.py
config.py
config.yaml
modules\
llm\
__init__.py
local_model.py
online_model.py
config
、modules
、llm
目录都加空的__init__.py
,使其成为包。- 在项目根目录执行:
python -m core.server.modules.llm.local_model
python -m core.server.modules.llm.online_model
确保Python可以正确解析包路径。
6. 说明
- 配置集中统一,方便维护,避免魔法数字和字符串散落代码。
- 代码完全分开,互不影响,且都共享同一配置,便于管理。
- 方便后续增加环境变量覆盖或动态配置读取。