-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconverter.py
More file actions
106 lines (88 loc) · 2.74 KB
/
converter.py
File metadata and controls
106 lines (88 loc) · 2.74 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
"""
Message converter for OpenAI format to Cursor Agent prompt
"""
from typing import List, Dict, Any
def messages_to_prompt(messages: List[Dict[str, Any]]) -> str:
"""
Convert OpenAI-style messages array to a single prompt string.
Example:
[
{"role": "system", "content": "You are helpful"},
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hi there!"},
{"role": "user", "content": "How are you?"}
]
->
"System: You are helpful
User: Hello
Assistant: Hi there!
User: How are you?"
"""
if not messages:
return ""
# If only one user message, return content directly
if len(messages) == 1 and messages[0].get("role") == "user":
return messages[0].get("content", "")
parts = []
for msg in messages:
role = msg.get("role", "user")
content = msg.get("content", "")
if role == "system":
parts.append(f"System: {content}")
elif role == "user":
parts.append(f"User: {content}")
elif role == "assistant":
parts.append(f"Assistant: {content}")
else:
parts.append(f"{role.capitalize()}: {content}")
return "\n\n".join(parts)
def cursor_response_to_openai(
cursor_result: Dict[str, Any],
model: str,
request_id: str = None
) -> Dict[str, Any]:
"""
Convert Cursor Agent JSON response to OpenAI-compatible format.
Cursor response:
{
"type": "result",
"subtype": "success",
"result": "Hello!",
"session_id": "...",
"request_id": "..."
}
OpenAI response:
{
"id": "chatcmpl-xxx",
"object": "chat.completion",
"model": "sonnet-4.5",
"choices": [{"message": {"role": "assistant", "content": "Hello!"}}],
"usage": {...}
}
"""
import time
content = cursor_result.get("result", "")
is_error = cursor_result.get("is_error", False)
if is_error:
content = f"Error: {content}"
return {
"id": f"chatcmpl-{request_id or cursor_result.get('request_id', 'unknown')}",
"object": "chat.completion",
"created": int(time.time()),
"model": model,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": content
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 0,
"completion_tokens": 0,
"total_tokens": 0
}
}