Team Ai
Apppublic

hong-red/sql-optimization-agent

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
sql_agent.py80 linesDownload Raw Back to root
1import requests2import json3import os4import config5 6# --- 使用 config.py 中的统一配置 ---7KIMI_API_KEY = config.KIMI_API_KEY8BASE_URL = config.BASE_URL9MODEL = config.MODEL10SYSTEM_PROMPT = config.SYSTEM_PROMPT11 12def ask_kimi(messages, temperature=0.3, max_tokens=2048):13    """通过 requests 直接调用 Kimi API"""14    headers = {15        "Content-Type": "application/json",16        "Authorization": f"Bearer {KIMI_API_KEY}"17    }18    19    payload = {20        "model": MODEL,21        "messages": messages,22        "temperature": temperature,23        "max_tokens": max_tokens24    }25    26    # 禁用代理并禁用 SSL 验证以应对特定网络环境27    proxies = {"http": None, "https": None}28    try:29        response = requests.post(BASE_URL, headers=headers, json=payload, verify=False, proxies=proxies, timeout=60)30        31        if response.status_code == 200:32            result = response.json()33            return result["choices"][0]["message"]["content"].strip()34        else:35            # 输出更详细的错误信息36            error_details = response.text37            raise Exception(f"API 请求失败 (状态码 {response.status_code}): {error_details}")38    except requests.exceptions.RequestException as e:39        raise Exception(f"网络连接异常: {str(e)}")40 41def run_agent():42    messages = [{"role": "system", "content": SYSTEM_PROMPT}]43    print("智能体已启动!输入 '退出' 结束。\n")44 45    while True:46        try:47            user_input = input("你: ")48        except EOFError:49            break50            51        if user_input.strip().lower() in ["退出", "exit", "q"]:52            break53 54        messages.append({"role": "user", "content": user_input})55 56        # 思考 + 回复57        print("思考中...\n")58        try:59            reply = ask_kimi(messages)60            print("智能体:", reply)61            print("-" * 60)62            messages.append({"role": "assistant", "content": reply})63        except Exception as e:64            print(f"发生错误: {e}")65            break66 67if __name__ == "__main__":68    # 先运行一个简单的测试69    print("正在测试 API 连接...")70    try:71        # 简单回复测试72        test_msg = [{"role": "user", "content": "你好,请用一句话介绍自己"}]73        test_reply = ask_kimi(test_msg)74        print(f"API 测试成功!Kimi 回复: {test_reply}\n")75        76        # 启动 Agent77        run_agent()78    except Exception as e:79        print(f"API 测试失败: {e}")80