use async_trait::async_trait;
use serde_json::{Value, json};
use std::sync::Arc;
use std::time::Duration;
use vlorql_core::errors::{ConfigErrorKind, LlmErrorKind, VlorQLError};
use vlorql_core::schema::QueryPlan;
use crate::schema::compact_query_plan_schema;
use crate::sse::{transport_error, truncate};
use crate::{
DEFAULT_MAX_ATTEMPTS, LlmClient, LlmConfig, LlmProvider, RetryableHttpClient, StreamResult,
TokenUsage,
};
const DEFAULT_API_BASE: &str = "https://open.bigmodel.cn/api/paas/v4/chat/completions";
const ZHIPU_API_KEY_ENV: &str = "ZHIPU_API_KEY";
const DEFAULT_MAX_TOKENS: u32 = 4_096;
const MIN_MAX_TOKENS: u32 = 256;
#[derive(Clone)]
pub struct ZhipuClient {
config: LlmConfig,
client: reqwest::Client,
api_key: String,
}
impl std::fmt::Debug for ZhipuClient {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("ZhipuClient")
.field("api_key", &"[REDACTED]")
.field("provider", &self.config.provider)
.field("model", &self.config.model)
.field("api_base", &self.config.api_base)
.field("max_retries", &self.max_attempts())
.finish()
}
}
impl ZhipuClient {
pub fn new(config: LlmConfig) -> Result<Self, VlorQLError> {
if config.model.trim().is_empty() {
return Err(VlorQLError::config(
ConfigErrorKind::EmptyModel,
json!({"provider": LlmProvider::Zhipu, "field": "model"}),
));
}
let api_key = config
.api_key
.clone()
.or_else(|| std::env::var(ZHIPU_API_KEY_ENV).ok())
.map(|value| value.trim().to_owned())
.filter(|value| !value.is_empty())
.ok_or_else(|| {
VlorQLError::config(
ConfigErrorKind::MissingApiKey {
provider: "zhipu".to_owned(),
},
json!({
"provider": LlmProvider::Zhipu,
"env": ZHIPU_API_KEY_ENV,
}),
)
})?;
let timeout = Duration::from_secs(config.timeout_seconds.max(1));
let client = reqwest::Client::builder()
.timeout(timeout)
.build()
.unwrap_or_else(|_| reqwest::Client::new());
Ok(Self {
config,
client,
api_key,
})
}
fn endpoint(&self) -> String {
self.config
.api_base
.clone()
.unwrap_or_else(|| DEFAULT_API_BASE.to_owned())
}
fn effective_max_tokens(&self) -> u32 {
if self.config.max_tokens == 0 {
DEFAULT_MAX_TOKENS
} else if self.config.max_tokens < MIN_MAX_TOKENS {
MIN_MAX_TOKENS
} else {
self.config.max_tokens
}
}
fn supports_strict_json_schema(&self) -> bool {
if let Some(override_value) = self.config.extra.get("strict_json_schema")
&& let Some(flag) = override_value.as_bool()
{
return flag;
}
let model = self.config.model.to_ascii_lowercase();
model.starts_with("glm-4.7")
|| model.starts_with("glm-4.8")
|| model.starts_with("glm-4.9")
|| model.starts_with("glm-5")
|| model.starts_with("glm-6")
}
fn build_request_body(
&self,
question: &str,
system_prompt: &str,
stream: bool,
temperature: Option<f32>,
) -> Value {
let response_format = if self.supports_strict_json_schema() {
json!({
"type": "json_schema",
"json_schema": {
"name": "QueryPlan",
"strict": true,
"schema": compact_query_plan_schema(),
},
})
} else {
json!({"type": "json_object"})
};
let model = self.config.model.to_ascii_lowercase();
let supports_tool_stream = model.starts_with("glm-5") || model.starts_with("glm-6");
let mut body = json!({
"model": self.config.model,
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": question},
],
"temperature": temperature.unwrap_or(self.config.temperature),
"max_tokens": self.effective_max_tokens(),
"response_format": response_format,
});
if stream {
body["stream"] = Value::Bool(true);
if supports_tool_stream {
body["tool_stream"] = Value::Bool(true);
}
}
body
}
}
#[async_trait]
impl RetryableHttpClient for ZhipuClient {
fn max_attempts(&self) -> usize {
usize::try_from(self.config.max_retries.max(1)).unwrap_or(DEFAULT_MAX_ATTEMPTS)
}
fn provider_label(&self) -> &'static str {
"zhipu"
}
fn parse_response(&self, body: &str) -> Result<QueryPlan, VlorQLError> {
parse_completion_payload(body)
}
async fn send_request(
&self,
endpoint: &str,
body: &Value,
) -> Result<reqwest::Response, VlorQLError> {
self.client
.post(endpoint)
.bearer_auth(&self.api_key)
.header("accept", "text/event-stream")
.json(body)
.send()
.await
.map_err(|error| transport_error(&error))
}
}
#[async_trait]
impl LlmClient for ZhipuClient {
async fn generate_plan(
&self,
question: &str,
system_prompt: &str,
temperature: Option<f32>,
) -> Result<(QueryPlan, TokenUsage), VlorQLError> {
let endpoint = self.endpoint();
let body = self.build_request_body(question, system_prompt, false, temperature);
self.generate_with_retry(&endpoint, &body).await
}
async fn stream_plan(
&self,
question: String,
system_prompt: String,
) -> Result<StreamResult, VlorQLError> {
let endpoint = self.endpoint();
let body = self.build_request_body(&question, &system_prompt, true, None);
let usage = Arc::new(tokio::sync::Mutex::new(None));
let usage_clone = Arc::clone(&usage);
let extract = move |data: &Value| {
if let Some(u) = data.get("usage")
&& let Ok(mut guard) = usage_clone.try_lock()
{
*guard = Some(TokenUsage {
prompt_tokens: u.get("prompt_tokens").and_then(|v| v.as_u64()).unwrap_or(0),
completion_tokens: u
.get("completion_tokens")
.and_then(|v| v.as_u64())
.unwrap_or(0),
});
}
data.pointer("/choices/0/delta/content")
.and_then(|v| v.as_str().map(String::from))
};
let stream = self.stream_with_sse(&endpoint, &body, extract).await?;
Ok(StreamResult { stream, usage })
}
fn provider(&self) -> LlmProvider {
LlmProvider::Zhipu
}
fn config(&self) -> &LlmConfig {
&self.config
}
}
fn parse_completion_payload(body: &str) -> Result<QueryPlan, VlorQLError> {
let value: Value = serde_json::from_str(body).map_err(|error| {
VlorQLError::llm(
LlmErrorKind::ParseError {
details: format!("Zhipu response is not valid JSON: {error}"),
},
json!({
"source": "zhipu_response",
"body": truncate(body, 1024),
}),
)
})?;
if let Some(error) = value.get("error") {
return Err(VlorQLError::llm(
LlmErrorKind::ApiError {
status: 0,
message: error
.get("message")
.and_then(Value::as_str)
.unwrap_or("zhipu returned an error")
.to_owned(),
},
json!({"source": "zhipu_error", "error": error}),
));
}
let content = value
.get("choices")
.and_then(Value::as_array)
.and_then(|choices| choices.first())
.and_then(|choice| choice.get("message"))
.and_then(|message| message.get("content"))
.and_then(Value::as_str)
.ok_or_else(|| {
VlorQLError::llm(
LlmErrorKind::ParseError {
details: "Zhipu response did not contain choices[0].message.content".to_owned(),
},
json!({"source": "zhipu_response"}),
)
})?;
crate::parse_llm_response(content).map_err(|error| {
VlorQLError::llm(
LlmErrorKind::ParseError {
details: format!("assistant content is not a valid QueryPlan: {error}"),
},
json!({
"source": "zhipu_content",
"content": truncate(content, 4096),
}),
)
})
}
#[cfg(test)]
mod tests {
use super::*;
use mockito::{Matcher, Server};
use vlorql_core::schema::{FromClause, Projection, QueryPlan};
fn plan() -> QueryPlan {
QueryPlan {
select: vec![Projection::Column {
table: Some("users".to_owned()),
column: "id".to_owned(),
alias: None,
}],
from: FromClause::table("users".to_owned(), Some("t1".to_owned())),
r#where: None,
group_by: None,
having: None,
order_by: None,
limit: None,
offset: None,
joins: None,
ctes: None,
distinct: false,
distinct_on: None,
set_operation: None,
}
}
fn zhipu_config(model: &str) -> LlmConfig {
LlmConfig {
provider: LlmProvider::Zhipu,
api_key: Some("test-key".to_owned()),
api_base: Some("http://127.0.0.1:0/v4/chat/completions".to_owned()),
model: model.to_owned(),
max_tokens: 1024,
temperature: 0.0,
timeout_seconds: 60,
max_retries: 1,
extra: std::collections::HashMap::new(),
}
}
fn chat_response(plan: &QueryPlan) -> String {
json!({
"id": "chatcmpl-1",
"model": "glm-4.7",
"choices": [{
"index": 0,
"message": {
"role": "assistant",
"content": serde_json::to_string(plan).expect("plan should serialize"),
},
"finish_reason": "stop",
}],
"usage": {"prompt_tokens": 1, "completion_tokens": 2, "total_tokens": 3},
})
.to_string()
}
#[tokio::test]
async fn zhipu_client_uses_strict_json_schema_for_glm_4_7() {
let mut server = Server::new_async().await;
let expected = plan();
let mock = server
.mock("POST", "/v4/chat/completions")
.match_body(Matcher::Regex(
r#""model":"glm-4\.7".*"name":"QueryPlan".*"strict":true"#.to_owned(),
))
.with_status(200)
.with_body(chat_response(&expected))
.create_async()
.await;
let config = LlmConfig {
api_base: Some(format!("{}/v4/chat/completions", server.url())),
..zhipu_config("glm-4.7")
};
let client = ZhipuClient::new(config).expect("client should build");
let request_body = client.build_request_body("show users", "system", false, None);
assert_eq!(request_body["model"], "glm-4.7");
assert_eq!(request_body["temperature"], 0.0);
assert_eq!(request_body["response_format"]["type"], "json_schema");
assert_eq!(
request_body["response_format"]["json_schema"]["name"],
"QueryPlan"
);
assert_eq!(
request_body["response_format"]["json_schema"]["strict"],
true
);
let (actual, _usage) = client
.generate_plan("show users", "system", None)
.await
.expect("zhipu plan should parse");
assert_eq!(actual, expected);
assert_eq!(client.provider(), LlmProvider::Zhipu);
let config_ref = client.config();
assert_eq!(config_ref.model, "glm-4.7");
mock.assert_async().await;
}
#[tokio::test]
async fn zhipu_client_falls_back_to_json_object_for_older_models() {
let mut server = Server::new_async().await;
let expected = plan();
let mock = server
.mock("POST", "/v4/chat/completions")
.match_body(Matcher::Regex(
r#""model":"glm-4".*"response_format".*"type":"json_object""#.to_owned(),
))
.with_status(200)
.with_body(chat_response(&expected))
.create_async()
.await;
let config = LlmConfig {
api_base: Some(format!("{}/v4/chat/completions", server.url())),
..zhipu_config("glm-4")
};
let client = ZhipuClient::new(config).expect("client should build");
let request_body = client.build_request_body("q", "s", false, None);
assert_eq!(request_body["model"], "glm-4");
assert_eq!(request_body["response_format"]["type"], "json_object");
let (actual, _usage) = client
.generate_plan("q", "s", None)
.await
.expect("response");
assert_eq!(actual, expected);
mock.assert_async().await;
}
#[tokio::test]
async fn zhipu_client_converts_error_response() {
let mut server = Server::new_async().await;
let body = json!({
"error": {"code": "invalid_api_key", "message": "bad key"}
})
.to_string();
let mock = server
.mock("POST", "/v4/chat/completions")
.with_status(401)
.with_body(body)
.create_async()
.await;
let config = LlmConfig {
api_base: Some(format!("{}/v4/chat/completions", server.url())),
..zhipu_config("glm-4.7")
};
let client = ZhipuClient::new(config).expect("client should build");
let error = client
.generate_plan("hi", "system", None)
.await
.expect_err("401 should be reported");
assert_eq!(error.error_code(), "L001");
mock.assert_async().await;
}
#[tokio::test]
async fn zhipu_client_converts_invalid_plan_to_llm_parse_error() {
let mut server = Server::new_async().await;
let body = json!({
"choices": [{"message": {"role": "assistant", "content": r#"{"unexpected":true}"#}}]
})
.to_string();
let mock = server
.mock("POST", "/v4/chat/completions")
.with_status(200)
.with_body(body)
.create_async()
.await;
let config = LlmConfig {
api_base: Some(format!("{}/v4/chat/completions", server.url())),
..zhipu_config("glm-4.7")
};
let client = ZhipuClient::new(config).expect("client should build");
let error = client
.generate_plan("hi", "system", None)
.await
.expect_err("invalid plan should fail");
assert_eq!(error.error_code(), "L003");
mock.assert_async().await;
}
#[tokio::test]
async fn zhipu_client_stream_emits_delta_chunks() {
use futures::StreamExt;
let mut server = Server::new_async().await;
let body = [
format!(
"data: {}\n\n",
json!({
"id": "1",
"choices": [{"delta": {"content": "hello "}}],
})
),
format!(
"data: {}\n\n",
json!({
"id": "1",
"choices": [{"delta": {"content": "world"}}],
})
),
"data: [DONE]\n".to_owned(),
]
.join("");
let mock = server
.mock("POST", "/v4/chat/completions")
.match_header("accept", "text/event-stream")
.with_status(200)
.with_header("content-type", "text/event-stream")
.with_body(body)
.create_async()
.await;
let config = LlmConfig {
api_base: Some(format!("{}/v4/chat/completions", server.url())),
..zhipu_config("glm-4.7")
};
let client = ZhipuClient::new(config).expect("client should build");
let body = client.build_request_body("hi", "system", true, None);
assert_eq!(body["stream"], true);
let mut result = client
.stream_plan("hi".to_owned(), "system".to_owned())
.await
.expect("stream should be produced");
let mut combined = String::new();
while let Some(chunk) = result.stream.next().await {
combined.push_str(&chunk.expect("chunk should be Ok"));
}
assert_eq!(combined, "hello world");
mock.assert_async().await;
}
#[tokio::test]
async fn zhipu_client_stream_propagates_http_error() {
let mut server = Server::new_async().await;
let mock = server
.mock("POST", "/v4/chat/completions")
.with_status(500)
.with_body(r#"{"error":{"message":"down"}}"#)
.create_async()
.await;
let config = LlmConfig {
api_base: Some(format!("{}/v4/chat/completions", server.url())),
..zhipu_config("glm-4.7")
};
let client = ZhipuClient::new(config).expect("client should build");
let outcome = client
.stream_plan("hi".to_owned(), "system".to_owned())
.await;
let err = match outcome {
Ok(_) => panic!("500 should produce an error"),
Err(error) => error,
};
assert_eq!(err.error_code(), "L001");
mock.assert_async().await;
}
#[test]
fn zhipu_client_requires_api_key() {
let key_backup = std::env::var(ZHIPU_API_KEY_ENV).ok();
unsafe { std::env::remove_var(ZHIPU_API_KEY_ENV) };
let mut config = zhipu_config("glm-4.7");
config.api_key = None;
config.api_base = None;
let error = match ZhipuClient::new(config) {
Ok(client) => {
if let Some(previous) = key_backup {
unsafe { std::env::set_var(ZHIPU_API_KEY_ENV, previous) };
}
panic!("missing api key should fail; got client {client:?}");
}
Err(error) => {
if let Some(previous) = key_backup {
unsafe { std::env::set_var(ZHIPU_API_KEY_ENV, previous) };
}
error
}
};
assert_eq!(error.error_code(), "G004");
}
#[tokio::test]
async fn zhipu_client_reads_api_key_from_env() {
let mut server = Server::new_async().await;
let expected = plan();
let mock = server
.mock("POST", "/v4/chat/completions")
.match_header("authorization", "Bearer env-key")
.with_status(200)
.with_body(chat_response(&expected))
.create_async()
.await;
let key_backup = std::env::var(ZHIPU_API_KEY_ENV).ok();
struct RestoreEnv(Option<String>);
impl Drop for RestoreEnv {
fn drop(&mut self) {
unsafe {
match self.0.take() {
Some(previous) => std::env::set_var(ZHIPU_API_KEY_ENV, previous),
None => std::env::remove_var(ZHIPU_API_KEY_ENV),
}
}
}
}
let _guard = RestoreEnv(key_backup.clone());
unsafe {
std::env::set_var(ZHIPU_API_KEY_ENV, "env-key");
}
let mut config = zhipu_config("glm-4.7");
config.api_key = None;
config.api_base = Some(format!("{}/v4/chat/completions", server.url()));
let client = ZhipuClient::new(config).expect("client should build from env var");
let (actual, _usage) = client
.generate_plan("q", "s", None)
.await
.expect("env-keyed request should succeed");
assert_eq!(actual, expected);
mock.assert_async().await;
}
#[test]
fn zhipu_client_effective_max_tokens_floors_low_values() {
let mut config = zhipu_config("glm-4.7");
config.max_tokens = 0;
config.api_base = None;
let client = ZhipuClient::new(config).expect("client should build");
assert_eq!(client.effective_max_tokens(), DEFAULT_MAX_TOKENS);
let mut config = zhipu_config("glm-4.7");
config.max_tokens = 64;
config.api_base = None;
let client = ZhipuClient::new(config).expect("client should build");
assert_eq!(client.effective_max_tokens(), MIN_MAX_TOKENS);
}
#[test]
fn zhipu_client_endpoint_uses_default_when_unset() {
let mut config = zhipu_config("glm-4.7");
config.api_base = None;
let client = ZhipuClient::new(config).expect("client should build");
assert_eq!(client.endpoint(), DEFAULT_API_BASE);
}
#[test]
fn zhipu_client_supports_strict_json_schema_detection() {
let mut config = zhipu_config("glm-3-turbo");
config.api_base = None;
let client = ZhipuClient::new(config).expect("client should build");
assert!(!client.supports_strict_json_schema());
let mut config = zhipu_config("glm-4");
config.api_base = None;
let client = ZhipuClient::new(config).expect("client should build");
assert!(!client.supports_strict_json_schema());
let mut config = zhipu_config("glm-4.7");
config.api_base = None;
let client = ZhipuClient::new(config).expect("client should build");
assert!(client.supports_strict_json_schema());
let mut config = zhipu_config("glm-5-air");
config.api_base = None;
let client = ZhipuClient::new(config).expect("client should build");
assert!(client.supports_strict_json_schema());
let mut config = zhipu_config("glm-4.6");
config.api_base = None;
config
.extra
.insert("strict_json_schema".to_owned(), Value::Bool(true));
let client = ZhipuClient::new(config).expect("client should build");
assert!(client.supports_strict_json_schema());
let mut config = zhipu_config("glm-4.7");
config.api_base = None;
config
.extra
.insert("strict_json_schema".to_owned(), Value::Bool(false));
let client = ZhipuClient::new(config).expect("client should build");
assert!(!client.supports_strict_json_schema());
}
#[test]
fn zhipu_query_plan_schema_round_trips_through_parse() {
let value = compact_query_plan_schema();
let serialized = serde_json::to_string(&value).expect("schema should serialize");
let _: Value = serde_json::from_str(&serialized).expect("schema should parse");
}
}