返回 VideoClaw
llm_gpt.py
1 import os
2 import sys
3
4 models_dir = os.path.dirname(os.path.abspath(__file__))
5 backend_dir = os.path.dirname(models_dir)
6 if backend_dir not in sys.path:
7 sys.path.insert(0, backend_dir)
8
9 import time
10 import logging
11 from openai import OpenAI
12 from config import Config
13
14 logger = logging.getLogger(__name__)
15
16
17 class GPT:
18 """
19 OpenAI 文本生成客户端
20 可选模型:gpt-4o,
21 """
22 def __init__(self, base_url="", api_key="", proxy=None, timeout=300):
23 import httpx
24 self.api_key = api_key or Config.OPENAI_API_KEY
25 self.timeout = timeout
26
27 kwargs = {"api_key": self.api_key, "timeout": self.timeout}
28
29 self.base_url = base_url
30 if proxy is None:
31 proxy = Config.provider_proxy("openai")
32 if proxy:
33 kwargs["http_client"] = httpx.Client(
34 proxy=proxy,
35 timeout=self.timeout,
36 )
37 if self.base_url:
38 kwargs["base_url"] = self.base_url
39
40 self.client = OpenAI(**kwargs)
41 self.max_attempts = 10
42
43 def query(self, prompt, image_urls=[], model="", web_search=False):
44 self.model = model
45 if self.model == "":
46 self.model = "gpt-5"
47
48 # Switch to search model if web_search is enabled
49 # OpenAI uses gpt-4o-search-preview for web search
50 if web_search and not self.model.endswith("-search"):
51 search_model_map = {
52 "gpt-4o": "gpt-4o-search-preview",
53 "gpt-4": "gpt-4-search-preview",
54 "gpt-5": "gpt-5-search",
55 }
56 self.model = search_model_map.get(self.model, self.model + "-search")
57
58 messages = [{"role": "system", "content": "You are a helpful assistant."}]
59 content = [{"type": "text", "text": prompt}]
60 if image_urls:
61 content.extend([{"type": "image_url", "image_url": {"url": url}} for url in image_urls])
62 messages.append({"role": "user", "content": content})
63
64 attempts = 0
65 while attempts < self.max_attempts:
66 try:
67 # Build request parameters
68 request_params = {
69 "model": self.model,
70 "messages": messages,
71 }
72 # Add search tool if web_search is enabled
73 if web_search:
74 request_params["search_tool"] = "auto"
75
76 response = self.client.chat.completions.create(**request_params)
77 if response.choices[0].message.content.strip():
78 return response.choices[0].message.content
79 else:
80 logger.warning("OpenAI returned an empty response; retrying in 10 seconds")
81 except Exception as e:
82 logger.warning("OpenAI request failed; retrying in 10 seconds: %s", e)
83 logger.debug("OpenAI request messages: %s", messages)
84 time.sleep(10)
85 attempts += 1
86
87 raise Exception("Max attempts reached, failed to get a response from OpenAI.")
88
89
90 if __name__ == "__main__":
91 import sys
92 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
93 from config import Config
94
95 # 支持的模型列表
96 MODELS = ["gpt-4o", "gpt-5", "gpt-5.4"]
97
98 print("=== GPT 文本生成可用性测试 ===")
99 api_key = Config.OPENAI_API_KEY
100 base_url = Config.OPENAI_BASE_URL
101 if not api_key:
102 print("✗ OPENAI_API_KEY 未设置,跳过")
103 sys.exit(1)
104 print(f" API Key: {api_key[:6]}***{api_key[-4:]}")
105 print(f" Base URL: {base_url}")
106 client = GPT(api_key=api_key, base_url=base_url)
107
108 prompt = "用一句话介绍你自己。"
109 print(f" Prompt: {prompt}")
110
111 for model in MODELS:
112 print(f"\n--- 测试模型: {model} ---")
113 t0 = time.time()
114 try:
115 resp = client.query(prompt, model=model)
116 elapsed = time.time() - t0
117 print(f"✓ 响应 ({elapsed:.1f}s): {resp.strip()[:200]}")
118 except Exception as e:
119 print(f"✗ 失败: {e}")
120
120 lines PYTHON