- stream:true uses the provider's send_stream and writes each text delta as a chat.completion.chunk as it arrives, instead of one chunk at the end. The SSE headers and the role chunk go out before the upstream call, so a slow provider still gives the caller a live connection. - caller tool calls are sent as one tool_calls delta at the end of the step, when their names and arguments are complete; filtered gw_ calls are renumbered 0,1,... so strict accumulators see no gap. Local gw_ calls stay invisible. - stream_options.include_usage asks the provider for usage and adds the summed token counts in a final chunk before [DONE]. Usage is now summed over every upstream round, for the non-stream reply too. - an error after the first byte becomes an SSE error object plus [DONE]; a bad request is still an ordinary HTTP 400. SIGPIPE is ignored and TCP_NODELAY set, so a caller that closes early cannot kill the gateway. - tests: fake_gateway.py has a slow stream, tests/stream_probe.py measures that chunks arrive while the upstream streams, usage is checked, and the mixed reply keeps index 0 after filtering. make check green.
1284 lines
34 KiB
C
1284 lines
34 KiB
C
/*
|
|
* splinter -- an OpenAI-compatible endpoint with tools on both sides.
|
|
*
|
|
* Copyright (c) 2026 Konrad Lother
|
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
*
|
|
* POST /v1/chat/completions a chat completion, for another harness
|
|
* GET /v1/models what this endpoint answers as
|
|
*
|
|
* Why: splinter runs where the files and the shell are. Another harness (on
|
|
* another machine) can point its OpenAI client at this endpoint and get an
|
|
* answer, without implementing the tools itself.
|
|
*
|
|
* Two kinds of tools are offered to the model in one request:
|
|
*
|
|
* gw_read, gw_write, gw_run, ... splinter's own registry. The gateway
|
|
* executes them here, on this host, and
|
|
* loops until the model has an answer.
|
|
* the caller's tools (any other returned to the caller as ordinary
|
|
* name, provided in "tools") tool_calls; the harness executes them
|
|
* where it runs and sends the results in
|
|
* the next request.
|
|
*
|
|
* The gw_ prefix is the namespace: a caller may use read/write/edit itself,
|
|
* and it cannot collide with the local ones. A caller tool that starts with
|
|
* gw_ is refused, because that name is ours.
|
|
*
|
|
* Splinter is a stateless gateway here: the conversation travels in every
|
|
* request, exactly as the OpenAI protocol says. Local gw_ calls are executed
|
|
* inside one request; a model reply that mixes local and caller calls runs
|
|
* the local ones and asks again (the caller calls come on a later step).
|
|
*
|
|
* Security: binding beyond loopback requires SPLINTER_GATEWAY_TOKEN, and the
|
|
* token is checked on every request. Mutating and destructive local tools run
|
|
* only with --autonomous; otherwise the model is told they are denied. There
|
|
* is no TLS: put it behind ssh or a tunnel when the network is not yours.
|
|
*/
|
|
#include <arpa/inet.h>
|
|
#include <ctype.h>
|
|
#include <errno.h>
|
|
#include <fcntl.h>
|
|
#include <netinet/in.h>
|
|
#include <netinet/tcp.h>
|
|
#include <signal.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <strings.h>
|
|
#include <sys/socket.h>
|
|
#include <sys/time.h>
|
|
#include <sys/types.h>
|
|
#include <time.h>
|
|
#include <unistd.h>
|
|
|
|
#include "splinter.h"
|
|
#include "mcp.h"
|
|
#include "config.h"
|
|
#include "http.h"
|
|
#include "log.h"
|
|
#include "openai_server.h"
|
|
|
|
#define GW_STEPS 16
|
|
#define GW_OBS_MAX (32 * 1024)
|
|
#define GW_NAME_MAX 96
|
|
#define GW_PREFIX "gw_"
|
|
|
|
static volatile sig_atomic_t g_stop;
|
|
static unsigned long g_seq;
|
|
|
|
static void
|
|
on_signal(int sig)
|
|
{
|
|
(void)sig;
|
|
g_stop = 1;
|
|
}
|
|
|
|
/* ------------------------------------------------------------- JSON out */
|
|
|
|
static void
|
|
json_dump(const mcp_json *v, struct sp_buf *out)
|
|
{
|
|
size_t i;
|
|
|
|
if (v == NULL) {
|
|
sp_buf_puts(out, "null");
|
|
return;
|
|
}
|
|
switch (v->t) {
|
|
case MCP_NULL:
|
|
sp_buf_puts(out, "null");
|
|
break;
|
|
case MCP_BOOL:
|
|
sp_buf_puts(out, v->b ? "true" : "false");
|
|
break;
|
|
case MCP_NUM:
|
|
sp_buf_printf(out, "%.17g", v->n);
|
|
break;
|
|
case MCP_STR:
|
|
sp_buf_puts(out, "\"");
|
|
(void)sp_json_escape(out, v->s != NULL ? v->s : "");
|
|
sp_buf_puts(out, "\"");
|
|
break;
|
|
case MCP_ARR:
|
|
sp_buf_puts(out, "[");
|
|
for (i = 0; i < v->count; i++) {
|
|
if (i > 0)
|
|
sp_buf_puts(out, ",");
|
|
json_dump(v->items[i], out);
|
|
}
|
|
sp_buf_puts(out, "]");
|
|
break;
|
|
case MCP_OBJ:
|
|
sp_buf_puts(out, "{");
|
|
for (i = 0; i < v->count; i++) {
|
|
if (i > 0)
|
|
sp_buf_puts(out, ",");
|
|
sp_buf_puts(out, "\"");
|
|
(void)sp_json_escape(out, v->keys[i]);
|
|
sp_buf_puts(out, "\":");
|
|
json_dump(v->items[i], out);
|
|
}
|
|
sp_buf_puts(out, "}");
|
|
break;
|
|
}
|
|
}
|
|
|
|
/* the text of a content value: a string, or the text parts of an array */
|
|
static void
|
|
content_text(const mcp_json *v, struct sp_buf *out)
|
|
{
|
|
if (v == NULL) {
|
|
sp_buf_puts(out, "");
|
|
return;
|
|
}
|
|
if (v->t == MCP_STR) {
|
|
sp_buf_puts(out, v->s != NULL ? v->s : "");
|
|
return;
|
|
}
|
|
if (v->t == MCP_ARR) {
|
|
size_t i;
|
|
|
|
for (i = 0; i < v->count; i++) {
|
|
const mcp_json *part = v->items[i];
|
|
const char *type = mcp_arg_string(part, "type");
|
|
const char *text;
|
|
|
|
if (type != NULL && strcmp(type, "text") != 0)
|
|
continue; /* an image is not text */
|
|
text = mcp_arg_string(part, "text");
|
|
if (text == NULL && part->t == MCP_STR)
|
|
text = part->s;
|
|
if (text != NULL)
|
|
sp_buf_puts(out, text);
|
|
}
|
|
}
|
|
}
|
|
|
|
/* ------------------------------------------------------------- gateway */
|
|
|
|
struct gw_local {
|
|
char *name; /* gw_<tool> */
|
|
const struct sp_tool *tool; /* the real one */
|
|
};
|
|
|
|
/* the temporary registry the upstream transport shapes its request from */
|
|
struct gw_tools {
|
|
struct sp_registry reg;
|
|
char **owned;
|
|
size_t nown, capown;
|
|
struct gw_local **locals;
|
|
size_t nlocals, caplocals;
|
|
};
|
|
|
|
static char *
|
|
own(struct gw_tools *t, const char *s)
|
|
{
|
|
char *copy = strdup(s != NULL ? s : "");
|
|
|
|
if (copy == NULL)
|
|
return NULL;
|
|
if (t->nown == t->capown) {
|
|
size_t nc = t->capown != 0 ? t->capown * 2 : 32;
|
|
char **nv = realloc(t->owned, nc * sizeof(*nv));
|
|
|
|
if (nv == NULL) {
|
|
free(copy);
|
|
return NULL;
|
|
}
|
|
t->owned = nv;
|
|
t->capown = nc;
|
|
}
|
|
t->owned[t->nown++] = copy;
|
|
return copy;
|
|
}
|
|
|
|
static void
|
|
tools_free(struct gw_tools *t)
|
|
{
|
|
size_t i;
|
|
|
|
for (i = 0; i < t->nlocals; i++) {
|
|
free(t->locals[i]->name);
|
|
free(t->locals[i]);
|
|
}
|
|
free(t->locals);
|
|
for (i = 0; i < t->nown; i++)
|
|
free(t->owned[i]);
|
|
free(t->owned);
|
|
sp_registry_free(&t->reg);
|
|
memset(t, 0, sizeof(*t));
|
|
}
|
|
|
|
static int
|
|
local_run(const char *args, struct sp_buf *out, void *ctx)
|
|
{
|
|
struct gw_local *l = ctx;
|
|
|
|
if (l == NULL || l->tool == NULL || l->tool->run == NULL) {
|
|
sp_buf_puts(out, "gateway: the local tool has no runner");
|
|
return -1;
|
|
}
|
|
return l->tool->run(args, out, l->tool->ctx);
|
|
}
|
|
|
|
/* a caller tool is never executed here; it is returned to its owner */
|
|
static int
|
|
client_run(const char *args, struct sp_buf *out, void *ctx)
|
|
{
|
|
(void)args;
|
|
(void)ctx;
|
|
sp_buf_puts(out, "gateway: this tool belongs to the caller");
|
|
return -1;
|
|
}
|
|
|
|
static int
|
|
add_caller_tools(struct gw_tools *t, const mcp_json *tools, struct sp_buf *err)
|
|
{
|
|
const mcp_json *item;
|
|
size_t i, j;
|
|
size_t n = tools != NULL ? tools->count : 0;
|
|
|
|
for (i = 0; i < n; i++) {
|
|
const mcp_json *fn, *params;
|
|
const char *name, *desc;
|
|
struct sp_buf pbuf;
|
|
struct sp_tool tool;
|
|
char *p = NULL;
|
|
|
|
item = tools->items[i];
|
|
fn = mcp_arg(item, "function");
|
|
if (fn == NULL)
|
|
fn = item; /* tolerate a flat tool object */
|
|
name = mcp_arg_string(fn, "name");
|
|
desc = mcp_arg_string(fn, "description");
|
|
if (name == NULL || *name == '\0' ||
|
|
strlen(name) >= GW_NAME_MAX) {
|
|
sp_buf_printf(err, "tool %zu has no usable name", i);
|
|
return -1;
|
|
}
|
|
if (strncmp(name, GW_PREFIX, strlen(GW_PREFIX)) == 0) {
|
|
sp_buf_printf(err, "tool name '%s' is reserved: the "
|
|
"gateway's local tools live under %s", name,
|
|
GW_PREFIX);
|
|
return -1;
|
|
}
|
|
for (j = 0; j < t->reg.len; j++) {
|
|
if (t->reg.tools[j].name != NULL &&
|
|
strcmp(t->reg.tools[j].name, name) == 0) {
|
|
sp_buf_printf(err, "tool '%s' appears twice",
|
|
name);
|
|
return -1;
|
|
}
|
|
}
|
|
params = mcp_arg(fn, "parameters");
|
|
if (params != NULL) {
|
|
sp_buf_init(&pbuf);
|
|
json_dump(params, &pbuf);
|
|
p = own(t, pbuf.p != NULL ? pbuf.p : "{}");
|
|
sp_buf_free(&pbuf);
|
|
}
|
|
memset(&tool, 0, sizeof(tool));
|
|
tool.name = own(t, name);
|
|
tool.description = own(t, desc != NULL ? desc :
|
|
"a tool of the calling harness");
|
|
tool.params = p;
|
|
tool.auth = SP_AUTH_READ; /* never runs here */
|
|
tool.run = client_run;
|
|
tool.ctx = NULL;
|
|
if (tool.name == NULL || tool.description == NULL ||
|
|
sp_registry_add(&t->reg, &tool) != 0) {
|
|
sp_buf_puts(err, "cannot register the caller's tools");
|
|
return -1;
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
static int
|
|
add_local_tools(struct gw_tools *t, const struct sp_registry *real,
|
|
struct sp_buf *err)
|
|
{
|
|
const struct sp_tool *tv;
|
|
size_t i, n;
|
|
|
|
tv = sp_registry_tools(real, &n);
|
|
for (i = 0; i < n; i++) {
|
|
const struct sp_tool *r = &tv[i];
|
|
struct gw_local *l;
|
|
struct sp_tool tool;
|
|
char name[GW_NAME_MAX], desc[512];
|
|
|
|
if (r->name == NULL || *r->name == '\0')
|
|
continue;
|
|
snprintf(name, sizeof(name), "%s%s", GW_PREFIX, r->name);
|
|
snprintf(desc, sizeof(desc), "Runs %s on the splinter host: %s",
|
|
r->name, r->description != NULL ? r->description : "");
|
|
l = calloc(1, sizeof(*l));
|
|
if (l == NULL) {
|
|
sp_buf_puts(err, "out of memory");
|
|
return -1;
|
|
}
|
|
l->name = strdup(name);
|
|
if (l->name == NULL) {
|
|
free(l);
|
|
sp_buf_puts(err, "out of memory");
|
|
return -1;
|
|
}
|
|
l->tool = r;
|
|
if (t->nlocals == t->caplocals) {
|
|
size_t nc = t->caplocals != 0 ?
|
|
t->caplocals * 2 : 32;
|
|
struct gw_local **nv = realloc(t->locals,
|
|
nc * sizeof(*nv));
|
|
|
|
if (nv == NULL) {
|
|
free(l->name);
|
|
free(l);
|
|
sp_buf_puts(err, "out of memory");
|
|
return -1;
|
|
}
|
|
t->locals = nv;
|
|
t->caplocals = nc;
|
|
}
|
|
t->locals[t->nlocals++] = l;
|
|
memset(&tool, 0, sizeof(tool));
|
|
tool.name = l->name;
|
|
tool.description = own(t, desc);
|
|
tool.params = r->params != NULL ? own(t, r->params) : NULL;
|
|
tool.auth = SP_AUTH_READ; /* the gateway checks the class */
|
|
tool.run = local_run;
|
|
tool.ctx = l;
|
|
if (tool.description == NULL ||
|
|
sp_registry_add(&t->reg, &tool) != 0) {
|
|
sp_buf_puts(err, "cannot register the gateway tools");
|
|
return -1;
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/* messages: OpenAI's view -> splinter's conversation */
|
|
static int
|
|
parse_messages(const mcp_json *req, struct sp_conv *conv, struct sp_buf *err)
|
|
{
|
|
const mcp_json *msgs = mcp_arg(req, "messages");
|
|
size_t i;
|
|
|
|
if (msgs == NULL || msgs->t != MCP_ARR || msgs->count == 0) {
|
|
sp_buf_puts(err, "messages is required");
|
|
return -1;
|
|
}
|
|
for (i = 0; i < msgs->count; i++) {
|
|
const mcp_json *m = msgs->items[i];
|
|
const char *role = mcp_arg_string(m, "role");
|
|
const mcp_json *calls = mcp_arg(m, "tool_calls");
|
|
struct sp_msg msg;
|
|
struct sp_buf content, calls_json;
|
|
|
|
if (role == NULL) {
|
|
sp_buf_printf(err, "message %zu has no role", i);
|
|
return -1;
|
|
}
|
|
if (strcmp(role, "developer") == 0)
|
|
role = "system";
|
|
if (strcmp(role, "system") != 0 && strcmp(role, "user") != 0 &&
|
|
strcmp(role, "assistant") != 0 &&
|
|
strcmp(role, "tool") != 0) {
|
|
sp_buf_printf(err, "message %zu has role '%s'", i, role);
|
|
return -1;
|
|
}
|
|
if (sp_buf_init(&content) != 0)
|
|
return -1;
|
|
content_text(mcp_arg(m, "content"), &content);
|
|
memset(&msg, 0, sizeof(msg));
|
|
msg.role = (char *)role;
|
|
msg.content = content.p != NULL ? content.p : "";
|
|
msg.call_id = (char *)mcp_arg_string(m, "tool_call_id");
|
|
msg.name = (char *)mcp_arg_string(m, "name");
|
|
if (calls != NULL) {
|
|
sp_buf_init(&calls_json);
|
|
json_dump(calls, &calls_json);
|
|
msg.calls = calls_json.p;
|
|
}
|
|
if (sp_conv_add(conv, &msg) != 0) {
|
|
sp_buf_free(&content);
|
|
if (calls != NULL)
|
|
sp_buf_free(&calls_json);
|
|
sp_buf_puts(err, "out of memory");
|
|
return -1;
|
|
}
|
|
if (calls != NULL)
|
|
sp_buf_free(&calls_json);
|
|
sp_buf_free(&content);
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/*
|
|
* A normalized tool_calls array from a reply. `only_caller` drops the gw_
|
|
* calls: those belong to this host and never go back to the harness.
|
|
*/
|
|
static void
|
|
calls_json(const struct sp_reply *r, int only_caller, struct sp_buf *out)
|
|
{
|
|
size_t i, slot = 0;
|
|
int first = 1;
|
|
|
|
sp_buf_puts(out, "[");
|
|
for (i = 0; i < r->ncalls; i++) {
|
|
const struct sp_toolcall *c = &r->calls[i];
|
|
|
|
if (only_caller && c->name != NULL &&
|
|
strncmp(c->name, GW_PREFIX, strlen(GW_PREFIX)) == 0)
|
|
continue;
|
|
if (!first)
|
|
sp_buf_puts(out, ",");
|
|
first = 0;
|
|
sp_buf_puts(out, "{\"index\":");
|
|
/*
|
|
* Filtered calls leave no gap: streaming clients key their
|
|
* accumulator by this index and expect 0, 1, ...
|
|
*/
|
|
sp_buf_printf(out, "%zu", slot++);
|
|
sp_buf_puts(out, ",\"id\":\"");
|
|
(void)sp_json_escape(out, c->id != NULL ? c->id : "call");
|
|
sp_buf_puts(out, "\",\"type\":\"function\",\"function\":{\"name\":\"");
|
|
(void)sp_json_escape(out, c->name != NULL ? c->name : "");
|
|
sp_buf_puts(out, "\",\"arguments\":\"");
|
|
(void)sp_json_escape(out, c->args != NULL ? c->args : "");
|
|
sp_buf_puts(out, "\"}}");
|
|
}
|
|
sp_buf_puts(out, "]");
|
|
}
|
|
|
|
/* the assistant turn with only the local calls; every one gets its result */
|
|
static void
|
|
append_assistant_turn(struct sp_conv *conv, const struct sp_reply *rep,
|
|
struct sp_buf *local_calls)
|
|
{
|
|
struct sp_msg m;
|
|
|
|
memset(&m, 0, sizeof(m));
|
|
m.role = "assistant";
|
|
m.content = rep->content != NULL ? rep->content : "";
|
|
m.calls = local_calls->p;
|
|
(void)sp_conv_add(conv, &m);
|
|
}
|
|
|
|
static void
|
|
append_tool_result(struct sp_conv *conv, const struct sp_toolcall *c,
|
|
const char *obs)
|
|
{
|
|
struct sp_msg m;
|
|
|
|
memset(&m, 0, sizeof(m));
|
|
m.role = "tool";
|
|
m.call_id = c->id;
|
|
m.name = c->name;
|
|
m.content = (char *)(obs != NULL ? obs : "");
|
|
(void)sp_conv_add(conv, &m);
|
|
}
|
|
|
|
/* the local calls only, so the assistant turn needs results for every call */
|
|
static void
|
|
local_calls_json(const struct sp_reply *rep, struct sp_buf *out)
|
|
{
|
|
size_t i;
|
|
int first = 1;
|
|
|
|
sp_buf_puts(out, "[");
|
|
for (i = 0; i < rep->ncalls; i++) {
|
|
const struct sp_toolcall *c = &rep->calls[i];
|
|
|
|
if (c->name == NULL ||
|
|
strncmp(c->name, GW_PREFIX, strlen(GW_PREFIX)) != 0)
|
|
continue;
|
|
if (!first)
|
|
sp_buf_puts(out, ",");
|
|
first = 0;
|
|
sp_buf_puts(out, "{\"id\":\"");
|
|
(void)sp_json_escape(out, c->id != NULL ? c->id : "call");
|
|
sp_buf_puts(out, "\",\"type\":\"function\",\"function\":"
|
|
"{\"name\":\"");
|
|
(void)sp_json_escape(out, c->name);
|
|
sp_buf_puts(out, "\",\"arguments\":\"");
|
|
(void)sp_json_escape(out, c->args != NULL ? c->args : "{}");
|
|
sp_buf_puts(out, "\"}}");
|
|
}
|
|
sp_buf_puts(out, "]");
|
|
}
|
|
|
|
/* one local tool; returns 0 with the observation in out */
|
|
static int
|
|
run_local(const struct sp_gateway_opts *o, const char *gw_name,
|
|
const char *args, struct sp_buf *out)
|
|
{
|
|
const struct sp_tool *t;
|
|
const char *name = gw_name + strlen(GW_PREFIX);
|
|
|
|
t = sp_registry_find(o->reg, name);
|
|
if (t == NULL) {
|
|
sp_buf_printf(out, "gateway: no local tool '%s'", name);
|
|
return -1;
|
|
}
|
|
if (t->auth != SP_AUTH_READ && !o->autonomous) {
|
|
sp_buf_puts(out, "denied: the gateway runs mutating and "
|
|
"destructive tools only with --autonomous");
|
|
return 0;
|
|
}
|
|
if (t->run == NULL) {
|
|
sp_buf_printf(out, "gateway: '%s' has no runner", name);
|
|
return -1;
|
|
}
|
|
if (sp_log_active())
|
|
sp_logf("gateway", "local tool %s", name);
|
|
return t->run(args, out, t->ctx);
|
|
}
|
|
|
|
static struct sp_transport
|
|
make_transport(const struct sp_gateway_opts *o, struct gw_tools *t,
|
|
const struct sp_gen_opts *gen)
|
|
{
|
|
const char *key = (o->key_env != NULL && *o->key_env != '\0') ?
|
|
getenv(o->key_env) : NULL;
|
|
const char *hto = getenv("SPLINTER_HTTP_TIMEOUT");
|
|
long timeout = hto != NULL && *hto != '\0' ?
|
|
strtol(hto, NULL, 10) : 0;
|
|
|
|
if (timeout <= 0)
|
|
timeout = 900;
|
|
if (o->kind != NULL && strcmp(o->kind, "anthropic") == 0)
|
|
return sp_anthropic_transport_gen(o->endpoint, o->model, key,
|
|
&t->reg, timeout, gen);
|
|
return sp_openai_transport_gen(o->endpoint, o->model, key, &t->reg,
|
|
timeout, gen);
|
|
}
|
|
|
|
static void
|
|
error_json(struct sp_buf *b, const char *msg)
|
|
{
|
|
sp_buf_clear(b);
|
|
sp_buf_puts(b, "{\"error\":{\"message\":\"");
|
|
(void)sp_json_escape(b, msg != NULL ? msg : "error");
|
|
sp_buf_puts(b, "\",\"type\":\"invalid_request_error\"}}");
|
|
}
|
|
|
|
static void
|
|
usage_fields(struct sp_buf *b, long tin, long tout)
|
|
{
|
|
sp_buf_printf(b, "\"prompt_tokens\":%ld,\"completion_tokens\":%ld,"
|
|
"\"total_tokens\":%ld", tin, tout, tin + tout);
|
|
}
|
|
|
|
static void
|
|
completion_json(struct sp_buf *out, const char *id, const char *model,
|
|
const char *content, long tin, long tout, const char *calls)
|
|
{
|
|
char created[32];
|
|
|
|
snprintf(created, sizeof(created), "%ld", (long)time(NULL));
|
|
sp_buf_clear(out);
|
|
sp_buf_puts(out, "{\"id\":\"");
|
|
(void)sp_json_escape(out, id);
|
|
sp_buf_puts(out, "\",\"object\":\"chat.completion\",\"created\":");
|
|
sp_buf_puts(out, created);
|
|
sp_buf_puts(out, ",\"model\":\"");
|
|
(void)sp_json_escape(out, model != NULL ? model : "");
|
|
sp_buf_puts(out, "\",\"choices\":[{\"index\":0,\"message\":{\"role\":"
|
|
"\"assistant\",\"content\":\"");
|
|
(void)sp_json_escape(out, content != NULL ? content : "");
|
|
sp_buf_puts(out, "\"");
|
|
if (calls != NULL) {
|
|
sp_buf_puts(out, ",\"tool_calls\":");
|
|
sp_buf_puts(out, calls);
|
|
}
|
|
sp_buf_puts(out, "},\"finish_reason\":\"");
|
|
sp_buf_puts(out, calls != NULL ? "tool_calls" : "stop");
|
|
sp_buf_puts(out, "\"}],\"usage\":{");
|
|
usage_fields(out, tin, tout);
|
|
sp_buf_puts(out, "}}");
|
|
}
|
|
|
|
/* ------------------------------------------------------------ the stream */
|
|
|
|
/* what the upstream callback needs, and what it already sent */
|
|
struct gw_stream {
|
|
int fd;
|
|
const char *id;
|
|
const char *model;
|
|
long created;
|
|
int got_text;
|
|
int failed;
|
|
};
|
|
|
|
static int
|
|
sse_raw(int fd, const char *json)
|
|
{
|
|
if (sp_http_write_all(fd, "data: ", 6) != 0 ||
|
|
sp_http_write_all(fd, json, strlen(json)) != 0 ||
|
|
sp_http_write_all(fd, "\n\n", 2) != 0)
|
|
return -1;
|
|
return 0;
|
|
}
|
|
|
|
/*
|
|
* One chat.completion.chunk. `role`, `content` and `calls` are optional; a
|
|
* chunk may carry content and caller tool calls together (the mixed reply).
|
|
*/
|
|
static int
|
|
sse_chunk(int fd, const char *id, const char *model, long created,
|
|
const char *role, const char *content, const char *calls,
|
|
const char *finish)
|
|
{
|
|
struct sp_buf b;
|
|
int first = 1, rc;
|
|
|
|
if (sp_buf_init(&b) != 0)
|
|
return -1;
|
|
sp_buf_puts(&b, "{\"id\":\"");
|
|
(void)sp_json_escape(&b, id);
|
|
sp_buf_printf(&b, "\",\"object\":\"chat.completion.chunk\","
|
|
"\"created\":%ld,\"model\":\"", created);
|
|
(void)sp_json_escape(&b, model != NULL ? model : "");
|
|
sp_buf_puts(&b, "\",\"choices\":[{\"index\":0,\"delta\":{");
|
|
if (role != NULL) {
|
|
sp_buf_puts(&b, "\"role\":\"");
|
|
(void)sp_json_escape(&b, role);
|
|
sp_buf_puts(&b, "\"");
|
|
first = 0;
|
|
}
|
|
if (content != NULL) {
|
|
if (!first)
|
|
sp_buf_puts(&b, ",");
|
|
sp_buf_puts(&b, "\"content\":\"");
|
|
(void)sp_json_escape(&b, content);
|
|
sp_buf_puts(&b, "\"");
|
|
first = 0;
|
|
}
|
|
if (calls != NULL) {
|
|
if (!first)
|
|
sp_buf_puts(&b, ",");
|
|
sp_buf_puts(&b, "\"tool_calls\":");
|
|
sp_buf_puts(&b, calls);
|
|
}
|
|
sp_buf_puts(&b, "},\"finish_reason\":");
|
|
if (finish != NULL) {
|
|
sp_buf_puts(&b, "\"");
|
|
(void)sp_json_escape(&b, finish);
|
|
sp_buf_puts(&b, "\"");
|
|
} else
|
|
sp_buf_puts(&b, "null");
|
|
sp_buf_puts(&b, "}]}");
|
|
rc = sse_raw(fd, b.p != NULL ? b.p : "{}");
|
|
sp_buf_free(&b);
|
|
return rc;
|
|
}
|
|
|
|
static int
|
|
sse_usage(int fd, const char *id, const char *model, long created, long tin,
|
|
long tout)
|
|
{
|
|
struct sp_buf b;
|
|
int rc;
|
|
|
|
if (sp_buf_init(&b) != 0)
|
|
return -1;
|
|
sp_buf_puts(&b, "{\"id\":\"");
|
|
(void)sp_json_escape(&b, id);
|
|
sp_buf_printf(&b, "\",\"object\":\"chat.completion.chunk\","
|
|
"\"created\":%ld,\"model\":\"", created);
|
|
(void)sp_json_escape(&b, model != NULL ? model : "");
|
|
sp_buf_puts(&b, "\",\"choices\":[],\"usage\":{");
|
|
usage_fields(&b, tin, tout);
|
|
sp_buf_puts(&b, "}}");
|
|
rc = sse_raw(fd, b.p != NULL ? b.p : "{}");
|
|
sp_buf_free(&b);
|
|
return rc;
|
|
}
|
|
|
|
static int
|
|
sse_error(int fd, const char *msg)
|
|
{
|
|
struct sp_buf b;
|
|
int rc;
|
|
|
|
if (sp_buf_init(&b) != 0)
|
|
return -1;
|
|
error_json(&b, msg != NULL ? msg : "error");
|
|
rc = sse_raw(fd, b.p != NULL ? b.p : "{}");
|
|
sp_buf_free(&b);
|
|
return rc;
|
|
}
|
|
|
|
static int
|
|
sse_done(int fd)
|
|
{
|
|
return sp_http_write_all(fd, "data: [DONE]\n\n", 14);
|
|
}
|
|
|
|
/* the upstream's text deltas go straight to the caller; thinking does not */
|
|
static void
|
|
gw_stream_cb(void *ctx, int kind, const char *text)
|
|
{
|
|
struct gw_stream *s = ctx;
|
|
|
|
if (s->failed || kind != SP_STREAM_TEXT || text == NULL ||
|
|
*text == '\0')
|
|
return;
|
|
if (sse_chunk(s->fd, s->id, s->model, s->created, NULL, text, NULL,
|
|
NULL) != 0)
|
|
s->failed = 1;
|
|
else
|
|
s->got_text = 1;
|
|
}
|
|
|
|
/* tool calls, finish reason, optional usage, [DONE] - in that order */
|
|
static int
|
|
stream_finish(int fd, const char *id, const char *model, long created,
|
|
const char *calls, const char *finish, int want_usage, long tin,
|
|
long tout)
|
|
{
|
|
if (calls != NULL && sse_chunk(fd, id, model, created, NULL, NULL,
|
|
calls, NULL) != 0)
|
|
return -1;
|
|
if (sse_chunk(fd, id, model, created, NULL, NULL, NULL, finish) != 0)
|
|
return -1;
|
|
if (want_usage && sse_usage(fd, id, model, created, tin, tout) != 0)
|
|
return -1;
|
|
return sse_done(fd);
|
|
}
|
|
|
|
/* ------------------------------------------------------------ one request */
|
|
|
|
/* the generation knobs a caller may set; absent ones stay provider default */
|
|
static void
|
|
parse_gen(const mcp_json *req, struct sp_gen_opts *g)
|
|
{
|
|
const mcp_json *v;
|
|
|
|
memset(g, 0, sizeof(*g));
|
|
v = mcp_arg(req, "temperature");
|
|
if (v != NULL && v->t == MCP_NUM) {
|
|
g->have_temperature = 1;
|
|
g->temperature = v->n;
|
|
}
|
|
v = mcp_arg(req, "top_p");
|
|
if (v != NULL && v->t == MCP_NUM) {
|
|
g->have_top_p = 1;
|
|
g->top_p = v->n;
|
|
}
|
|
v = mcp_arg(req, "max_tokens");
|
|
if (v == NULL || v->t != MCP_NUM)
|
|
v = mcp_arg(req, "max_completion_tokens");
|
|
if (v != NULL && v->t == MCP_NUM && v->n >= 1 && v->n <= 1e9) {
|
|
g->have_max_tokens = 1;
|
|
g->max_tokens = (long)v->n;
|
|
}
|
|
}
|
|
|
|
static void
|
|
append_observation_note(struct sp_buf *notes, const char *name,
|
|
const char *obs)
|
|
{
|
|
if (notes->len > 0)
|
|
sp_buf_puts(notes, "\n");
|
|
sp_buf_puts(notes, "[");
|
|
sp_buf_puts(notes, name != NULL ? name : "gw_");
|
|
sp_buf_puts(notes, "]\n");
|
|
sp_buf_puts(notes, obs != NULL ? obs : "");
|
|
}
|
|
|
|
static void
|
|
handle_chat(int fd, const struct sp_gateway_opts *o, const char *body)
|
|
{
|
|
mcp_json *req;
|
|
const mcp_json *msgtools;
|
|
const char *req_model;
|
|
struct sp_conv conv;
|
|
struct gw_tools tools;
|
|
struct sp_buf err, answer, payload;
|
|
struct sp_gen_opts gen;
|
|
long created = (long)time(NULL);
|
|
long tokens_in = 0, tokens_out = 0;
|
|
int stream, want_usage = 0, headers_sent = 0;
|
|
unsigned long seq = ++g_seq;
|
|
char id[80];
|
|
const char *model;
|
|
|
|
req = mcp_parse(body);
|
|
if (req == NULL) {
|
|
sp_buf_init(&payload);
|
|
error_json(&payload, "the request is not JSON");
|
|
sp_http_reply(fd, 400, "Bad Request", "application/json",
|
|
payload.p);
|
|
sp_buf_free(&payload);
|
|
return;
|
|
}
|
|
memset(&conv, 0, sizeof(conv));
|
|
memset(&tools, 0, sizeof(tools));
|
|
sp_conv_init(&conv);
|
|
if (sp_buf_init(&err) != 0 || sp_buf_init(&answer) != 0 ||
|
|
sp_buf_init(&payload) != 0) {
|
|
mcp_json_free(req);
|
|
return;
|
|
}
|
|
if (parse_messages(req, &conv, &err) != 0)
|
|
goto bad;
|
|
msgtools = mcp_arg(req, "tools");
|
|
if (msgtools != NULL && msgtools->t != MCP_ARR) {
|
|
sp_buf_puts(&err, "tools must be an array");
|
|
goto bad;
|
|
}
|
|
if (add_caller_tools(&tools, msgtools, &err) != 0)
|
|
goto bad;
|
|
if (add_local_tools(&tools, o->reg, &err) != 0)
|
|
goto bad;
|
|
req_model = mcp_arg_string(req, "model");
|
|
model = req_model != NULL && *req_model != '\0' ? req_model : o->model;
|
|
stream = mcp_arg_bool(req, "stream", 0);
|
|
parse_gen(req, &gen);
|
|
if (stream) {
|
|
const mcp_json *so = mcp_arg(req, "stream_options");
|
|
|
|
want_usage = so != NULL && mcp_arg_bool(so, "include_usage", 0);
|
|
gen.include_usage = want_usage;
|
|
}
|
|
snprintf(id, sizeof(id), "chatcmpl-%ld-%lu", (long)getpid(), seq);
|
|
|
|
/*
|
|
* Everything is parsed and the tool table is built before the first
|
|
* byte of the stream: a bad request is still a clean HTTP 400.
|
|
*/
|
|
if (stream) {
|
|
if (sp_http_begin_stream(fd) != 0)
|
|
goto out;
|
|
headers_sent = 1;
|
|
if (sse_chunk(fd, id, model, created, "assistant", "", NULL,
|
|
NULL) != 0)
|
|
goto out;
|
|
}
|
|
|
|
{
|
|
size_t max_steps = o->max_steps > 0 ? o->max_steps : GW_STEPS;
|
|
int step;
|
|
|
|
for (step = 0; step < (int)max_steps; step++) {
|
|
struct sp_transport tr = make_transport(o, &tools,
|
|
&gen);
|
|
struct sp_reply rep;
|
|
struct sp_buf uerr;
|
|
struct gw_stream sc;
|
|
size_t i, nlocal = 0, nclient = 0;
|
|
int rc;
|
|
|
|
if (tr.send == NULL) {
|
|
sp_buf_puts(&err, "cannot build the upstream "
|
|
"transport");
|
|
goto upstream_bad;
|
|
}
|
|
memset(&rep, 0, sizeof(rep));
|
|
memset(&sc, 0, sizeof(sc));
|
|
sc.fd = fd;
|
|
sc.id = id;
|
|
sc.model = model;
|
|
sc.created = created;
|
|
sp_buf_init(&uerr);
|
|
if (stream && tr.send_stream != NULL)
|
|
rc = tr.send_stream(tr.ctx, &conv, &rep, &uerr,
|
|
gw_stream_cb, &sc);
|
|
else
|
|
rc = tr.send(tr.ctx, &conv, &rep, &uerr);
|
|
sp_transport_dispose(&tr);
|
|
if (rc != 0) {
|
|
sp_buf_printf(&err, "upstream: %s",
|
|
uerr.p != NULL && uerr.len > 0 ? uerr.p :
|
|
"no answer");
|
|
sp_buf_free(&uerr);
|
|
sp_reply_free(&rep);
|
|
goto upstream_bad;
|
|
}
|
|
sp_buf_free(&uerr);
|
|
tokens_in += rep.tokens_in > 0 ? rep.tokens_in : 0;
|
|
tokens_out += rep.tokens_out > 0 ? rep.tokens_out : 0;
|
|
if (sc.failed) {
|
|
/* the caller went away mid-stream */
|
|
sp_reply_free(&rep);
|
|
goto out;
|
|
}
|
|
/*
|
|
* A transport without a working callback, or a stream
|
|
* that carried no text: send the answer we have, so a
|
|
* quiet upstream never looks like an empty answer.
|
|
*/
|
|
if (stream && !sc.got_text && rep.content != NULL &&
|
|
*rep.content != '\0') {
|
|
if (sse_chunk(fd, id, model, created, NULL,
|
|
rep.content, NULL, NULL) != 0) {
|
|
sp_reply_free(&rep);
|
|
goto out;
|
|
}
|
|
}
|
|
for (i = 0; i < rep.ncalls; i++) {
|
|
if (rep.calls[i].name != NULL &&
|
|
strncmp(rep.calls[i].name, GW_PREFIX,
|
|
strlen(GW_PREFIX)) == 0)
|
|
nlocal++;
|
|
else
|
|
nclient++;
|
|
}
|
|
if (nlocal == 0 && nclient == 0) {
|
|
/* the answer */
|
|
if (stream) {
|
|
if (stream_finish(fd, id, model,
|
|
created, NULL, "stop", want_usage,
|
|
tokens_in, tokens_out) != 0) {
|
|
sp_reply_free(&rep);
|
|
goto out;
|
|
}
|
|
} else {
|
|
sp_buf_clear(&answer);
|
|
if (rep.content != NULL)
|
|
sp_buf_puts(&answer,
|
|
rep.content);
|
|
completion_json(&payload, id, model,
|
|
answer.p, tokens_in, tokens_out,
|
|
NULL);
|
|
}
|
|
sp_reply_free(&rep);
|
|
break;
|
|
}
|
|
if (nlocal > 0) {
|
|
struct sp_buf local, notes;
|
|
|
|
sp_buf_init(¬es);
|
|
/*
|
|
* Local calls belong to this host. With no
|
|
* caller calls they continue the loop; a mixed
|
|
* reply cannot be continued here (its caller
|
|
* calls still need results), so the caller's
|
|
* calls go out in tool_calls and the local
|
|
* observations in the content.
|
|
*/
|
|
if (nclient == 0) {
|
|
sp_buf_init(&local);
|
|
local_calls_json(&rep, &local);
|
|
append_assistant_turn(&conv, &rep,
|
|
&local);
|
|
sp_buf_free(&local);
|
|
}
|
|
for (i = 0; i < rep.ncalls; i++) {
|
|
struct sp_buf obs;
|
|
const char *nm = rep.calls[i].name;
|
|
|
|
if (nm == NULL ||
|
|
strncmp(nm, GW_PREFIX,
|
|
strlen(GW_PREFIX)) != 0)
|
|
continue;
|
|
sp_buf_init(&obs);
|
|
(void)run_local(o, nm,
|
|
rep.calls[i].args != NULL ?
|
|
rep.calls[i].args : "{}", &obs);
|
|
if (obs.len > GW_OBS_MAX) {
|
|
obs.p[GW_OBS_MAX] = '\0';
|
|
obs.len = GW_OBS_MAX;
|
|
sp_buf_puts(&obs, "\n[... "
|
|
"truncated]");
|
|
}
|
|
if (nclient == 0)
|
|
append_tool_result(&conv,
|
|
&rep.calls[i],
|
|
obs.p != NULL ? obs.p : "");
|
|
else
|
|
append_observation_note(
|
|
¬es, nm, obs.p);
|
|
sp_buf_free(&obs);
|
|
}
|
|
if (nclient > 0) {
|
|
struct sp_buf calls;
|
|
|
|
sp_buf_init(&calls);
|
|
calls_json(&rep, 1, &calls);
|
|
if (stream) {
|
|
if (notes.len > 0 &&
|
|
sse_chunk(fd, id, model,
|
|
created, NULL, notes.p, NULL,
|
|
NULL) != 0) {
|
|
sp_buf_free(&calls);
|
|
sp_buf_free(¬es);
|
|
sp_reply_free(&rep);
|
|
goto out;
|
|
}
|
|
if (stream_finish(fd, id, model,
|
|
created, calls.p,
|
|
"tool_calls", want_usage,
|
|
tokens_in, tokens_out) != 0) {
|
|
sp_buf_free(&calls);
|
|
sp_buf_free(¬es);
|
|
sp_reply_free(&rep);
|
|
goto out;
|
|
}
|
|
} else {
|
|
sp_buf_clear(&answer);
|
|
if (rep.content != NULL)
|
|
sp_buf_puts(&answer,
|
|
rep.content);
|
|
if (notes.len > 0) {
|
|
if (answer.len > 0)
|
|
sp_buf_puts(&answer,
|
|
"\n\n");
|
|
sp_buf_puts(&answer,
|
|
"local gateway tools "
|
|
"ran on the splinter "
|
|
"host:\n");
|
|
sp_buf_puts(&answer,
|
|
notes.p);
|
|
}
|
|
completion_json(&payload, id,
|
|
model, answer.p, tokens_in,
|
|
tokens_out, calls.p);
|
|
}
|
|
sp_buf_free(&calls);
|
|
sp_buf_free(¬es);
|
|
sp_reply_free(&rep);
|
|
break;
|
|
}
|
|
sp_buf_free(¬es);
|
|
sp_reply_free(&rep);
|
|
continue;
|
|
}
|
|
/*
|
|
* Only the caller's tools: return them. It runs them
|
|
* where it lives and sends the results next time.
|
|
*/
|
|
{
|
|
struct sp_buf calls;
|
|
|
|
sp_buf_init(&calls);
|
|
calls_json(&rep, 0, &calls);
|
|
if (stream) {
|
|
if (stream_finish(fd, id, model, created,
|
|
calls.p, "tool_calls", want_usage,
|
|
tokens_in, tokens_out) != 0) {
|
|
sp_buf_free(&calls);
|
|
sp_reply_free(&rep);
|
|
goto out;
|
|
}
|
|
} else {
|
|
sp_buf_clear(&answer);
|
|
if (rep.content != NULL)
|
|
sp_buf_puts(&answer,
|
|
rep.content);
|
|
completion_json(&payload, id, model,
|
|
answer.p, tokens_in, tokens_out,
|
|
calls.p);
|
|
}
|
|
sp_buf_free(&calls);
|
|
}
|
|
sp_reply_free(&rep);
|
|
break;
|
|
}
|
|
if (step == (int)max_steps) {
|
|
sp_buf_printf(&err, "more than %zu gateway tool rounds",
|
|
max_steps);
|
|
goto upstream_bad;
|
|
}
|
|
}
|
|
if (!stream)
|
|
sp_http_reply(fd, 200, "OK", "application/json",
|
|
payload.p != NULL ? payload.p : "{}");
|
|
goto out;
|
|
|
|
bad:
|
|
if (headers_sent) {
|
|
(void)sse_error(fd, err.p != NULL ? err.p : "bad request");
|
|
(void)sse_done(fd);
|
|
} else {
|
|
error_json(&payload, err.p != NULL ? err.p : "bad request");
|
|
sp_http_reply(fd, 400, "Bad Request", "application/json",
|
|
payload.p);
|
|
}
|
|
goto out;
|
|
upstream_bad:
|
|
if (headers_sent) {
|
|
(void)sse_error(fd, err.p != NULL ? err.p : "upstream failed");
|
|
(void)sse_done(fd);
|
|
} else {
|
|
error_json(&payload,
|
|
err.p != NULL ? err.p : "upstream failed");
|
|
sp_http_reply(fd, 502, "Bad Gateway", "application/json",
|
|
payload.p);
|
|
}
|
|
out:
|
|
sp_buf_free(&payload);
|
|
sp_buf_free(&answer);
|
|
sp_buf_free(&err);
|
|
tools_free(&tools);
|
|
sp_conv_free(&conv);
|
|
mcp_json_free(req);
|
|
}
|
|
|
|
static void
|
|
handle_models(int fd, const struct sp_gateway_opts *o)
|
|
{
|
|
struct sp_buf b;
|
|
|
|
sp_buf_init(&b);
|
|
sp_buf_puts(&b, "{\"object\":\"list\",\"data\":[{\"id\":\"");
|
|
(void)sp_json_escape(&b, o->model != NULL ? o->model : "splinter");
|
|
sp_buf_puts(&b, "\",\"object\":\"model\",\"created\":0,"
|
|
"\"owned_by\":\"splinter\"}]}");
|
|
sp_http_reply(fd, 200, "OK", "application/json", b.p);
|
|
sp_buf_free(&b);
|
|
}
|
|
|
|
/* ------------------------------------------------------------- the server */
|
|
|
|
static void
|
|
serve_one(int fd, const struct sp_gateway_opts *o, const char *token)
|
|
{
|
|
char hdr[SP_HTTP_HDR_MAX], method[16], path[256];
|
|
struct sp_buf body, payload;
|
|
const char *p;
|
|
size_t n;
|
|
|
|
if (sp_buf_init(&body) != 0)
|
|
return;
|
|
if (sp_http_read_request(fd, hdr, sizeof(hdr), &body,
|
|
SP_HTTP_BODY_MAX) != 0) {
|
|
sp_buf_init(&payload);
|
|
error_json(&payload, "cannot read the request");
|
|
sp_http_reply(fd, 400, "Bad Request", "application/json",
|
|
payload.p);
|
|
sp_buf_free(&payload);
|
|
sp_buf_free(&body);
|
|
return;
|
|
}
|
|
if (token != NULL) {
|
|
const char *auth = sp_http_header_value(hdr, "Authorization");
|
|
|
|
if (!sp_http_bearer_is(auth, token)) {
|
|
sp_buf_init(&payload);
|
|
error_json(&payload, "missing or wrong bearer token");
|
|
sp_http_reply(fd, 401, "Unauthorized", "application/json",
|
|
payload.p);
|
|
sp_buf_free(&payload);
|
|
sp_buf_free(&body);
|
|
return;
|
|
}
|
|
}
|
|
method[0] = path[0] = '\0';
|
|
p = hdr;
|
|
n = 0;
|
|
while (*p != '\0' && *p != ' ' && n + 1 < sizeof(method))
|
|
method[n++] = *p++;
|
|
method[n] = '\0';
|
|
while (*p == ' ')
|
|
p++;
|
|
n = 0;
|
|
while (*p != '\0' && *p != ' ' && n + 1 < sizeof(path))
|
|
path[n++] = *p++;
|
|
path[n] = '\0';
|
|
if (strcmp(method, "GET") == 0 &&
|
|
(strcmp(path, "/v1/models") == 0 ||
|
|
strcmp(path, "/models") == 0)) {
|
|
handle_models(fd, o);
|
|
} else if (strcmp(method, "POST") == 0 &&
|
|
(strcmp(path, "/v1/chat/completions") == 0 ||
|
|
strcmp(path, "/chat/completions") == 0)) {
|
|
handle_chat(fd, o, body.p != NULL ? body.p : "");
|
|
} else {
|
|
sp_buf_init(&payload);
|
|
error_json(&payload, "no such route");
|
|
sp_http_reply(fd, 404, "Not Found", "application/json",
|
|
payload.p);
|
|
sp_buf_free(&payload);
|
|
}
|
|
sp_buf_free(&body);
|
|
}
|
|
|
|
int
|
|
sp_openai_serve(const struct sp_gateway_opts *o, struct sp_buf *err)
|
|
{
|
|
struct sockaddr_in addr;
|
|
int s, one = 1;
|
|
struct sigaction sa;
|
|
const char *token;
|
|
|
|
if (o == NULL || o->reg == NULL || o->endpoint == NULL ||
|
|
o->model == NULL) {
|
|
sp_buf_puts(err, "gateway: no registry, endpoint or model");
|
|
return -1;
|
|
}
|
|
token = o->token != NULL && *o->token != '\0' ? o->token : NULL;
|
|
if (token == NULL && strncmp(o->ip != NULL ? o->ip : "127.",
|
|
"127.", 4) != 0) {
|
|
sp_buf_puts(err, "gateway: beyond loopback it needs "
|
|
"SPLINTER_GATEWAY_TOKEN: gw_run would give the network the "
|
|
"shell of this user");
|
|
return -1;
|
|
}
|
|
s = socket(AF_INET, SOCK_STREAM, 0);
|
|
if (s < 0) {
|
|
sp_buf_printf(err, "gateway: socket: %s", strerror(errno));
|
|
return -1;
|
|
}
|
|
(void)setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
|
|
memset(&addr, 0, sizeof(addr));
|
|
addr.sin_family = AF_INET;
|
|
addr.sin_port = htons((unsigned short)o->port);
|
|
if (inet_pton(AF_INET, o->ip != NULL ? o->ip : "127.0.0.1",
|
|
&addr.sin_addr) != 1) {
|
|
sp_buf_printf(err, "gateway: '%s' is not an address", o->ip);
|
|
close(s);
|
|
return -1;
|
|
}
|
|
if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
|
|
sp_buf_printf(err, "gateway: bind %s:%d: %s",
|
|
o->ip != NULL ? o->ip : "127.0.0.1", o->port,
|
|
strerror(errno));
|
|
close(s);
|
|
return -1;
|
|
}
|
|
if (listen(s, 8) != 0) {
|
|
sp_buf_printf(err, "gateway: listen: %s", strerror(errno));
|
|
close(s);
|
|
return -1;
|
|
}
|
|
/*
|
|
* A caller that closes its stream early must not kill the gateway with
|
|
* SIGPIPE; the write returns EPIPE and the request ends.
|
|
*/
|
|
(void)signal(SIGPIPE, SIG_IGN);
|
|
memset(&sa, 0, sizeof(sa));
|
|
sa.sa_handler = on_signal;
|
|
sigemptyset(&sa.sa_mask);
|
|
sigaction(SIGINT, &sa, NULL);
|
|
sigaction(SIGTERM, &sa, NULL);
|
|
fprintf(stderr, "splinter: OpenAI gateway on http://%s:%d/v1 "
|
|
"(model %s)\n", o->ip != NULL ? o->ip : "127.0.0.1", o->port,
|
|
o->model);
|
|
while (!g_stop) {
|
|
int fd = accept(s, NULL, NULL);
|
|
|
|
if (fd < 0) {
|
|
if (errno == EINTR)
|
|
continue;
|
|
sp_buf_printf(err, "gateway: accept: %s",
|
|
strerror(errno));
|
|
break;
|
|
}
|
|
(void)fcntl(fd, F_SETFD, FD_CLOEXEC);
|
|
{
|
|
int one_tcp = 1;
|
|
|
|
(void)setsockopt(fd, IPPROTO_TCP, TCP_NODELAY,
|
|
&one_tcp, sizeof(one_tcp));
|
|
}
|
|
serve_one(fd, o, token);
|
|
close(fd);
|
|
}
|
|
close(s);
|
|
return 0;
|
|
}
|