-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathapp.py
More file actions
306 lines (276 loc) · 11.1 KB
/
app.py
File metadata and controls
306 lines (276 loc) · 11.1 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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import copy
import json
import os
from typing import Any, AsyncIterator, Awaitable, Callable
import httpx
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, StreamingResponse
from parser_control import (
Parser,
build_tool_parser,
)
from regex_replacement import (
apply_replacement_to_messages,
apply_replacement_to_prompt,
)
app = FastAPI(title="Native Tool Call Adapter for Cline/Roo-Code")
TARGET_BASE_URL = os.getenv("TARGET_BASE_URL", "https://api.openai.com/v1")
MESSAGE_DUMP_PATH = os.getenv("MESSAGE_DUMP_PATH")
TOOL_DUMP_PATH = os.getenv("TOOL_DUMP_PATH")
DISABLE_STRICT_SCHEMAS = bool(os.getenv("DISABLE_STRICT_SCHEMAS"))
FORCE_TOOL_CALLING = os.getenv("FORCE_TOOL_CALLING")
def process_request(
request: dict[str, Any],
) -> tuple[dict[str, Any], Parser, Callable[[str], str]]:
request = copy.deepcopy(request)
if request["messages"] and request["messages"][0]["role"] in ["system", "user"]:
system_prompt = request["messages"][0]["content"]
if isinstance(system_prompt, list):
system_prompt = "\n".join(
[
str(t["text"])
for t in system_prompt
if isinstance(t, dict) and "text" in t
]
)
parser, processed_system_prompt = build_tool_parser(
system_prompt, not DISABLE_STRICT_SCHEMAS
)
request["messages"][0]["role"] = "system"
request["messages"][0]["content"] = processed_system_prompt
if parser.schemas:
request["tools"] = (request.get("tools") or []) + parser.schemas
messages, persistent_failure = parser.modify_xml_messages_to_tool_calls(
request["messages"]
)
if FORCE_TOOL_CALLING == "auto":
force_tool_calling = persistent_failure
else:
force_tool_calling = bool(FORCE_TOOL_CALLING)
if force_tool_calling and request.get("tools"):
request["tool_choice"] = "required"
request["messages"], apply_replacement_to_completion = (
apply_replacement_to_messages(messages)
)
if MESSAGE_DUMP_PATH:
with open(MESSAGE_DUMP_PATH, "w", encoding="utf-8") as f:
json.dump(request["messages"], f, ensure_ascii=False, indent=2)
if TOOL_DUMP_PATH:
with open(TOOL_DUMP_PATH, "w", encoding="utf-8") as f:
json.dump((request.get("tools") or "[]"), f, ensure_ascii=False, indent=2)
return request, parser, apply_replacement_to_completion
async def handle_stream_response(
response: httpx.Response,
parser: Parser,
apply_replacement_to_completion: Callable[[str], str],
is_disconnected: Callable[[], Awaitable[bool]],
) -> AsyncIterator[str]:
if response.is_error:
await response.aread()
yield f"data: {response.text}\n\n"
yield "data: [DONE]\n\n"
return
buffer = ""
last_chunk = None
role = None
choice_index = 0
tool_call_index = 0
tool_call_id = ""
tool_name = ""
reasoning_content_buffer = ""
async for line in response.aiter_lines():
if await is_disconnected():
return
if not line.startswith("data: "):
continue
def create_tool_call():
nonlocal buffer, tool_name, tool_call_id, reasoning_content_buffer
modified_data = parser.modify_tool_call_to_xml_message(
tool_name, buffer, tool_call_id, reasoning_content_buffer
)
modified_data = apply_replacement_to_completion(modified_data)
last_chunk["choices"][0]["delta"]["content"] = modified_data
buffer = ""
tool_name = ""
tool_call_id = ""
reasoning_content_buffer = ""
return f"data: {json.dumps(last_chunk, ensure_ascii=False)}\n\n"
if line.strip() == "data: [DONE]":
if buffer:
yield create_tool_call()
yield line + "\n\n"
continue
data = json.loads(line[6:].strip())
choice = (data.get("choices") or [{}])[0]
choice_index_of_delta = choice.get("index", choice_index)
delta = choice.get("delta") or {}
role_in_delta = delta.get("role", role)
tool_calls_in_delta = delta.get("tool_calls")
reasoning_content_buffer += delta.get("reasoning_content") or ""
if (
choice_index_of_delta != choice_index
or not delta
or role_in_delta != role
or not tool_calls_in_delta
) and buffer:
yield create_tool_call()
choice_index = choice_index_of_delta
role = role_in_delta
if role == "assistant":
tool_call = (tool_calls_in_delta or [{}])[0]
if tool_call.get("index") != tool_call_index and buffer:
yield create_tool_call()
if tool_call:
tool_name += tool_call.get("function").get("name", "")
buffer += tool_call.get("function").get("arguments", "")
tool_call_id += tool_call.get("id", "")
tool_call_index = tool_call.get("index", tool_call_index)
last_chunk = data
if data.get("finish_reason") and buffer:
yield create_tool_call()
if data.get("finish_reason") == "tool_calls":
data["finish_reason"] = "stop"
yield "data: " + json.dumps(data, ensure_ascii=False) + "\n\n"
@app.post("/v1/chat/completions")
async def create_completion(request: Request):
modified_request, parser, apply_replacement_to_completion = process_request(
await request.json()
)
headers = dict(request.headers)
if "host" in headers:
del headers["host"]
if "content-length" in headers:
del headers["content-length"]
stream = modified_request.get("stream")
if stream:
async def create_event_stream() -> AsyncIterator[str]:
async with httpx.AsyncClient(timeout=None) as client:
async with client.stream(
"POST",
f"{TARGET_BASE_URL}/chat/completions",
json=modified_request,
headers=headers,
params=request.query_params,
) as r:
async for iter in handle_stream_response(
r,
parser,
apply_replacement_to_completion,
request.is_disconnected,
):
yield iter
return StreamingResponse(create_event_stream(), media_type="text/event-stream")
else:
async with httpx.AsyncClient(timeout=None) as client:
r = await client.post(
f"{TARGET_BASE_URL}/chat/completions",
json=modified_request,
headers=headers,
params=request.query_params,
)
if r.is_error:
return JSONResponse(status_code=r.status_code, content=r.json())
modified_response = parser.modify_tool_calls_to_xml_messages(
r.json(), apply_replacement_to_completion
)
return JSONResponse(status_code=r.status_code, content=modified_response)
@app.get("/v1/models")
async def get_models(request: Request):
headers = dict(request.headers)
if "host" in headers:
del headers["host"]
if "content-length" in headers:
del headers["content-length"]
async with httpx.AsyncClient(timeout=None) as client:
r = await client.get(
f"{TARGET_BASE_URL}/models", headers=headers, params=request.query_params
)
return JSONResponse(status_code=r.status_code, content=r.json())
async def handle_stream_response_for_legacy_completion(
response: httpx.Response,
apply_replacement_to_completion: Callable[[str], str],
is_disconnected: Callable[[], Awaitable[bool]],
) -> AsyncIterator[str]:
if response.is_error:
await response.aread()
yield f"data: {response.text}\n\n"
yield "data: [DONE]\n\n"
return
buffer = ""
last_chunk = None
choice_index = 0
async for line in response.aiter_lines():
if await is_disconnected():
return
if not line.startswith("data: "):
continue
def create_tool_call():
nonlocal buffer
modified_data = apply_replacement_to_completion(buffer)
last_chunk["choices"][0]["text"] = modified_data
buffer = ""
return f"data: {json.dumps(last_chunk, ensure_ascii=False)}\n\n"
if line.strip() == "data: [DONE]":
if buffer:
yield create_tool_call()
yield line + "\n\n"
continue
data = json.loads(line[6:].strip())
choice = (data.get("choices") or [{}])[0]
text = choice.get("text") or ""
choice_index_of_delta = choice.get("index", choice_index)
if (not text or choice_index_of_delta != choice_index) and buffer:
yield create_tool_call()
choice_index = choice_index_of_delta
if text:
buffer += text
last_chunk = data
if data.get("finish_reason") and buffer:
yield create_tool_call()
choice["text"] = ""
yield "data: " + json.dumps(data, ensure_ascii=False) + "\n\n"
@app.post("/v1/completions")
async def create_legacy_completion(request: Request):
req = await request.json()
req["prompt"], apply_replacement_to_completion = apply_replacement_to_prompt(
req["prompt"]
)
if MESSAGE_DUMP_PATH:
with open(MESSAGE_DUMP_PATH, "w", encoding="utf-8") as f:
f.write(req["prompt"])
headers = dict(request.headers)
if "host" in headers:
del headers["host"]
if "content-length" in headers:
del headers["content-length"]
stream = req.get("stream")
if stream:
async def create_event_stream() -> AsyncIterator[str]:
async with httpx.AsyncClient(timeout=None) as client:
async with client.stream(
"POST",
f"{TARGET_BASE_URL}/completions",
json=req,
headers=headers,
params=request.query_params,
) as r:
async for iter in handle_stream_response_for_legacy_completion(
r, apply_replacement_to_completion, request.is_disconnected
):
yield iter
return StreamingResponse(create_event_stream(), media_type="text/event-stream")
else:
async with httpx.AsyncClient(timeout=None) as client:
r = await client.post(
f"{TARGET_BASE_URL}/completions",
json=req,
headers=headers,
params=request.query_params,
)
if r.is_error:
return JSONResponse(status_code=r.status_code, content=r.json())
response = r.json()
for choice in response.get("choices", []):
text = choice.get("text", "")
choice["text"] = apply_replacement_to_completion(text)
return JSONResponse(status_code=r.status_code, content=response)