AxonHub System One API:通过 /v1/systemone 调用 TypeSafe Jev 决策推理模型

原创2026-10-12 09:33:472,306 阅读
文章标签:AI 应用API网关LLM 网关后端前端

AxonHub System One API:通过 /v1/systemone 调用 TypeSafe Jev 决策推理模型

AxonHub 原生支持 System One 决策推理 API,首发对接 TypeSafe 的 Jev 决策模型。System One 源于认知心理学中的"系统 1"思维(快速、直觉式、确定性决策):与逐 token 生成自由文本的常规生成式 LLM 不同,它面向结构化输入状态,输出快速、经过校准的概率化判断与分类。System One 是与 OpenAI Chat Completions、OpenAI Responses、Anthropic Messages、Embeddings、Rerank 平级的一等 API 格式,通过 POST /v1/systemone 和 POST /typesafe/v1/systemone 两个入口暴露。读完本文,你将掌握 System One 的请求/响应 Wire Format、三种决策原语(noul / choice / score)、完整的 cURL / Python / Go 调用示例,以及 AxonHub 中 TypeSafe 通道的配置、模型映射、故障转移行为,并能对照源码理解 AxonHub 是如何以"零伪装、零会话开销"的方式透传这些请求的。

重要前提:System One 不是 Chat Completion

  • System One 是原生的、一等公民的 API 格式,与 OpenAI Chat Completions、OpenAI Responses、Anthropic Messages、Embeddings、Rerank 地位相同。
  • 不支持通过 /v1/chat/completions 调用 Jev 模型。
  • 请求与响应严格遵循 System One 原生 Wire Format,没有任何伪装(masquerading)或会话(conversational)开销。

从源码结构可以印证这一点:/v1/systemone 与 /typesafe/v1/systemone 两个路由都直接注册到专门的 TypeSafe.SystemOne 处理器,独立于 OpenAI 的 chat/completions 路由,见 routes.go 与 routes.go:

// Native System One endpoint
openaiGroup.POST("/systemone", handlers.TypeSafe.SystemOne)
...
typesafeGroup := apiGroup.Group("/typesafe/v1")
typesafeGroup.POST("/systemone", handlers.TypeSafe.SystemOne)

请求类型与 API 格式在 constants.go 中被定义为独立的常量 RequestTypeSystemOne = "systemone" 和 APIFormatTypeSafeSystemOne = "typesafe/systemone",从协议层面就把 System One 与其他生成式接口隔离开来。

支持的端点与认证

  • POST /v1/systemone —— 原生 System One API(主入口)
  • POST /typesafe/v1/systemone —— TypeSafe 提供商命名空间别名

两个端点使用标准的 Bearer Token 认证:

  • 请求头:Authorization: Bearer <your-axonhub-api-key>
  • Content-Type:application/json

请求格式

请求体是一个包含 model、state、questions 三个字段的 JSON 对象:

{
  "model": "jev-latest",
  "state": {
    "user_id": "usr_94821",
    "recent_transactions": [
      { "amount": 12000, "currency": "USD", "country": "NG" },
      { "amount": 15, "currency": "USD", "country": "US" }
    ],
    "account_age_days": 2
  },
  "questions": {
    "is_fraud": {
      "type": "noul",
      "instructions": "Determine if this activity exhibits fraud or money laundering risk"
    },
    "risk_level": {
      "type": "choice",
      "instructions": "Classify transaction risk tier",
      "criteria": {
        "low": "Standard low-risk transaction",
        "medium": "Unusual amount or new account cross-border transaction",
        "high": "High risk of fraud or money laundering"
      }
    },
    "compliance_score": {
      "type": "score",
      "instructions": "Score overall compliance for this account",
      "criteria": [
        "Critically non-compliant",
        "Dubious, needs review",
        "Basically compliant",
        "Fully compliant"
      ]
    }
  }
}

参数说明

参数 类型 必填 说明
model string 是 目标模型名(如 jev-latest、jev-preview、jev-1.13.0,或配置好的模型映射别名)。
state string / object / array 是 待评估的上下文或实体。AxonHub 会原样保留对象与数组,不做有损的字符串化。
questions map<string, Question> 是 从问题标识符到问题定义的映射。

源码级的请求解析

入站转换逻辑位于 inbound.go。SystemOneInboundTransformer.TransformRequest 的行为与文档承诺一一对应:

  • 使用 json.NewDecoder 且开启 UseNumber(),将请求解码为 Wire 结构 systemOneWireRequest(定义见 model.go),其中 State 的 Go 类型是 any——这正是"保留对象和数组、不做有损字符串化"的实现基础;
  • 若请求携带 stream: true,直接返回错误 streaming is not supported for systemone requests(对应下文"已知限制"中的 HTTP 400);
  • 校验 model 非空、state 非 nil、questions 非空,任一缺失均返回 ErrInvalidRequest;
  • 最终组装为内部 llm.Request,打上 RequestType: llm.RequestTypeSystemOne 与 APIFormat: llm.APIFormatTypeSafeSystemOne 标签。

对应的内部数据模型定义在 systemone.go:SystemOneRequest(State any + Questions map[string]SystemOneQuestion),每个 SystemOneQuestion 含 Type、Instructions(string/object/array 均可)与可选的 Criteria。

三种决策原语(Three Decision Primitives)

每个问题定义(question specification)都必须声明一个 type,且只能是以下三种原语之一:

1. noul(真伪判断)

在二元判断语境下评估某个陈述或断言是否为真。

  • 请求定义:
    • type: "noul"
    • instructions: 引导评估的字符串 / 对象 / 数组
    • criteria: 可选的 真/假 判分标准(rubric)
  • 响应字段:
    • noul: float(0.0 ~ 1.0),表示校准后的"为真"概率。按照官方规范,noul 已经是一个完整的一维伯努利分布,因此不会再返回单独的 choice、probabilities 或 confidence 字段。

2. choice(分类选择)

从预定义的离散选项中选出胜出类别。

  • 请求定义:
    • type: "choice"
    • instructions: 字符串 / 对象 / 数组
    • criteria: map<string, any>,定义候选选项及其描述
  • 响应字段:
    • choice: string,被选中的选项标签
    • probabilities: Record<string, float>,跨选项的归一化概率分布
    • confidence: float(0.0 ~ 1.0),整体决策置信度

3. score(评分量表打分)

在有序定性档位(rubric 阶梯)之间插值出连续的数值分数。

  • 请求定义:
    • type: "score"
    • instructions: 字符串 / 对象 / 数组
    • criteria: 有序数组,即 rubric 档位列表
  • 响应字段:
    • score: float,连续的概率加权分数
    • legend: 档位描述
    • probabilities: Record<string, float>,跨档位索引的概率分布
    • confidence: float(0.0 ~ 1.0),确定度分数

源码级的响应模型

响应的答案容器 SystemOneAnswer 定义在 systemone.go,字段恰好覆盖三种原语的返回面:Choice、Noul、Score、Legend、Probabilities、Confidence。值得一提的是它的自定义 UnmarshalJSON(systemone.go):除上述已知字段外,上游返回的任何未知字段都会被收进 Extra map<a href="https://link.gitcode.com/i/2b9a82762f61b1d2b2e8917f2f0dffff" target="_blank">string]json.RawMessage 并在序列化时原样回写(见 [systemone.go)。这意味着 AxonHub 对上游协议演进是前向兼容的——即使 TypeSafe 未来给答案增加新字段,网关也不会把它们丢掉。

响应格式

{
  "model": "jev-latest",
  "answers": {
    "is_fraud": {
      "type": "noul",
      "noul": 0.892
    },
    "risk_level": {
      "type": "choice",
      "choice": "high",
      "probabilities": {
        "low": 0.012,
        "medium": 0.108,
        "high": 0.880
      },
      "confidence": 0.88
    },
    "compliance_score": {
      "type": "score",
      "score": 1.25,
      "legend": [
        "Critically non-compliant",
        "Dubious, needs review",
        "Basically compliant",
        "Fully compliant"
      ],
      "probabilities": {
        "0": 0.75,
        "1": 0.25,
        "2": 0.00,
        "3": 0.00
      },
      "confidence": 0.75
    }
  },
  "usage": {
    "input_tokens": 142,
    "output_tokens": 3
  }
}

注意 probabilities 在 noul 答案中缺失、choice/score 中完整——这与"每种原语只返回自己那组字段"的规范完全一致。

usage 的双向映射

AxonHub 会把 usage.input_tokens 和 usage.output_tokens 映射为内部 prompt / completion 指标,用于请求审计与计费,同时在对外响应中保留原生字段名。这个双向转换可以在源码中精确定位:

  • 上游 → 内部:outbound.go 中 PromptTokens = InputTokens、CompletionTokens = OutputTokens,并计算 TotalTokens = input + output;
  • 内部 → 上游:inbound.go 中再把 Usage.PromptTokens / Usage.CompletionTokens 还原为 Wire 层的 input_tokens / output_tokens 回写给调用方。

实战示例

cURL

curl -X POST "http://localhost:8090/v1/systemone" \
  -H "Authorization: Bearer your-axonhub-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "jev-latest",
    "state": "Customer says: I received the wrong size and want a replacement.",
    "questions": {
      "intent": {
        "type": "choice",
        "instructions": "Classify user intent",
        "criteria": {
          "refund": "Customer wants money back",
          "exchange": "Customer wants a replacement",
          "inquiry": "General product inquiry"
        }
      }
    }
  }'

Python

import requests

url = "http://localhost:8090/v1/systemone"
headers = {
    "Authorization": "Bearer your-axonhub-api-key",
    "Content-Type": "application/json"
}

payload = {
    "model": "jev-latest",
    "state": "The user reported receiving a damaged parcel upon delivery.",
    "questions": {
        "is_complaint": {
            "type": "noul",
            "instructions": "Determine whether this input constitutes a formal customer complaint."
        },
        "urgency": {
            "type": "choice",
            "instructions": "Determine priority urgency level",
            "criteria": {
                "low": "Non-urgent standard issue",
                "high": "Damaged goods, immediate action needed"
            }
        }
    }
}

response = requests.post(url, headers=headers, json=payload)
data = response.json()

print(f"Complaint Probability: {data['answers']['is_complaint']['noul']}")
print(f"Urgency Choice: {data['answers']['urgency']['choice']}")
print(f"Confidence: {data['answers']['urgency']['confidence']}")

Go

package main

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

func main() {
	payload := map[string]any{
		"model": "jev-latest",
		"state": "Order payment delayed by 48 hours",
		"questions": map[string]any{
			"action": map[string]any{
				"type":         "choice",
				"instructions": "Select next system operation",
				"criteria": map[string]string{
					"wait":   "Keep waiting for gateway callback",
					"cancel": "Cancel order and release inventory",
				},
			},
		},
	}
	body, _ := json.Marshal(payload)

	req, _ := http.NewRequestWithContext(context.Background(), "POST", "http://localhost:8090/v1/systemone", bytes.NewBuffer(body))
	req.Header.Set("Authorization", "Bearer your-axonhub-api-key")
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	respBody, _ := io.ReadAll(resp.Body)
	fmt.Println(string(respBody))
}

通道配置与网关特性

1. TypeSafe 通道配置

在 AxonHub 中添加通道时的配置约定如下:

  • Provider:选择 TypeSafe
  • Base URL:默认 https://api.typesafe.ai/v1
  • Protocol Endpoint:严格锁定为 typesafe/systemone(不可改为其他协议)
  • Default Models:预置 jev-latest、jev-preview、jev-1.13.0
  • API Keys:支持单个或多个 API Key,可选 sticky / round-robin 轮换策略

这些默认值在前端通道配置中可以直接找到:config_channels.ts 中 typesafe 条目的 baseURL 与 defaultModels 和文档一致。而"协议端点锁定"则由 protocol-options.ts 保证:对 typesafe 通道类型,可配置的 API 格式列表只返回 ['typesafe/systemone'],其他所有通道类型反而会被显式过滤掉该格式——System One 是 TypeSafe 通道的专属协议。

后端的通道端点校验测试也印证了这一约束,见 channel_endpoint_typesafe_test.go:TypeSafe 通道携带 typesafe/systemone 端点应通过校验;OpenAI 等非 TypeSafe 通道携带该格式应失败;TypeSafe 通道的默认端点只能是 typesafe/systemone。

另外,出站转换器 outbound.go 在 Base URL 为空时会回落到 https://api.typesafe.ai/v1,并通过 NormalizeBaseURL 归一化 URL,最终请求路径由 buildURL()(outbound.go)拼出 <BaseURL>/systemone。

2. 模型映射(Model Mapping)

客户端请求可以通过模型映射使用抽象别名:

  • 请求模型:"model": "jev"
  • 通道映射规则:jev -> jev-latest
  • AxonHub 只修改 "model" 字节段,"state" 与 "questions" 保持**透传(pass-through)**模式

透传行为在源码中有明确体现:OutboundTransformer 实现了 AllowPassThroughBody(outbound.go),只要请求类型是 RequestTypeSystemOne 就允许原始请求体透传,配合网关层仅替换 model 字节的映射机制,保证业务负载在网关内零变形。

3. 故障转移与重试

  • 429(Rate Limit)/ 529(Overloaded):触发重试或切换到其他 TypeSafe 通道(failover)。
  • 401(Auth Failed)/ 422(Unprocessable Entity):直接透传给调用方,不做多余的重试。

AxonHub 的调度层对 429 类限流错误有专门的识别与处理路径(如 channel_queue_error.go 中的限流错误构造、channel_endpoint_detect.go 中对 StatusTooManyRequests 的分支),这是上述 429/529 自动重试与切换能力的落地位置。而 401/422 这类"重试也不会变好"的错误则直接透传,避免浪费配额。

已知限制

  1. 不支持流式:System One 是确定性的单步评估。携带 stream: true 的请求会被拒绝并返回 HTTP 400。源码中入站(inbound.go)、入站流聚合与出站 TransformStream(outbound.go)均显式返回 systemone does not support streaming,流式能力在协议层被彻底关闭。
  2. 不支持 Chat 生成参数:不要传 messages、temperature、top_p、max_tokens 或 tools——这些字段不属于 System One Wire Format,网关的 Wire 结构(model.go)中只定义了 model、state、questions 与 stream 字段。

小结

System One 让 AxonHub 从"生成式 LLM 网关"扩展到了"决策推理网关":noul/choice/score 三种原语覆盖了真伪判断、分类选择与量表打分三类高频风控/合规场景,而 Wire Format 的严格透传、usage 的双向映射、typesafe/systemone 的协议锁定、429/529 的自动故障转移,共同保证了这条链路在生产环境中的可观测性与可用性。所有关键实现都集中在这几处,便于二次开发或对接自定义上游:

关注点 文件位置
路由注册(/v1/systemone、/typesafe/v1/systemone) internal/server/routes.go
入站转换(参数校验、stream 拒绝、usage 还原) llm/transformer/typesafe/inbound.go
出站转换(URL 构造、Bearer 鉴权、透传、usage 映射) llm/transformer/typesafe/outbound.go
Wire 请求/响应结构 llm/transformer/typesafe/model.go
内部数据模型(含未知字段前向兼容) llm/systemone.go
TypeSafe 通道默认配置 frontend/src/features/channels/data/config_channels.ts
协议端点锁定 frontend/src/features/channels/data/protocol-options.ts
登录后查看全文
axonhub