File size: 6,578 Bytes
d8229c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#!/usr/bin/env python3
"""
Test OpenAI integration
"""

import os
import json
from openai import OpenAI


def test_openai_connection():
    """Test basic OpenAI connection"""
    api_key = os.getenv("OPENAI_API_KEY")
    base_url = os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1")
    
    if not api_key:
        print("❌ 请先设置 OPENAI_API_KEY 环境变量")
        print("   export OPENAI_API_KEY=your_api_key_here")
        return False
    
    try:
        client = OpenAI(
            api_key=api_key,
            base_url=base_url
        )
        
        print(f"🔗 连接到: {base_url}")
        print(f"🔑 API Key: {api_key[:4]}...{api_key[-4:]}")
        
        # 测试简单的聊天完成
        response = client.chat.completions.create(
            model=os.getenv("OPENAI_MODEL", "gpt-4o-mini"),
            messages=[
                {"role": "user", "content": "Hello! Please respond with just 'OK' to confirm the connection."}
            ],
            max_tokens=10,
            temperature=0
        )
        
        result = response.choices[0].message.content.strip()
        print(f"✅ 连接成功! 响应: {result}")
        
        return True
        
    except Exception as e:
        print(f"❌ 连接失败: {e}")
        return False


def test_scoring_function():
    """Test the scoring functionality similar to what's used in app.py"""
    api_key = os.getenv("OPENAI_API_KEY")
    
    if not api_key:
        print("❌ 请先设置 OPENAI_API_KEY 环境变量")
        return False
    
    try:
        client = OpenAI(
            api_key=api_key,
            base_url=os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1")
        )
        
        # 测试数据,类似app.py中的格式
        test_challenges = [
            {
                "id": "test1",
                "title": "Build a Python Web API",
                "prize": 500.0,
                "deadline": "2025-02-15",
                "tags": ["python", "api", "web"],
                "description": "Create a REST API using Python and FastAPI framework"
            },
            {
                "id": "test2", 
                "title": "React Frontend Development",
                "prize": 300.0,
                "deadline": "2025-02-20",
                "tags": ["react", "frontend", "javascript"],
                "description": "Build a modern React application with responsive design"
            }
        ]
        
        scoring_prompt = (
            "You are an expert Topcoder challenge analyst. Analyze items and rate match to the query.\n"
            f"Query: python web development\n"
            "Items: " + json.dumps(test_challenges) + "\n\n"
            "Instructions:\n"
            "- Consider skills, tags, and brief description.\n"
            "- Higher prize is slightly better all else equal.\n"
            "- Return ONLY JSON array of objects: [{id, score, reason}] where 0<=score<=1.\n"
            "- Do not include any extra text."
        )
        
        print("🧪 测试智能评分功能...")
        
        response = client.chat.completions.create(
            model=os.getenv("OPENAI_MODEL", "gpt-4o-mini"),
            messages=[
                {"role": "system", "content": "You are a helpful assistant. Return JSON only."},
                {"role": "user", "content": scoring_prompt}
            ],
            temperature=0.2,
            timeout=30
        )
        
        result = response.choices[0].message.content.strip()
        print(f"📊 评分结果: {result}")
        
        # 尝试解析JSON
        try:
            scores = json.loads(result)
            print("✅ JSON解析成功!")
            for item in scores:
                print(f"   - {item.get('id')}: 分数={item.get('score')}, 原因={item.get('reason')}")
            return True
        except json.JSONDecodeError as e:
            print(f"❌ JSON解析失败: {e}")
            return False
            
    except Exception as e:
        print(f"❌ 评分测试失败: {e}")
        return False


def test_planning_function():
    """Test the planning functionality"""
    api_key = os.getenv("OPENAI_API_KEY")
    
    if not api_key:
        print("❌ 请先设置 OPENAI_API_KEY 环境变量")
        return False
    
    try:
        client = OpenAI(
            api_key=api_key,
            base_url=os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1")
        )
        
        # 测试数据
        test_challenges = [
            {
                "title": "Build a Python Web API",
                "prize": 500.0,
                "deadline": "2025-02-15",
                "tags": ["python", "api", "web"]
            }
        ]
        
        prompt = (
            "You are a concise challenge scout. Given compact challenge metadata, output:\n"
            "- Top 3 picks (title + brief reason)\n"
            "- Quick plan of action (3 bullets)\n"
            f"Constraints: keyword='python', min_prize>=100, within 30 days.\n"
            f"Data: {json.dumps(test_challenges)}"
        )
        
        print("📋 测试计划生成功能...")
        
        response = client.chat.completions.create(
            model=os.getenv("OPENAI_MODEL", "gpt-4o-mini"),
            messages=[
                {"role": "system", "content": "You are a helpful, terse assistant."},
                {"role": "user", "content": prompt}
            ],
            temperature=0.3,
            timeout=30
        )
        
        result = response.choices[0].message.content.strip()
        print(f"📝 计划结果:\n{result}")
        print("✅ 计划生成成功!")
        
        return True
        
    except Exception as e:
        print(f"❌ 计划测试失败: {e}")
        return False


def main():
    print("🤖 OpenAI API 集成测试")
    print("=" * 40)
    
    # 测试基本连接
    if not test_openai_connection():
        print("\n❌ 基本连接测试失败,请检查配置")
        return
    
    print("\n" + "-" * 40)
    
    # 测试评分功能
    if not test_scoring_function():
        print("❌ 评分功能测试失败")
        return
    
    print("\n" + "-" * 40)
    
    # 测试计划功能
    if not test_planning_function():
        print("❌ 计划功能测试失败")
        return
    
    print("\n" + "=" * 40)
    print("🎉 所有测试通过! OpenAI集成工作正常")
    print("现在可以运行主应用: python app.py")
    print("=" * 40)


if __name__ == "__main__":
    main()