Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

server.sh

417 lines10.6 KB

1#!/usr/bin/env bash
2​
3set -uo pipefail
4​
5PORT="${PORT:-8005}"
6SCRIPT_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/$(basename "${BASH_SOURCE[0]}")"
7DEFAULT_OPENAI_MODEL="gpt-4o"
8DEFAULT_ANTHROPIC_MODEL="claude-sonnet-4-6"
9​
10json_event() {
11 jq -nc "$@"
13​
14write_event() {
15 printf 'data: %s\n\n' "$1"
17​
18write_error_response() {
19 local status="$1"
20 local message="$2"
21 printf 'HTTP/1.1 %s\r\n' "$status"
22 printf 'Content-Type: text/plain; charset=utf-8\r\n'
23 printf 'Access-Control-Allow-Origin: *\r\n'
24 printf 'Connection: close\r\n'
25 printf '\r\n'
26 printf '%s' "$message"
28​
29normalize_messages() {
30 jq -c '
31 def message_text:
32 if (.parts? | type) == "array" then
33 [.parts[]? |
34 select(
35 type == "object" and
36 .type == "text" and
37 (.content | type) == "string"
38 ) |
39 .content
40 ] | join("")
41 elif (.content? | type) == "string" then
42 .content
43 elif (.content? | type) == "array" then
44 [.content[]? |
45 select(
46 type == "object" and
47 .type == "text" and
48 (.text | type) == "string"
49 ) |
50 .text
51 ] | join("")
52 else
53 ""
54 end;
55​
56 [.messages[]? |
57 select(type == "object") |
58 (if .role == "developer" then "system" else (.role // "") end) as $role |
59 message_text as $content |
60 select(
61 ($role == "system" or $role == "user" or $role == "assistant") and
62 ($content | length) > 0
63 ) |
64 { role: $role, content: $content }
65 ]
66 '
68​
69process_openai_stream() {
70 local message_id="$1"
71 local line data event
72​
73 while IFS= read -r line || [[ -n "$line" ]]; do
74 line="${line%$'\r'}"
75 [[ "$line" == "data: "* ]] || continue
76 data="${line#data: }"
77 [[ "$data" == "[DONE]" ]] && continue
78​
79 event="$(
80 jq -c --arg messageId "$message_id" '
81 .choices[0].delta.content? as $delta |
82 select(($delta | type) == "string" and ($delta | length) > 0) |
83 {
84 type: "TEXT_MESSAGE_CONTENT",
85 messageId: $messageId,
86 delta: $delta
87 }
88 ' <<<"$data" 2>/dev/null
89 )" || continue
90​
91 [[ -n "$event" ]] && write_event "$event"
92 done
94​
95process_anthropic_stream() {
96 local message_id="$1"
97 local line data event
98​
99 while IFS= read -r line || [[ -n "$line" ]]; do
100 line="${line%$'\r'}"
101 [[ "$line" == "data: "* ]] || continue
102 data="${line#data: }"
103​
104 event="$(
105 jq -c --arg messageId "$message_id" '
106 select(
107 .type == "content_block_delta" and
108 .delta.type == "text_delta" and
109 (.delta.text | type) == "string" and
110 (.delta.text | length) > 0
111 ) |
112 {
113 type: "TEXT_MESSAGE_CONTENT",
114 messageId: $messageId,
115 delta: .delta.text
116 }
117 ' <<<"$data" 2>/dev/null
118 )" || continue
119​
120 [[ -n "$event" ]] && write_event "$event"
121 done
123​
124stream_openai() {
125 local payload="$1"
126 local message_id="$2"
127​
128 curl --silent --show-error --no-buffer --fail \
129 https://api.openai.com/v1/chat/completions \
130 -H "Authorization: Bearer ${OPENAI_API_KEY}" \
131 -H 'Content-Type: application/json' \
132 --data-binary "$payload" |
133 process_openai_stream "$message_id"
134​
135 return "${PIPESTATUS[0]}"
137​
138stream_anthropic() {
139 local payload="$1"
140 local message_id="$2"
141​
142 curl --silent --show-error --no-buffer --fail \
143 https://api.anthropic.com/v1/messages \
144 -H "x-api-key: ${ANTHROPIC_API_KEY}" \
145 -H 'anthropic-version: 2023-06-01' \
146 -H 'Content-Type: application/json' \
147 --data-binary "$payload" |
148 process_anthropic_stream "$message_id"
149​
150 return "${PIPESTATUS[0]}"
152​
153handle_chat() {
154 local body="$1"
155 local thread_id run_id provider model normalized system chat message_id payload
156 local stream_status
157​
158 thread_id="$(jq -r 'if (.threadId? | type) == "string" then .threadId else "" end' <<<"$body")"
159 run_id="$(jq -r 'if (.runId? | type) == "string" then .runId else "" end' <<<"$body")"
160​
161 if [[ -z "$thread_id" || -z "$run_id" ]]; then
162 write_error_response '400 Bad Request' 'threadId and runId are required'
163 return
164 fi
165​
166 provider="$(
167 jq -r '
168 (.forwardedProps // .data // {}) as $props |
169 if ($props.provider? | type) == "string" and ($props.provider | length) > 0
170 then $props.provider
171 else "openai"
172 end
173 ' <<<"$body"
174 )"
175 model="$(
176 jq -r '
177 (.forwardedProps // .data // {}) as $props |
178 if ($props.model? | type) == "string" then $props.model else "" end
179 ' <<<"$body"
180 )"
181​
182 normalized="$(normalize_messages <<<"$body")"
183 system="$(
184 jq -r '[.[] | select(.role == "system") | .content] | join("\n\n")' \
185 <<<"$normalized"
186 )"
187 chat="$(jq -c '[.[] | select(.role == "user" or .role == "assistant")]' <<<"$normalized")"
188​
189 printf 'HTTP/1.1 200 OK\r\n'
190 printf 'Content-Type: text/event-stream\r\n'
191 printf 'Cache-Control: no-cache\r\n'
192 printf 'Connection: close\r\n'
193 printf 'Access-Control-Allow-Origin: *\r\n'
194 printf '\r\n'
195​
196 message_id="msg-${run_id}"
197 write_event "$(
198 json_event \
199 --arg threadId "$thread_id" \
200 --arg runId "$run_id" \
201 '{ type: "RUN_STARTED", threadId: $threadId, runId: $runId }'
202 )"
203​
204 if [[ "$(jq 'length' <<<"$chat")" -eq 0 ]]; then
205 write_event "$(
206 json_event \
207 --arg threadId "$thread_id" \
208 --arg runId "$run_id" \
209 --arg message 'no user or assistant messages to send' \
210 '{
211 type: "RUN_ERROR",
212 threadId: $threadId,
213 runId: $runId,
214 error: { message: $message }
215 }'
216 )"
217 return
218 fi
219​
220 write_event "$(
221 json_event \
222 --arg messageId "$message_id" \
223 '{ type: "TEXT_MESSAGE_START", messageId: $messageId, role: "assistant" }'
224 )"
225​
226 case "$provider" in
227 openai)
228 if [[ -z "${OPENAI_API_KEY:-}" ]]; then
229 stream_status=1
230 else
231 [[ -n "$model" ]] || model="$DEFAULT_OPENAI_MODEL"
232 payload="$(
233 jq -nc \
234 --arg model "$model" \
235 --arg system "$system" \
236 --argjson messages "$chat" '
237 {
238 model: $model,
239 messages:
240 (if ($system | length) > 0
241 then [{ role: "system", content: $system }] + $messages
242 else $messages
243 end),
244 stream: true
245 }
246 '
247 )"
248 stream_openai "$payload" "$message_id"
249 stream_status=$?
250 fi
251 ;;
252 anthropic)
253 if [[ -z "${ANTHROPIC_API_KEY:-}" ]]; then
254 stream_status=1
255 else
256 [[ -n "$model" ]] || model="$DEFAULT_ANTHROPIC_MODEL"
257 payload="$(
258 jq -nc \
259 --arg model "$model" \
260 --arg system "$system" \
261 --argjson messages "$chat" '
262 {
263 model: $model,
264 max_tokens: 4096,
265 messages: $messages,
266 stream: true
267 } +
268 (if ($system | length) > 0 then { system: $system } else {} end)
269 '
270 )"
271 stream_anthropic "$payload" "$message_id"
272 stream_status=$?
273 fi
274 ;;
275 *)
276 stream_status=1
277 ;;
278 esac
279​
280 if [[ "$stream_status" -ne 0 ]]; then
281 local error_message
282 case "$provider" in
283 openai)
284 error_message="${OPENAI_API_KEY:+OpenAI request failed}"
285 error_message="${error_message:-OPENAI_API_KEY is not set}"
286 ;;
287 anthropic)
288 error_message="${ANTHROPIC_API_KEY:+Anthropic request failed}"
289 error_message="${error_message:-ANTHROPIC_API_KEY is not set}"
290 ;;
291 *)
292 error_message="unsupported provider \"${provider}\" (expected openai or anthropic)"
293 ;;
294 esac
295​
296 write_event "$(
297 json_event \
298 --arg threadId "$thread_id" \
299 --arg runId "$run_id" \
300 --arg message "$error_message" \
301 '{
302 type: "RUN_ERROR",
303 threadId: $threadId,
304 runId: $runId,
305 error: { message: $message }
306 }'
307 )"
308 return
309 fi
310​
311 write_event "$(
312 json_event \
313 --arg messageId "$message_id" \
314 '{ type: "TEXT_MESSAGE_END", messageId: $messageId }'
315 )"
316 write_event "$(
317 json_event \
318 --arg threadId "$thread_id" \
319 --arg runId "$run_id" \
320 '{
321 type: "RUN_FINISHED",
322 threadId: $threadId,
323 runId: $runId,
324 finishReason: "stop"
325 }'
326 )"
328​
329handle_connection() {
330 local request_line method target version line header_name header_value
331 local content_length=0 body=''
332​
333 IFS= read -r request_line || return
334 request_line="${request_line%$'\r'}"
335 read -r method target version <<<"$request_line"
336​
337 while IFS= read -r line; do
338 line="${line%$'\r'}"
339 [[ -z "$line" ]] && break
340​
341 header_name="${line%%:*}"
342 header_value="${line#*:}"
343 header_value="${header_value#"${header_value%%[![:space:]]*}"}"
344 if [[ "${header_name,,}" == 'content-length' ]]; then
345 content_length="$header_value"
346 fi
347 done
348​
349 if ! [[ "$content_length" =~ ^[0-9]+$ ]]; then
350 write_error_response '400 Bad Request' 'invalid Content-Length'
351 return
352 fi
353​
354 if [[ "$content_length" -gt 0 ]]; then
355 body="$(dd bs=1 count="$content_length" 2>/dev/null)"
356 fi
357​
358 target="${target%%\?*}"
359​
360 if [[ "$method" == 'OPTIONS' ]]; then
361 printf 'HTTP/1.1 204 No Content\r\n'
362 printf 'Access-Control-Allow-Origin: *\r\n'
363 printf 'Access-Control-Allow-Methods: POST, OPTIONS\r\n'
364 printf 'Access-Control-Allow-Headers: Content-Type\r\n'
365 printf 'Connection: close\r\n'
366 printf '\r\n'
367 return
368 fi
369​
370 if [[ "$method" == 'GET' && "$target" == '/health' ]]; then
371 printf 'HTTP/1.1 200 OK\r\n'
372 printf 'Content-Type: text/plain; charset=utf-8\r\n'
373 printf 'Content-Length: 2\r\n'
374 printf 'Connection: close\r\n'
375 printf '\r\n'
376 printf 'ok'
377 return
378 fi
379​
380 if [[ "$method" != 'POST' ]]; then
381 write_error_response '405 Method Not Allowed' 'method not allowed'
382 return
383 fi
384​
385 if [[ "$target" != '/' ]]; then
386 write_error_response '404 Not Found' 'not found'
387 return
388 fi
389​
390 if ! jq -e 'type == "object"' >/dev/null 2>&1 <<<"$body"; then
391 write_error_response '400 Bad Request' 'invalid JSON body'
392 return
393 fi
394​
395 handle_chat "$body"
397​
398check_dependencies() {
399 local dependency
400 for dependency in bash curl jq socat; do
401 if ! command -v "$dependency" >/dev/null 2>&1; then
402 printf '[bash] missing dependency: %s\n' "$dependency" >&2
403 return 1
404 fi
405 done
407​
408if [[ "${1:-}" == '--handle' ]]; then
409 handle_connection
410 exit 0
411fi
412​
413check_dependencies || exit 1
414printf '[bash] listening on http://127.0.0.1:%s\n' "$PORT"
415exec socat \
416 "TCP-LISTEN:${PORT},bind=127.0.0.1,reuseaddr,fork" \
417 "SYSTEM:exec bash '${SCRIPT_PATH}' --handle"