lihubot commited on
Commit
0c19e48
·
verified ·
1 Parent(s): 9c8321c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -21
app.py CHANGED
@@ -3,7 +3,8 @@ import subprocess
3
  import json
4
  import logging
5
  import sys
6
- import requests
 
7
  from flask import Flask
8
 
9
  # 配置日志
@@ -18,29 +19,44 @@ CONFIG_FILE = os.path.join(LOCAL_DIR, "openclaw.json")
18
 
19
  app = Flask(__name__)
20
 
21
- # --- 第一步:Python 原生测试 (基准测试) ---
22
  def test_google_openai_compatibility():
23
- logger.info("🧪 [Test] 正在使用 Python 直接测试 Google OpenAI 兼容接口...")
24
 
25
  url = "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions"
 
26
  headers = {
27
  "Content-Type": "application/json",
28
  "Authorization": f"Bearer {GOOGLE_API_KEY}"
29
  }
 
30
  data = {
31
  "model": "gemini-1.5-flash",
32
- "messages": [{"role": "user", "content": "Hello, are you working?"}],
33
  "max_tokens": 10
34
  }
35
 
36
  try:
37
- response = requests.post(url, headers=headers, json=data, timeout=10)
38
- if response.status_code == 200:
39
- logger.info(f"✅ [Test] Python 测试成功! 响应: {response.json()['choices'][0]['message']['content']}")
 
 
 
 
 
 
 
 
 
 
 
40
  return True
41
- else:
42
- logger.error(f"❌ [Test] Python 测试失败: {response.status_code} - {response.text}")
43
- return False
 
 
44
  except Exception as e:
45
  logger.error(f"❌ [Test] 连接异常: {e}")
46
  return False
@@ -49,15 +65,13 @@ def test_google_openai_compatibility():
49
  def generate_minimal_config():
50
  if not os.path.exists(LOCAL_DIR): os.makedirs(LOCAL_DIR)
51
 
52
- # 我们直接复用 "openai" 这个 Provider ID,因为它是内置支持最好的
53
- # 我们只覆盖它的 baseUrl
54
  config = {
55
  "models": {
56
  "providers": {
57
- "openai": { # <--- 直接用 openai,别起名字叫 gemini_proxy 了,防止触发校验错误
58
- "baseUrl": "https://generativelanguage.googleapis.com/v1beta/openai", # 注意:不带 /v1,OpenClaw 会自动补
59
  "apiKey": GOOGLE_API_KEY,
60
- # 显式声明模型,防止它去 OpenAI 官网拉列表
61
  "models": [
62
  { "id": "gemini-1.5-flash", "name": "Gemini Flash" }
63
  ]
@@ -71,7 +85,7 @@ def generate_minimal_config():
71
  },
72
  "gateway": {
73
  "mode": "local",
74
- "auth": { "token": "test" } # 随便填,反正我们看日志
75
  }
76
  }
77
 
@@ -79,7 +93,6 @@ def generate_minimal_config():
79
  json.dump(config, f, indent=2)
80
  logger.info(f"✅ [System] 极简配置已生成")
81
 
82
- # 确保权限正确
83
  try:
84
  os.chmod(LOCAL_DIR, 0o700)
85
  os.chmod(CONFIG_FILE, 0o600)
@@ -107,11 +120,8 @@ if __name__ == "__main__":
107
  # 这会打印出所有发出的请求头、URL 和响应
108
  env["NODE_DEBUG"] = "https"
109
 
110
- # 也可以开启 OpenClaw 自身的调试
111
- env["DEBUG"] = "openclaw:*"
112
-
113
  # 注入 Key
114
- env["OPENAI_API_KEY"] = GOOGLE_API_KEY # 既然用了 openai provider,它可能会读这个变量
115
 
116
  # 启动!
117
  process = subprocess.Popen(
 
3
  import json
4
  import logging
5
  import sys
6
+ import urllib.request
7
+ import urllib.error
8
  from flask import Flask
9
 
10
  # 配置日志
 
19
 
20
  app = Flask(__name__)
21
 
22
+ # --- 第一步:Python 原生测试 (使用标准库 urllib) ---
23
  def test_google_openai_compatibility():
24
+ logger.info("🧪 [Test] 正在使用 Python (urllib) 测试 Google OpenAI 兼容接口...")
25
 
26
  url = "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions"
27
+
28
  headers = {
29
  "Content-Type": "application/json",
30
  "Authorization": f"Bearer {GOOGLE_API_KEY}"
31
  }
32
+
33
  data = {
34
  "model": "gemini-1.5-flash",
35
+ "messages": [{"role": "user", "content": "Hello, simply reply 'OK'."}],
36
  "max_tokens": 10
37
  }
38
 
39
  try:
40
+ # 构造请求
41
+ req = urllib.request.Request(
42
+ url,
43
+ data=json.dumps(data).encode('utf-8'),
44
+ headers=headers,
45
+ method='POST'
46
+ )
47
+
48
+ # 发送请求
49
+ with urllib.request.urlopen(req, timeout=10) as response:
50
+ response_body = response.read().decode('utf-8')
51
+ result = json.loads(response_body)
52
+ content = result['choices'][0]['message']['content']
53
+ logger.info(f"✅ [Test] Python 测试成功! Gemini 回复: {content}")
54
  return True
55
+
56
+ except urllib.error.HTTPError as e:
57
+ error_body = e.read().decode('utf-8')
58
+ logger.error(f"❌ [Test] Python 测试失败 (HTTP {e.code}): {error_body}")
59
+ return False
60
  except Exception as e:
61
  logger.error(f"❌ [Test] 连接异常: {e}")
62
  return False
 
65
  def generate_minimal_config():
66
  if not os.path.exists(LOCAL_DIR): os.makedirs(LOCAL_DIR)
67
 
68
+ # 我们直接复用 "openai" 这个 Provider ID
 
69
  config = {
70
  "models": {
71
  "providers": {
72
+ "openai": {
73
+ "baseUrl": "https://generativelanguage.googleapis.com/v1beta/openai", # OpenClaw 会自动补 /chat/completions
74
  "apiKey": GOOGLE_API_KEY,
 
75
  "models": [
76
  { "id": "gemini-1.5-flash", "name": "Gemini Flash" }
77
  ]
 
85
  },
86
  "gateway": {
87
  "mode": "local",
88
+ "auth": { "token": "test" }
89
  }
90
  }
91
 
 
93
  json.dump(config, f, indent=2)
94
  logger.info(f"✅ [System] 极简配置已生成")
95
 
 
96
  try:
97
  os.chmod(LOCAL_DIR, 0o700)
98
  os.chmod(CONFIG_FILE, 0o600)
 
120
  # 这会打印出所有发出的请求头、URL 和响应
121
  env["NODE_DEBUG"] = "https"
122
 
 
 
 
123
  # 注入 Key
124
+ env["OPENAI_API_KEY"] = GOOGLE_API_KEY
125
 
126
  # 启动!
127
  process = subprocess.Popen(