alpha-release: 0.0.1 #1

Merged
Hare merged 18 commits from develop into master 2026-01-08 20:40:25 +09:00
4 changed files with 430 additions and 0 deletions
Showing only changes of commit 170c8708ae - Show all commits

127
Cargo.lock generated
View File

@ -2,6 +2,56 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "anstream"
version = "0.6.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78"
[[package]]
name = "anstyle-parse"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys 0.61.2",
]
[[package]]
name = "async-trait"
version = "0.1.89"
@ -95,6 +145,46 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
[[package]]
name = "clap"
version = "4.5.54"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6e6ff9dcd79cff5cd969a17a545d79e84ab086e444102a591e288a8aa3ce394"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap_builder"
version = "4.5.54"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa42cf4d2b7a41bc8f663a7cab4031ebafa1bf3875705bfaf8466dc60ab52c00"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_derive"
version = "4.5.49"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a0b5487afeab2deb2ff4e03a807ad1a03ac532ff5a2cee5d86884440c7f7671"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "clap_lex"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d"
[[package]]
name = "cmake"
version = "0.1.57"
@ -104,6 +194,12 @@ dependencies = [
"cc",
]
[[package]]
name = "colorchoice"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"
[[package]]
name = "combine"
version = "4.6.7"
@ -373,6 +469,12 @@ version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "http"
version = "1.4.0"
@ -604,6 +706,12 @@ dependencies = [
"serde",
]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "itoa"
version = "1.0.17"
@ -727,6 +835,12 @@ version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "openssl-probe"
version = "0.2.0"
@ -1209,6 +1323,12 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "subtle"
version = "2.6.1"
@ -1494,6 +1614,12 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "walkdir"
version = "2.5.0"
@ -1905,6 +2031,7 @@ name = "worker"
version = "0.1.0"
dependencies = [
"async-trait",
"clap",
"eventsource-stream",
"futures",
"reqwest",

View File

@ -16,5 +16,6 @@ worker-macros = { path = "../worker-macros" }
worker-types = { path = "../worker-types" }
[dev-dependencies]
clap = { version = "4.5.54", features = ["derive", "env"] }
schemars = "1.2.0"
tempfile = "3.24.0"

View File

@ -0,0 +1,283 @@
//! Worker を用いた対話型 CLI クライアント
//!
//! Anthropic Claude API と対話するシンプルなCLIアプリケーション。
//! ツールの登録と実行、ストリーミングレスポンスの表示をデモする。
//!
//! ## 使用方法
//!
//! ```bash
//! # .envファイルにAPIキーを設定
//! echo "ANTHROPIC_API_KEY=your-api-key" > .env
//!
//! # 基本的な実行
//! cargo run --example worker_cli
//!
//! # オプション指定
//! cargo run --example worker_cli -- --model claude-3-haiku-20240307 --system "You are a helpful assistant."
//!
//! # ヘルプ表示
//! cargo run --example worker_cli -- --help
//! ```
use std::io::{self, Write};
use std::sync::{Arc, Mutex};
use clap::Parser;
use worker::{
llm_client::providers::anthropic::AnthropicClient, Handler, TextBlockEvent, TextBlockKind,
ToolUseBlockEvent, ToolUseBlockKind, Worker,
};
use worker_macros::tool_registry;
use worker_types::Message;
// 必要なマクロ展開用インポート
use schemars;
use serde;
// =============================================================================
// CLI引数定義
// =============================================================================
/// Anthropic Claude API を使った対話型CLIクライアント
#[derive(Parser, Debug)]
#[command(name = "worker-cli")]
#[command(about = "Interactive CLI client for Anthropic Claude API using Worker")]
#[command(version)]
struct Args {
/// 使用するモデル名
#[arg(short, long, default_value = "claude-sonnet-4-20250514")]
model: String,
/// システムプロンプト
#[arg(short, long)]
system: Option<String>,
/// ツールを無効化
#[arg(long, default_value = "false")]
no_tools: bool,
/// 最初のメッセージ(指定するとそれを送信して終了)
#[arg(short = 'p', long)]
prompt: Option<String>,
/// APIキー環境変数 ANTHROPIC_API_KEY より優先)
#[arg(long, env = "ANTHROPIC_API_KEY")]
api_key: String,
}
// =============================================================================
// ツール定義
// =============================================================================
/// アプリケーションコンテキスト
#[derive(Clone)]
struct AppContext;
#[tool_registry]
impl AppContext {
/// 現在の日時を取得する
///
/// システムの現在の日付と時刻を返します。
#[tool]
fn get_current_time(&self) -> String {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs();
// シンプルなUnixタイムスタンプからの変換
format!("Current Unix timestamp: {}", now)
}
/// 簡単な計算を行う
///
/// 2つの数値の四則演算を実行します。
#[tool]
fn calculate(&self, a: f64, b: f64, operation: String) -> Result<String, String> {
let result = match operation.as_str() {
"add" | "+" => a + b,
"subtract" | "-" => a - b,
"multiply" | "*" => a * b,
"divide" | "/" => {
if b == 0.0 {
return Err("Cannot divide by zero".to_string());
}
a / b
}
_ => return Err(format!("Unknown operation: {}", operation)),
};
Ok(format!("{} {} {} = {}", a, operation, b, result))
}
}
// =============================================================================
// ストリーミング表示用ハンドラー
// =============================================================================
/// テキストをリアルタイムで出力するハンドラー
struct StreamingPrinter {
is_first_delta: Arc<Mutex<bool>>,
}
impl StreamingPrinter {
fn new() -> Self {
Self {
is_first_delta: Arc::new(Mutex::new(true)),
}
}
}
impl Handler<TextBlockKind> for StreamingPrinter {
type Scope = ();
fn on_event(&mut self, _scope: &mut (), event: &TextBlockEvent) {
match event {
TextBlockEvent::Start(_) => {
let mut first = self.is_first_delta.lock().unwrap();
if *first {
print!("\n🤖 ");
*first = false;
}
}
TextBlockEvent::Delta(text) => {
print!("{}", text);
io::stdout().flush().ok();
}
TextBlockEvent::Stop(_) => {
println!();
}
}
}
}
/// ツール呼び出しを表示するハンドラー
struct ToolCallPrinter;
impl Handler<ToolUseBlockKind> for ToolCallPrinter {
type Scope = String;
fn on_event(&mut self, json_buffer: &mut String, event: &ToolUseBlockEvent) {
match event {
ToolUseBlockEvent::Start(start) => {
println!("\n🔧 Calling tool: {}", start.name);
}
ToolUseBlockEvent::InputJsonDelta(json) => {
json_buffer.push_str(json);
}
ToolUseBlockEvent::Stop(_) => {
println!(" Args: {}", json_buffer);
}
}
}
}
// =============================================================================
// メイン
// =============================================================================
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// CLI引数をパース
let args = Args::parse();
// 対話モードかワンショットモードか
let is_interactive = args.prompt.is_none();
if is_interactive {
println!("╔════════════════════════════════════════════════╗");
println!("║ Worker CLI - Anthropic Claude Client ║");
println!("╚════════════════════════════════════════════════╝");
println!();
println!("Model: {}", args.model);
if let Some(ref system) = args.system {
println!("System: {}", system);
}
if args.no_tools {
println!("Tools: disabled");
} else {
println!("Tools:");
println!(" • get_current_time - Get the current timestamp");
println!(" • calculate - Perform arithmetic (add, subtract, multiply, divide)");
}
println!();
println!("Type 'quit' or 'exit' to end the session.");
println!("─────────────────────────────────────────────────");
}
// クライアント作成
let client = AnthropicClient::new(&args.api_key, &args.model);
// Worker作成
let mut worker = Worker::new(client);
// システムプロンプトを設定
if let Some(ref system_prompt) = args.system {
worker.set_system_prompt(system_prompt);
}
// ツール登録(--no-tools でなければ)
if !args.no_tools {
let app = AppContext;
worker.register_tool(app.get_current_time_tool());
worker.register_tool(app.calculate_tool());
}
// ストリーミング表示用ハンドラーを登録
worker
.timeline_mut()
.on_text_block(StreamingPrinter::new())
.on_tool_use_block(ToolCallPrinter);
// 会話履歴
let mut history: Vec<Message> = Vec::new();
// ワンショットモード
if let Some(prompt) = args.prompt {
history.push(Message::user(&prompt));
match worker.run(history).await {
Ok(_) => {}
Err(e) => {
eprintln!("\n❌ Error: {}", e);
std::process::exit(1);
}
}
return Ok(());
}
// 対話ループ
loop {
print!("\n👤 You: ");
io::stdout().flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
let input = input.trim();
if input.is_empty() {
continue;
}
if input == "quit" || input == "exit" {
println!("\n👋 Goodbye!");
break;
}
// ユーザーメッセージを履歴に追加
history.push(Message::user(input));
// Workerを実行
match worker.run(history.clone()).await {
Ok(new_history) => {
history = new_history;
}
Err(e) => {
eprintln!("\n❌ Error: {}", e);
// エラー時は最後のユーザーメッセージを削除
history.pop();
}
}
}
Ok(())
}

View File

@ -72,6 +72,8 @@ pub struct Worker<C: LlmClient> {
tools: HashMap<String, Arc<dyn Tool>>,
/// 登録されたHook
hooks: Vec<Box<dyn WorkerHook>>,
/// システムプロンプト
system_prompt: Option<String>,
}
impl<C: LlmClient> Worker<C> {
@ -92,9 +94,21 @@ impl<C: LlmClient> Worker<C> {
tool_call_collector,
tools: HashMap::new(),
hooks: Vec::new(),
system_prompt: None,
}
}
/// システムプロンプトを設定
pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
self.system_prompt = Some(prompt.into());
self
}
/// システムプロンプトを設定(可変参照版)
pub fn set_system_prompt(&mut self, prompt: impl Into<String>) {
self.system_prompt = Some(prompt.into());
}
/// 設定を適用(将来の拡張用)
#[allow(dead_code)]
pub fn config(self, _config: WorkerConfig) -> Self {
@ -241,6 +255,11 @@ impl<C: LlmClient> Worker<C> {
fn build_request(&self, context: &[Message], tool_definitions: &[ToolDefinition]) -> Request {
let mut request = Request::new();
// システムプロンプトを設定
if let Some(ref system) = self.system_prompt {
request = request.system(system);
}
// メッセージを追加
for msg in context {
// worker-types::Message から llm_client::Message への変換