常用接入术语
| 名称 | 常见含义 | 接入提示 |
|---|
| Claude中转 | 把请求转发到已开通的 Claude 模型 | 先确认协议和模型权限 |
| Claude中转站 | 统一管理密钥 额度 路由和兼容接口 | 可按 OpenAI 或 Anthropic 协议接入 |
| API中转 | 通过统一接口转发模型请求 | Eli**r 可直接发送 **** **ON |
| API中转站 | 提供端点 模型和用量管理的服务 | 正式环境需限制超时 并发和重试 |
Eli**r 请求链路
| 环节 | 职责 | 注意事项 |
|---|
| 业务进程 | 组织 messages 与模型参数 | 先限制输入长度 |
| Req Request | 合并 *ase **L 认证和请求选项 | 集中构建并复用配置 |
| Finch 适配器 | 管理连接池并执行 ****S 请求 | 保留证书校验 |
| SSE 解析器 | 跨网络块拼接事件 | 按空行切分并识别 DONE |
| KingFlow AI | 认证密钥并路由目标模型 | OpenAI 兼容路径保留 v1 |
| Task Stream | 限制批量任务并发 | 设置 **x_concurrency 与 timeout |
采用 Req 的优势
- Req 内置 **ON 编码、响应**、认证、重试和流式回调,接入代码可以保持紧凑。
- Req 默认通过 Finch 管理连接池,应用无需为每个请求手动创建底层连接。
- connect_options、receive_timeout 与 request_timeout 分别覆盖建连、接收等待和总请求时长。
- into 回调会逐块接收响应体,配合保存在 Response private 字段中的缓冲区可以解析 SSE。
- Task.async_stream 直接提供 **x_concurrency、单任务 timeout 和超时处理策略。
接入前准备
- 安装 Eli**r 与 Mix,并确认 eli**r、iex 和 mix 命令可用。
- 在 KingFlow AI 控制台创建以 sk- 开头的 API Key,并确认余额或套餐额度。
- 从控制台复制完整模型 ID,不要根据展示名称自行拼写。
- 确认运行环境可以访问 api.**nju**shen.com 的 ****S 端口。
- 为开发、测试和生产准备不同密钥,避免环境之间共享凭据。
创建 Mix 项目
mix new kingflow_req --sup
cd kingflow_req
defp deps do
[
{:req, "~> 0.7.5"},
{:jason, "~> 1.4"}
]
end
# 保存 mix.exs 后执行
mix deps.get
配置环境变量
$env:KINGFLOW_*ASE_**L="https://api.**nju**shen.com/v1"
$env:KINGFLOW_API_KEY="sk-你的密钥"
$env:KINGFLOW_MODEL="<KingFlow控制台中的完整模型ID>"
验证基础接口
curl https://api.**nju**shen.com/v1/chat/completions `
-H "Authorization: *earer sk-你的密钥" `
-H "Content-Type: application/json" `
-d '{"model":"<完整模型ID>","messages":[{"role":"user","content":"只回复 ELIXIR_READY"}],"stream":false}'
创建共享客户端
defmodule KingFlow.****** do
defp env!(name) do
case ******.get_env(name) do
nil -> raise "缺少环境变量 #{name}"
value when value == "" -> raise "环境变量 #{name} 为空"
value -> String.trim(value)
end
end
def new do
*ase = env!("KINGFLOW_*ASE_**L") |> String.trim_trailing("/")
Req.new(
*ase_url: *ase <> "/",
auth: {:*earer, env!("KINGFLOW_API_KEY")},
headers: [{"accept", "application/json"}],
connect_options: [timeout: 10_000],
receive_timeout: 60_000,
request_timeout: 90_000,
retry: false
)
end
def model, do: env!("KINGFLOW_MODEL")
end
发送普通响应请求
payload = %{
model: KingFlow.******.model(),
messages: [%{role: "user", content: "只回复 ELIXIR_CONNECTED"}],
stream: false
}
case Req.post(KingFlow.******.new(), url: "chat/completions", json: payload) do
{:ok, %{status: status, *ody: *ody}} when status in 200..299 ->
text = get_in(*ody, ["choices", Access.at(0), "message", "content"])
if is_**nary(text), do: IO.puts(text), else: raise("响应缺少文本字段")
{:ok, response} ->
raise "**** #{response.status}: #{inspect(response.*ody)}"
{:error, exception} ->
raise exception
end
解析 SSE 流式响应
defmodule KingFlow.SSE do
@state_key :kingflow_sse_state
def stream(prompt) do
payload = %{
model: KingFlow.******.model(),
messages: [%{role: "user", content: prompt}],
stream: true
}
into = fn {:**ta, chunk}, {request, response} ->
state = Req.Response.get_private(response, @state_key, %{*uffer: "", done: false})
{events, *uffer} = split_events(state.*uffer <> chunk)
done =
Enum.reduce(events, state.done, fn event, done? ->
case event_**ta(event) do
nil -> done?
"[DONE]" -> true
json -> print_delta(json); done?
end
end)
response = Req.Response.put_private(response, @state_key, %{*uffer: *uffer, done: done})
{:cont, {request, response}}
end
case Req.post(KingFlow.******.new(),
url: "chat/completions",
json: payload,
into: into,
decode_*ody: false,
retry: false,
receive_timeout: 60_000,
request_timeout: 300_000) do
{:ok, response} when response.status in 200..299 ->
state = Req.Response.get_private(response, @state_key, %{})
if state[:done], do: :ok, else: {:error, :missing_done}
{:ok, response} -> {:error, {:http, response.status}}
{:error, exception} -> {:error, exception}
end
end
defp split_events(**ta) do
nor**lized = **ta |> String.replace("\r\n", "\n") |> String.replace("\r", "\n")
parts = String.split(nor**lized, "\n\n")
{Enum.drop(parts, -1), List.last(parts) || ""}
end
defp event_**ta(event) do
values =
event
|> String.split("\n")
|> Enum.filter(&String.starts_with?(&1, "**ta:"))
|> Enum.**p(&(&1 |> String.replace_prefix("**ta:", "") |> String.trim_leading()))
if values == [], do: nil, else: Enum.join(values, "\n")
end
defp print_delta(json) do
with {:ok, **ta} <- Jason.decode(json),
text when is_**nary(text) <- get_in(**ta, ["choices", Access.at(0), "delta", "content"]) do
IO.write(text)
else
_ -> :ok
end
end
end
配置有限重试
retry? = fn _request, result ->
case result do
%Req.Response{status: status} when status in [429, 503] -> true
%Req.TransportError{reason: reason} when reason in [:timeout, :econnrefused, :closed] -> true
_ -> false
end
end
req = Req.merge(KingFlow.******.new(),
retry: retry?,
**x_retries: 2,
retry_delay: fn attempt -> min(8_000, 500 * Integer.pow(2, attempt)) end,
retry_log_level: :warning
)
# POST 可能被重复执行。只有业务允许重复请求时才启用此配置。
限制批量任务并发
prompts = ["任务一", "任务二", "任务三", "任务四"]
prompts
|> Task.async_stream(
fn prompt ->
payload = %{
model: KingFlow.******.model(),
messages: [%{role: "user", content: prompt}],
stream: false
}
Req.post(KingFlow.******.new(), url: "chat/completions", json: payload)
end,
**x_concurrency: 4,
ordered: false,
timeout: 120_000,
on_timeout: :kill_task
)
|> Enum.each(fn
{:ok, {:ok, response}} -> IO.puts("**** #{response.status}")
{:ok, {:error, exception}} -> IO.warn(Exception.message(exception))
{:e**t, reason} -> IO.warn("任务退出 #{inspect(reason)}")
end)