Skip to main content

AgentLinkClient

Struct AgentLinkClient 

Source
pub struct AgentLinkClient { /* private fields */ }
Expand description

AgentLink SDK 主客户端

这是 SDK 的主要入口点,提供对所有服务的访问。

§Example

use agentlink_sdk::{AgentLinkClient, ClientConfig};

async fn example() {
    let config = ClientConfig::default();
    let client = AgentLinkClient::new(config);

    // 登录
    let response = client.auth()
        .login_with_email_code("user@example.com", "123456")
        .await
        .unwrap();

    // 连接 MQTT(自动启动事件循环)
    client.connect_mqtt(&response.token, &response.user.id)
        .await
        .unwrap();
}

§使用 API Key(类似 OpenAI SDK)

// 方式 1:从环境变量自动读取 API Key
// 环境变量: AGENTLINK_API_KEY=your-api-key
let client = AgentLinkClient::from_env().expect("Missing AGENTLINK_API_KEY");

// 方式 2:直接传入 API Key
let client = AgentLinkClient::from_api_key("your-api-key");

// 连接 MQTT 并启动事件循环
client.connect_and_start().await.expect("Connection failed");

// 注册事件处理器
client.on(EVENT_MESSAGE_RECEIVED, |event| async move {
    println!("收到消息: {:?}", event);
}).await;

Implementations§

Source§

impl AgentLinkClient

Source

pub fn new(config: ClientConfig) -> Self

创建新的 SDK 客户端

Source

pub fn from_env() -> Result<Self, SdkError>

从环境变量创建客户端(类似 OpenAI SDK 风格)

§环境变量
  • AGENTLINK_API_KEY: API Key(必需)
  • AGENTLINK_API_URL: API 基础 URL(可选)
  • AGENTLINK_MQTT_URL: MQTT Broker URL(可选)
§Example
// 设置环境变量
std::env::set_var("AGENTLINK_API_KEY", "your-api-key");

// 创建客户端
let client = AgentLinkClient::from_env().expect("Missing AGENTLINK_API_KEY");
Source

pub fn try_from_env() -> Option<Self>

尝试从环境变量创建客户端,如果环境变量不存在则返回 None

Source

pub fn from_api_key(api_key: &str) -> Self

使用 API Key 创建客户端(类似 OpenAI SDK 风格)

§Example
let client = AgentLinkClient::from_api_key("your-api-key");
Source

pub fn from_api_key_with_urls( api_key: &str, api_url: &str, mqtt_url: &str, ) -> Self

使用 API Key 和自定义 URL 创建客户端

§Example
let client = AgentLinkClient::from_api_key_with_urls(
    "your-api-key",
    "https://api.example.com/api/v1",
    "mqtts://mqtt.example.com:8883"
);
Source

pub fn config(&self) -> &ClientConfig

获取当前配置

Source

pub fn update_config(&mut self, config: ClientConfig)

更新配置

Source

pub fn auth(&self) -> AuthService

获取认证服务

不需要认证即可使用

Source

pub fn users(&self) -> UserService

获取用户服务

需要认证 Token 才能调用具体方法

Source

pub fn messages(&self) -> MessageService

获取消息服务

需要认证 Token 才能调用具体方法

Source

pub fn conversations(&self) -> ConversationService

获取会话服务

需要认证 Token 才能调用具体方法

Source

pub fn friends(&self) -> FriendService

获取好友服务

需要认证 Token 才能调用具体方法

Source

pub async fn connect_mqtt(&self, token: &str, user_id: &str) -> SdkResult<()>

连接到 MQTT Broker

§Arguments
  • token - JWT Token
  • user_id - 用户 ID
§Returns
  • Ok(()) - 连接成功
  • Err(SdkError) - 连接失败
Source

pub async fn disconnect_mqtt(&self) -> SdkResult<()>

断开 MQTT 连接

Source

pub async fn mqtt_connection_state(&self) -> MqttConnectionState

获取 MQTT 连接状态

Source

pub async fn is_mqtt_connected(&self) -> bool

检查 MQTT 是否已连接

Source

pub async fn subscribe(&self, topic: &str) -> SdkResult<()>

订阅 MQTT 主题

§Arguments
  • topic - 主题路径
Source

pub async fn unsubscribe(&self, topic: &str) -> SdkResult<()>

取消订阅 MQTT 主题

§Arguments
  • topic - 主题路径
Source

pub async fn publish(&self, topic: &str, payload: &[u8]) -> SdkResult<()>

发布 MQTT 消息

§Arguments
  • topic - 主题路径
  • payload - 消息内容
Source

pub async fn on<T, F, Fut>(&self, event_type: &str, callback: F)
where T: DeserializeOwned + Send + Sync + 'static, F: Fn(ServerEvent<T>) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

注册事件回调

§Example
use agentlink_sdk::{AgentLinkClient, ClientConfig, EVENT_MESSAGE_RECEIVED, ServerEvent, MessageReceivedData};

let client = AgentLinkClient::new(ClientConfig::default());

client.on(EVENT_MESSAGE_RECEIVED, |event: ServerEvent<MessageReceivedData>| async move {
    println!("收到新消息: {:?}", event.data.content);
}).await;
Source

pub async fn off(&self, event_type: &str)

移除事件回调

§Example
client.off(EVENT_MESSAGE_RECEIVED).await;
Source

pub async fn clear_callbacks(&self)

清除所有事件回调

§Example
client.clear_callbacks().await;
Source

pub fn event_loop(&self) -> Arc<RwLock<EventLoop>>

获取事件循环的引用(高级用法)

大多数情况下,应该使用 client.on() 方法注册回调, 而不是直接访问 event_loop。

Source

pub async fn start_event_loop(&self) -> SdkResult<()>

启动事件循环

这个方法会启动一个后台任务,持续处理 MQTT 事件并调用注册的回调函数。 应该在 MQTT 连接成功后调用。

§Example
// 先注册回调
client.event_loop().write().await.on_event("new_message", |event| Box::pin(async move {
    // 处理新消息
})).await;
 
// 连接 MQTT
client.connect_mqtt(&token, &user_id).await?;
 
// 启动事件循环
client.start_event_loop().await;
Source

pub async fn stop_event_loop(&self)

停止事件循环

Source

pub async fn mqtt_subscriptions(&self) -> Vec<String>

获取所有订阅的主题

Source

pub async fn connect_and_start(&self) -> SdkResult<()>

使用 API Key 连接 MQTT 并启动事件循环

这是一个便捷方法,适合使用 API Key 认证的场景(类似 OpenAI SDK)。

§流程
  1. 使用 API Key 作为 MQTT 密码连接
  2. 启动事件循环
§Example
// 从环境变量创建客户端
let client = AgentLinkClient::from_env().expect("Missing AGENTLINK_API_KEY");

// 连接并启动事件循环
client.connect_and_start().await.expect("Connection failed");

// 注册事件处理器
client.on(EVENT_MESSAGE_RECEIVED, |event| async move {
    println!("收到消息: {:?}", event);
}).await;
Source

pub async fn connect_mqtt_with_api_key(&self, api_key: &str) -> SdkResult<()>

使用 API Key 连接到 MQTT Broker

API Key 作为 MQTT 密码,用户名为 “api-key”。

§Arguments
  • api_key - API Key
Source

pub async fn login(&self, email: &str, code: &str) -> SdkResult<LoginResponse>

执行完整的登录流程

  1. 登录获取 Token
  2. 连接 MQTT
  3. 启动事件循环
§Arguments
  • email - 邮箱地址
  • code - 验证码
§Returns
  • LoginResponse - 包含 token 和用户信息
§Note

Token 需要在使用此方法前通过 with_token()set_token() 设置

Source

pub fn set_token(&self, token: &str)

设置 Token(用于手动设置或更新)

§Arguments
  • token - JWT Token
Source

pub fn with_token(&self, token: &str) -> &Self

设置 Token 并返回自身(用于链式调用)

§Example
let client = AgentLinkClient::new(config)
    .with_token("jwt_token_here");
§Arguments
  • token - JWT Token
Source

pub fn clear_token(&self)

清除 Token(用于登出)

Source

pub fn get_token(&self) -> Option<String>

获取当前 Token

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more