pub struct Worker<C: LlmClient, S: WorkerState = Mutable> { /* private fields */ }Expand description
LLMとの対話を管理する中心コンポーネント
ユーザーからの入力を受け取り、LLMにリクエストを送信し、 ツール呼び出しがあれば自動的に実行してターンを進行させます。
§状態遷移(Type-state)
§Examples
use llm_worker::{Worker, Message};
// Workerを作成してツールを登録
let mut worker = Worker::new(client)
.system_prompt("You are a helpful assistant.");
worker.register_tool(my_tool);
// 対話を実行
let history = worker.run("Hello!").await?;§キャッシュ保護が必要な場合
let mut worker = Worker::new(client)
.system_prompt("...");
// 履歴を設定後、ロックしてキャッシュを保護
let mut locked = worker.lock();
locked.run("user input").await?;Implementations§
Source§impl<C: LlmClient, S: WorkerState> Worker<C, S>
impl<C: LlmClient, S: WorkerState> Worker<C, S>
Sourcepub async fn run(
&mut self,
user_input: impl Into<String>,
) -> Result<WorkerResult, WorkerError>
pub async fn run( &mut self, user_input: impl Into<String>, ) -> Result<WorkerResult, WorkerError>
ターンを実行
新しいユーザーメッセージを履歴に追加し、LLMにリクエストを送信する。 ツール呼び出しがある場合は自動的にループする。
Sourcepub fn subscribe<Sub: WorkerSubscriber + 'static>(&mut self, subscriber: Sub)
pub fn subscribe<Sub: WorkerSubscriber + 'static>(&mut self, subscriber: Sub)
イベント購読者を登録する
登録したSubscriberは、LLMからのストリーミングイベントを リアルタイムで受信できます。UIへのストリーム表示などに利用します。
§受信できるイベント
- ブロックイベント:
on_text_block,on_tool_use_block - メタイベント:
on_usage,on_status,on_error - 完了イベント:
on_text_complete,on_tool_call_complete - ターン制御:
on_turn_start,on_turn_end
§Examples
use llm_worker::{Worker, WorkerSubscriber, TextBlockEvent};
struct MyPrinter;
impl WorkerSubscriber for MyPrinter {
type TextBlockScope = ();
type ToolUseBlockScope = ();
fn on_text_block(&mut self, _: &mut (), event: &TextBlockEvent) {
if let TextBlockEvent::Delta(text) = event {
print!("{}", text);
}
}
}
worker.subscribe(MyPrinter);Sourcepub fn register_tool(
&mut self,
factory: ToolDefinition,
) -> Result<(), ToolRegistryError>
pub fn register_tool( &mut self, factory: ToolDefinition, ) -> Result<(), ToolRegistryError>
ツールを登録する
登録されたツールはLLMからの呼び出しで自動的に実行されます。 同名のツールを登録するとエラーになります。
§Examples
use llm_worker::tool::{ToolMeta, ToolDefinition, Tool};
use std::sync::Arc;
let def: ToolDefinition = Arc::new(|| {
(ToolMeta::new("search").description("..."), Arc::new(MyTool) as Arc<dyn Tool>)
});
worker.register_tool(def)?;Sourcepub fn register_tools(
&mut self,
factories: impl IntoIterator<Item = ToolDefinition>,
) -> Result<(), ToolRegistryError>
pub fn register_tools( &mut self, factories: impl IntoIterator<Item = ToolDefinition>, ) -> Result<(), ToolRegistryError>
複数のツールを登録
Sourcepub fn add_on_prompt_submit_hook(
&mut self,
hook: impl Hook<OnPromptSubmit> + 'static,
)
pub fn add_on_prompt_submit_hook( &mut self, hook: impl Hook<OnPromptSubmit> + 'static, )
on_prompt_submit Hookを追加する
run() でユーザーメッセージを受け取った直後に呼び出される。
Sourcepub fn add_pre_llm_request_hook(
&mut self,
hook: impl Hook<PreLlmRequest> + 'static,
)
pub fn add_pre_llm_request_hook( &mut self, hook: impl Hook<PreLlmRequest> + 'static, )
pre_llm_request Hookを追加する
各ターンのLLMリクエスト送信前に呼び出される。
Sourcepub fn add_pre_tool_call_hook(&mut self, hook: impl Hook<PreToolCall> + 'static)
pub fn add_pre_tool_call_hook(&mut self, hook: impl Hook<PreToolCall> + 'static)
pre_tool_call Hookを追加する
Sourcepub fn add_post_tool_call_hook(
&mut self,
hook: impl Hook<PostToolCall> + 'static,
)
pub fn add_post_tool_call_hook( &mut self, hook: impl Hook<PostToolCall> + 'static, )
post_tool_call Hookを追加する
Sourcepub fn add_on_turn_end_hook(&mut self, hook: impl Hook<OnTurnEnd> + 'static)
pub fn add_on_turn_end_hook(&mut self, hook: impl Hook<OnTurnEnd> + 'static)
on_turn_end Hookを追加する
Sourcepub fn add_on_abort_hook(&mut self, hook: impl Hook<OnAbort> + 'static)
pub fn add_on_abort_hook(&mut self, hook: impl Hook<OnAbort> + 'static)
on_abort Hookを追加する
Sourcepub fn timeline_mut(&mut self) -> &mut Timeline
pub fn timeline_mut(&mut self) -> &mut Timeline
タイムラインへの可変参照を取得(追加ハンドラ登録用)
Sourcepub fn get_system_prompt(&self) -> Option<&str>
pub fn get_system_prompt(&self) -> Option<&str>
システムプロンプトへの参照を取得
Sourcepub fn turn_count(&self) -> usize
pub fn turn_count(&self) -> usize
現在のターンカウントを取得
Sourcepub fn request_config(&self) -> &RequestConfig
pub fn request_config(&self) -> &RequestConfig
現在のリクエスト設定への参照を取得
Sourcepub fn set_max_tokens(&mut self, max_tokens: u32)
pub fn set_max_tokens(&mut self, max_tokens: u32)
Sourcepub fn set_temperature(&mut self, temperature: f32)
pub fn set_temperature(&mut self, temperature: f32)
Sourcepub fn add_stop_sequence(&mut self, sequence: impl Into<String>)
pub fn add_stop_sequence(&mut self, sequence: impl Into<String>)
Sourcepub fn clear_stop_sequences(&mut self)
pub fn clear_stop_sequences(&mut self)
ストップシーケンスをクリア
Sourcepub fn cancel_sender(&self) -> Sender<()>
pub fn cancel_sender(&self) -> Sender<()>
キャンセル通知用Senderを取得する
Sourcepub fn set_request_config(&mut self, config: RequestConfig)
pub fn set_request_config(&mut self, config: RequestConfig)
リクエスト設定を一括で設定
Sourcepub fn cancel(&self)
pub fn cancel(&self)
実行をキャンセルする
現在実行中のストリーミングやツール実行を中断します。 次のイベントループのチェックポイントでWorkerError::Cancelledが返されます。
§Examples
use std::sync::Arc;
let worker = Arc::new(Mutex::new(Worker::new(client)));
// 別スレッドで実行
let worker_clone = worker.clone();
tokio::spawn(async move {
let mut w = worker_clone.lock().unwrap();
w.run("Long task...").await
});
// キャンセル
worker.lock().unwrap().cancel();Sourcepub fn is_cancelled(&mut self) -> bool
pub fn is_cancelled(&mut self) -> bool
キャンセルされているかチェック
Sourcepub fn last_run_interrupted(&self) -> bool
pub fn last_run_interrupted(&self) -> bool
前回の実行が中断されたかどうか
Sourcepub async fn resume(&mut self) -> Result<WorkerResult, WorkerError>
pub async fn resume(&mut self) -> Result<WorkerResult, WorkerError>
実行を再開(Pause状態からの復帰)
新しいユーザーメッセージを履歴に追加せず、現在の状態からターン処理を再開する。
Source§impl<C: LlmClient> Worker<C, Mutable>
impl<C: LlmClient> Worker<C, Mutable>
Sourcepub fn system_prompt(self, prompt: impl Into<String>) -> Self
pub fn system_prompt(self, prompt: impl Into<String>) -> Self
システムプロンプトを設定(ビルダーパターン)
Sourcepub fn set_system_prompt(&mut self, prompt: impl Into<String>)
pub fn set_system_prompt(&mut self, prompt: impl Into<String>)
システムプロンプトを設定(可変参照版)
Sourcepub fn max_tokens(self, max_tokens: u32) -> Self
pub fn max_tokens(self, max_tokens: u32) -> Self
Sourcepub fn temperature(self, temperature: f32) -> Self
pub fn temperature(self, temperature: f32) -> Self
Sourcepub fn stop_sequence(self, sequence: impl Into<String>) -> Self
pub fn stop_sequence(self, sequence: impl Into<String>) -> Self
ストップシーケンスを追加(ビルダーパターン)
Sourcepub fn with_config(self, config: RequestConfig) -> Self
pub fn with_config(self, config: RequestConfig) -> Self
Sourcepub fn validate(self) -> Result<Self, WorkerError>
pub fn validate(self) -> Result<Self, WorkerError>
Sourcepub fn history_mut(&mut self) -> &mut Vec<Message>
pub fn history_mut(&mut self) -> &mut Vec<Message>
履歴への可変参照を取得
Mutable状態でのみ利用可能。履歴を自由に編集できる。
Sourcepub fn set_history(&mut self, messages: Vec<Message>)
pub fn set_history(&mut self, messages: Vec<Message>)
履歴を設定
Sourcepub fn with_message(self, message: Message) -> Self
pub fn with_message(self, message: Message) -> Self
履歴にメッセージを追加(ビルダーパターン)
Sourcepub fn push_message(&mut self, message: Message)
pub fn push_message(&mut self, message: Message)
履歴にメッセージを追加
Sourcepub fn with_messages(self, messages: impl IntoIterator<Item = Message>) -> Self
pub fn with_messages(self, messages: impl IntoIterator<Item = Message>) -> Self
複数のメッセージを履歴に追加(ビルダーパターン)
Sourcepub fn extend_history(&mut self, messages: impl IntoIterator<Item = Message>)
pub fn extend_history(&mut self, messages: impl IntoIterator<Item = Message>)
複数のメッセージを履歴に追加
Sourcepub fn clear_history(&mut self)
pub fn clear_history(&mut self)
履歴をクリア
Sourcepub fn config(self, _config: WorkerConfig) -> Self
pub fn config(self, _config: WorkerConfig) -> Self
設定を適用(将来の拡張用)
Sourcepub fn lock(self) -> Worker<C, CacheLocked>
pub fn lock(self) -> Worker<C, CacheLocked>
ロックしてCacheLocked状態へ遷移
この操作により、現在のシステムプロンプトと履歴が「確定済みプレフィックス」として 固定される。以降は履歴への追記のみが可能となり、キャッシュヒットが保証される。