This repository was archived by the owner on Jan 11, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
198 lines (180 loc) · 7.72 KB
/
main.py
File metadata and controls
198 lines (180 loc) · 7.72 KB
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
import uuid
import requests
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
import time
# =============================================================================
# 与 Intercom 系统交互的工具函数和常量
# =============================================================================
BASE_URL = "https://api-iam.intercom.io/messenger/web"
APP_ID = "dgkjq2bp"
HEADERS = {
"Accept": "*/*",
"Content-Type": "application/x-www-form-urlencoded",
"Sec-Fetch-Site": "cross-site",
"Origin": "https://help.openai.com",
"Sec-Fetch-Dest": "empty",
"Accept-Language": "zh-CN,zh-Hans;q=0.9",
"Sec-Fetch-Mode": "cors",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.3.1 Safari/605.1.15",
"Accept-Encoding": "gzip, deflate, br",
"Priority": "u=3, i"
}
def create_conversation() -> str:
"""
这里固定返回一个会话ID作为示例
"""
return "43647711255654"
def send_message(conversation_id: str, message_text: str) -> None:
"""
使用 send_message 发送消息到指定会话
"""
url = f"{BASE_URL}/conversations/{conversation_id}/reply"
payload = {
"app_id": APP_ID,
"v": "3",
"g": "8483918bd87cc2b087d33bca7e7901b1fa0ee380",
"s": "768d9f62-69c2-46b3-98ec-b111883bd0fa",
"r": "",
"platform": "web",
"installation_type": "js-snippet",
"Idempotency-Key": str(uuid.uuid4()),
"internal": "",
"is_intersection_booted": "false",
"page_title": "OpenAI Help Center",
"user_active_company_id": "-1",
"user_data": '{"anonymous_id":"454d0766-2545-4311-b0a6-daa3e9e84692"}',
"created_at": "Sat Apr 05 2025 16:01:54 GMT+0800 (中国标准时间)",
"self_serve_suggestions_match": "false",
"client_assigned_uuid": "3e30b452-af46-417e-9575-24282e96d873",
"email": "111@111.com",
"blocks": message_text, # 消息内容
"last_admin_part_created_at": "2025-04-05T08:00:13.000Z",
"last_admin_part_id": "22052955995",
"last_admin_part_client_uuid": "null",
"part_ids": "message-workflow-intro-0,2798205033,22052955995,",
"nexus_connection_status": '{"connectionState":"connected","lastMessageType":"ACK","lastMessageReceivedAt":1743840114076,"lastNewCommentReceivedAt":0,"globalConnectionState":"connected"}',
"referer": "https://help.openai.com/en/",
"device_identifier": "cc1a6cc8-93d5-4283-af07-a0eaf23f20a5",
}
response = requests.post(url, headers=HEADERS, data=payload)
if response.status_code == 200:
print(f"消息发送成功!内容: {message_text}")
else:
print(f"消息发送失败!状态码: {response.status_code}, 响应: {response.text}")
def get_conversation_messages(conversation_id: str) -> List[dict]:
"""
获取指定会话的消息列表
"""
url = f"{BASE_URL}/conversations/{conversation_id}"
payload = {
"app_id": APP_ID,
"v": "3",
"g": "8483918bd87cc2b087d33bca7e7901b1fa0ee380",
"s": "768d9f62-69c2-46b3-98ec-b111883bd0fa",
"r": "",
"platform": "web",
"installation_type": "js-snippet",
"Idempotency-Key": str(uuid.uuid4()),
"internal": "",
"is_intersection_booted": "false",
"page_title": "OpenAI Help Center",
"user_active_company_id": "-1",
"user_data": '{"anonymous_id":"454d0766-2545-4311-b0a6-daa3e9e84692"}',
"self_serve_suggestions_match": "true",
"request_origin": "Conversation visibility/focus change",
"referer": "https://help.openai.com/en/",
"device_identifier": "cc1a6cc8-93d5-4283-af07-a0eaf23f20a5"
}
response = requests.post(url, headers=HEADERS, data=payload)
if response.status_code == 200:
data = response.json()
messages = data.get("conversation_parts", [])
return messages
else:
print(f"获取消息失败!状态码: {response.status_code}, 响应: {response.text}")
return []
# =============================================================================
# FastAPI 接口部分(模拟 OpenAI /v1/chat/completions 接口)
# =============================================================================
app = FastAPI()
# 请求体定义(参考 OpenAI 接口输入格式,但实际依据会话消息进行交互)
class ChatMessage(BaseModel):
role: str
content: str
class ChatCompletionRequest(BaseModel):
model: str
messages: List[ChatMessage]
conversation_id: Optional[str] = None
@app.post("/v1/chat/completions")
async def chat_completions(request: ChatCompletionRequest):
"""
模拟 OpenAI chat completions 接口:
1. 必须包含一条 user 消息,先调用 send_message 发送此消息。
2. 然后轮询获取会话消息,查找该消息后所有管理员的回复,作为 AI 回复返回。
"""
if not request.messages or not any(m.role == "user" for m in request.messages):
raise HTTPException(status_code=400, detail="请求消息中必须包含至少一条 user 消息。")
# 选择最新的 user 消息进行发送
user_message = [m for m in request.messages if m.role == "user"][-1].content
# 获取或创建会话ID
conversation_id = request.conversation_id or create_conversation()
# 先调用 send_message 发送用户消息
user_payload = '[{"type":"paragraph","text":"' + user_message + '"}]'
send_message(conversation_id, user_payload)
# 轮询等待会话中出现管理员回复
initial_messages = get_conversation_messages(conversation_id)
messages = initial_messages
timeout = 30 # 设置超时时间,避免无限循环
start_time = time.time()
while messages == initial_messages:
time.sleep(1) # 每秒轮询一次
messages = get_conversation_messages(conversation_id)
if time.time() - start_time > timeout:
break
# 查找最新的用户消息在消息队列中的位置
latest_user_index = None
for idx, msg in enumerate(messages):
if not msg.get("author", {}).get("is_admin"):
latest_user_index = idx
if latest_user_index is None:
raise HTTPException(status_code=400, detail="未找到用户消息。")
# 收集最新用户消息之后的所有管理员的回复
ai_response_parts = []
for msg in messages[latest_user_index + 1:]:
if msg.get("author", {}).get("is_admin"):
blocks = msg.get("blocks", [])
if not blocks:
continue
text = blocks[0].get("text", "")
if text:
ai_response_parts.append(text)
ai_response = "\n".join(ai_response_parts) if ai_response_parts else "暂无回复。"
messages.append({"role": "assistant", "content": ai_response})
# 构造返回格式,符合 OpenAI 标准
response_payload = {
"id": str(uuid.uuid4()),
"object": "chat.completion",
"created": int(uuid.uuid1().time / 1e7),
"model": request.model,
"choices": [
{
"index": 0,
"message": messages,
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": len(user_message),
"completion_tokens": len(ai_response),
"total_tokens": len(user_message) + len(ai_response)
}
}
return response_payload
# =============================================================================
# 运行 FastAPI 应用
# =============================================================================
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)