1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright 2024-2026 Reflective Labs
// SPDX-License-Identifier: MIT
// See LICENSE file in the project root for full license information.
//! Zhipu GLM API provider.
use crate::common::{HttpProviderConfig, OpenAiCompatibleProvider};
use crate::provider_api::{LlmError, LlmProvider, LlmRequest, LlmResponse};
/// Zhipu GLM API provider.
///
/// # Example
///
/// ```ignore
/// use converge_provider::ZhipuProvider;
/// use crate::provider_api::{LlmProvider, LlmRequest};
///
/// let provider = ZhipuProvider::new(
/// "your-api-key",
/// "glm-4"
/// );
///
/// let request = LlmRequest::new("What is 2+2?");
/// let response = provider.complete(&request)?;
/// println!("{}", response.content);
/// ```
pub struct ZhipuProvider {
config: HttpProviderConfig,
}
impl ZhipuProvider {
/// Creates a new Zhipu provider.
#[must_use]
pub fn new(api_key: impl Into<String>, model: impl Into<String>) -> Self {
Self {
config: HttpProviderConfig::new(api_key, model, "https://open.bigmodel.cn"),
}
}
/// Creates a provider using the `ZHIPU_API_KEY` environment variable.
///
/// # Errors
///
/// Returns error if the environment variable is not set.
pub fn from_env(model: impl Into<String>) -> Result<Self, LlmError> {
let api_key = std::env::var("ZHIPU_API_KEY")
.map_err(|_| LlmError::auth("ZHIPU_API_KEY environment variable not set"))?;
Ok(Self::new(api_key, model))
}
/// Uses a custom base URL (for testing or proxies).
#[must_use]
pub fn with_base_url(mut self, url: impl Into<String>) -> Self {
self.config.base_url = url.into();
self
}
}
impl OpenAiCompatibleProvider for ZhipuProvider {
fn config(&self) -> &HttpProviderConfig {
&self.config
}
fn endpoint(&self) -> &'static str {
"/api/paas/v4/chat/completions"
}
}
impl LlmProvider for ZhipuProvider {
fn name(&self) -> &'static str {
"zhipu"
}
fn model(&self) -> &str {
&self.config.model
}
fn complete(&self, request: &LlmRequest) -> Result<LlmResponse, LlmError> {
self.complete_openai_compatible(request)
}
fn provenance(&self, request_id: &str) -> String {
format!("zhipu:{}:{}", self.config.model, request_id)
}
}