Worker

Struct Worker 

Source
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>

Source

pub async fn run( &mut self, user_input: impl Into<String>, ) -> Result<WorkerResult, WorkerError>

ターンを実行

新しいユーザーメッセージを履歴に追加し、LLMにリクエストを送信する。 ツール呼び出しがある場合は自動的にループする。

Source

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);
Source

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)?;
Source

pub fn register_tools( &mut self, factories: impl IntoIterator<Item = ToolDefinition>, ) -> Result<(), ToolRegistryError>

複数のツールを登録

Source

pub fn add_on_prompt_submit_hook( &mut self, hook: impl Hook<OnPromptSubmit> + 'static, )

on_prompt_submit Hookを追加する

run() でユーザーメッセージを受け取った直後に呼び出される。

Source

pub fn add_pre_llm_request_hook( &mut self, hook: impl Hook<PreLlmRequest> + 'static, )

pre_llm_request Hookを追加する

各ターンのLLMリクエスト送信前に呼び出される。

Source

pub fn add_pre_tool_call_hook(&mut self, hook: impl Hook<PreToolCall> + 'static)

pre_tool_call Hookを追加する

Source

pub fn add_post_tool_call_hook( &mut self, hook: impl Hook<PostToolCall> + 'static, )

post_tool_call Hookを追加する

Source

pub fn add_on_turn_end_hook(&mut self, hook: impl Hook<OnTurnEnd> + 'static)

on_turn_end Hookを追加する

Source

pub fn add_on_abort_hook(&mut self, hook: impl Hook<OnAbort> + 'static)

on_abort Hookを追加する

Source

pub fn timeline_mut(&mut self) -> &mut Timeline

タイムラインへの可変参照を取得(追加ハンドラ登録用)

Source

pub fn history(&self) -> &[Message]

履歴への参照を取得

Source

pub fn get_system_prompt(&self) -> Option<&str>

システムプロンプトへの参照を取得

Source

pub fn turn_count(&self) -> usize

現在のターンカウントを取得

Source

pub fn request_config(&self) -> &RequestConfig

現在のリクエスト設定への参照を取得

Source

pub fn set_max_tokens(&mut self, max_tokens: u32)

最大トークン数を設定

この設定はキャッシュロックとは独立しており、各リクエストに適用されます。

§Examples
worker.set_max_tokens(4096);
Source

pub fn set_temperature(&mut self, temperature: f32)

temperatureを設定

0.0から1.0(または2.0)の範囲で設定します。 低い値はより決定的な出力を、高い値はより多様な出力を生成します。

§Examples
worker.set_temperature(0.7);
Source

pub fn set_top_p(&mut self, top_p: f32)

top_pを設定(nucleus sampling)

§Examples
worker.set_top_p(0.9);
Source

pub fn set_top_k(&mut self, top_k: u32)

top_kを設定

トークン選択時に考慮する上位k個のトークンを指定します。

§Examples
worker.set_top_k(40);
Source

pub fn add_stop_sequence(&mut self, sequence: impl Into<String>)

ストップシーケンスを追加

§Examples
worker.add_stop_sequence("\n\n");
Source

pub fn clear_stop_sequences(&mut self)

ストップシーケンスをクリア

Source

pub fn cancel_sender(&self) -> Sender<()>

キャンセル通知用Senderを取得する

Source

pub fn set_request_config(&mut self, config: RequestConfig)

リクエスト設定を一括で設定

Source

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();
Source

pub fn is_cancelled(&mut self) -> bool

キャンセルされているかチェック

Source

pub fn last_run_interrupted(&self) -> bool

前回の実行が中断されたかどうか

Source

pub async fn resume(&mut self) -> Result<WorkerResult, WorkerError>

実行を再開(Pause状態からの復帰)

新しいユーザーメッセージを履歴に追加せず、現在の状態からターン処理を再開する。

Source§

impl<C: LlmClient> Worker<C, Mutable>

Source

pub fn new(client: C) -> Self

新しいWorkerを作成(Mutable状態)

Source

pub fn system_prompt(self, prompt: impl Into<String>) -> Self

システムプロンプトを設定(ビルダーパターン)

Source

pub fn set_system_prompt(&mut self, prompt: impl Into<String>)

システムプロンプトを設定(可変参照版)

Source

pub fn max_tokens(self, max_tokens: u32) -> Self

最大トークン数を設定(ビルダーパターン)

§Examples
let worker = Worker::new(client)
    .system_prompt("You are a helpful assistant.")
    .max_tokens(4096);
Source

pub fn temperature(self, temperature: f32) -> Self

temperatureを設定(ビルダーパターン)

§Examples
let worker = Worker::new(client)
    .temperature(0.7);
Source

pub fn top_p(self, top_p: f32) -> Self

top_pを設定(ビルダーパターン)

Source

pub fn top_k(self, top_k: u32) -> Self

top_kを設定(ビルダーパターン)

Source

pub fn stop_sequence(self, sequence: impl Into<String>) -> Self

ストップシーケンスを追加(ビルダーパターン)

Source

pub fn with_config(self, config: RequestConfig) -> Self

リクエスト設定をまとめて設定(ビルダーパターン)

§Examples
let config = RequestConfig::new()
    .with_max_tokens(4096)
    .with_temperature(0.7);

let worker = Worker::new(client)
    .system_prompt("...")
    .with_config(config);
Source

pub fn validate(self) -> Result<Self, WorkerError>

現在の設定をプロバイダに対してバリデーションする

未サポートの設定があればエラーを返す。 チェーンの最後で呼び出すことで、設定の問題を早期に検出できる。

§Examples
let worker = Worker::new(client)
    .temperature(0.7)
    .top_k(40)
    .validate()?;  // OpenAIならtop_kがサポートされないためエラー
§Returns
  • Ok(Self) - バリデーション成功
  • Err(WorkerError::ConfigWarnings) - 未サポートの設定がある
Source

pub fn history_mut(&mut self) -> &mut Vec<Message>

履歴への可変参照を取得

Mutable状態でのみ利用可能。履歴を自由に編集できる。

Source

pub fn set_history(&mut self, messages: Vec<Message>)

履歴を設定

Source

pub fn with_message(self, message: Message) -> Self

履歴にメッセージを追加(ビルダーパターン)

Source

pub fn push_message(&mut self, message: Message)

履歴にメッセージを追加

Source

pub fn with_messages(self, messages: impl IntoIterator<Item = Message>) -> Self

複数のメッセージを履歴に追加(ビルダーパターン)

Source

pub fn extend_history(&mut self, messages: impl IntoIterator<Item = Message>)

複数のメッセージを履歴に追加

Source

pub fn clear_history(&mut self)

履歴をクリア

Source

pub fn config(self, _config: WorkerConfig) -> Self

設定を適用(将来の拡張用)

Source

pub fn lock(self) -> Worker<C, CacheLocked>

ロックしてCacheLocked状態へ遷移

この操作により、現在のシステムプロンプトと履歴が「確定済みプレフィックス」として 固定される。以降は履歴への追記のみが可能となり、キャッシュヒットが保証される。

Source§

impl<C: LlmClient> Worker<C, CacheLocked>

Source

pub fn locked_prefix_len(&self) -> usize

ロック時点のプレフィックス長を取得

Source

pub fn unlock(self) -> Worker<C, Mutable>

ロックを解除してMutable状態へ戻す

注意: この操作を行うと、以降のリクエストでキャッシュがヒットしなくなる可能性がある。 履歴を編集する必要がある場合にのみ使用すること。

Auto Trait Implementations§

§

impl<C, S> Freeze for Worker<C, S>
where C: Freeze,

§

impl<C, S = Mutable> !RefUnwindSafe for Worker<C, S>

§

impl<C, S> Send for Worker<C, S>

§

impl<C, S> Sync for Worker<C, S>

§

impl<C, S> Unpin for Worker<C, S>
where C: Unpin, S: Unpin,

§

impl<C, S = Mutable> !UnwindSafe for Worker<C, S>

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