Skip to content

About

jiuwen-agent-core-rust is the Rust implementation of openJiuwen Core, providing a comprehensive SDK for AI agent development, execution, tuning, and evolution.

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

openJiuwen Core (Rust)

English | 简体中文

Overview

openjiuwen-rust is the Rust implementation of openJiuwen Core, providing a high-performance, embeddable runtime for large language model applications and agents. Built on a Rust core, the project also ships Java (JNI) and HarmonyOS (NAPI) bindings so the same agent, workflow, and tool capabilities can be reused across languages and deployment environments.

Core capabilities:

  • Runtime support for ReAct Agents, Workflows, and Duplex Agents;
  • LLM clients, message handling, and output processing;
  • Tool registration and invocation, plus an MCP (Model Context Protocol) client;
  • A2A (Agent2Agent) client, server, and streaming event handling;
  • Sessions, context, checkpoints, and streaming output;
  • Asynchronous execution, parallel graph execution, and distributed Runner capabilities;
  • Native extension interfaces for Java and HarmonyOS applications.

Why a Rust core

  • High-performance async runtime: built on Tokio and Rust async, suited to high-concurrency I/O, streaming responses, and long-lived agents.
  • Cross-language reuse: core logic is implemented once and exposed to Java and HarmonyOS applications through JNI and NAPI.
  • Complete protocol coverage: built-in MCP and A2A integration for connecting remote tools, agent services, and streaming tasks.
  • Embeddable and extensible: the core crate works directly as a Rust dependency, or compiles into a Java native library or HarmonyOS native module.
  • Controllable logging and build features: supports the max_level_off, max_level_error, max_level_warn, max_level_info, max_level_debug, and max_level_trace compile features.

Repository layout

.
├── Cargo.toml
├── crates/
│   ├── core/                  # Rust core library (Cargo package openjiuwen-core)
│   ├── gateway/               # Host-owned channel and cron adapters
│   ├── harness/               # Development and test harness
│   └── ffi/                   # Language and platform bindings (FFI layer)
│       ├── jni/               # Java/JNI (Cargo package openjiuwen-jni)
│       ├── jni-memory/        # Memory-only Java/JNI package
│       ├── napi/              # HarmonyOS NAPI (Cargo package openjiuwen-napi)
├── plugins/                   # External dynamic plugin crates
├── tests/e2e/                 # Migration and end-to-end tests
├── docs/                      # Design, data structure, and integration documentation
└── build.sh                   # Build script for the JNI library and Java wrapper package

Getting started

Requirements

  • Rust 1.86 or later;
  • JDK 21 and Maven (for building the Java/JNI package);
  • HarmonyOS, Linux, macOS, or Windows. build.sh requires Bash; on Windows you can run the equivalent Cargo and Maven commands directly.

Build the Rust core

git clone <repository-url>
cd jiuwen-rust
cargo check --workspace
cargo build --workspace

Build only the core library:

cargo build -p openjiuwen-core

Build the Java/JNI bindings

Build the JNI native library and the Java wrapper package:

cargo build -p openjiuwen-jni
cd crates/ffi/jni
mvn -DskipTests package

You can also use the repository script to build the JNI library and Java wrapper package end to end:

./build.sh                 # Compile check, then produce JNI/Java build artifacts
./build.sh --install       # Also install the Maven package
./build.sh --clean --install

--install installs the Java package into the local Maven repository. Make sure mvn is available in your environment before running the script.

Example 1: Native Rust build

Let's create a simple ReActAgent that calls an LLM to generate a piece of text:

use std::env;

use openjiuwen_core::agents::{AgentCard, ReActAgent, ReActAgentConfig};
use openjiuwen_core::runner::{AgentRef, Runner};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Provide the LLM configuration through environment variables
    let provider = env::var("MODEL_PROVIDER").unwrap_or_else(|_| "OpenAI".to_string());
    let api_key = env::var("API_KEY").expect("Please set API_KEY");
    let api_base = env::var("API_BASE").expect("Please set API_BASE");
    let model_name = env::var("MODEL_NAME").expect("Please set MODEL_NAME");

    // Create the ReActAgent configuration
    let mut config = ReActAgentConfig::new();
    config
        .configure_model_client(&provider, &api_key, &api_base, &model_name, true)
        .configure_max_iterations(5)
        .configure_prompt_template(vec![json!({
            "role": "system",
            "content": "You are a concise AI assistant. Answer the user's question directly."
        })]);

    // Create and configure the ReActAgent
    let card = AgentCard::new(
        "hello_react_agent",
        "Hello ReAct Agent",
        "Generate text with a large language model",
    );
    let mut agent = ReActAgent::new(card);
    agent.configure(config);

    // Run the agent
    let result = Runner::run_agent(
        AgentRef::Instance(Box::new(agent)),
        json!({"query": "Tell me a joke in 20 characters or fewer"}),
        None,
    )
    .await;

    if let Some(value) = result.get_value() {
        let output = value
            .get("output")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default();
        println!("ReActAgent output >>> {output}");
        Ok(())
    } else {
        let error = result.get_error().expect("Runner returned an empty result");
        Err(std::io::Error::new(std::io::ErrorKind::Other, error.to_string()).into())
    }
}

Set the model configuration before running. For example, on Linux or macOS:

export MODEL_PROVIDER=OpenAI
export API_BASE=https://api.openai.com/v1
export API_KEY=your_api_key
export MODEL_NAME=gpt-4o-mini

On Windows PowerShell:

$env:MODEL_PROVIDER = "OpenAI"
$env:API_BASE = "https://api.openai.com/v1"
$env:API_KEY = "your_api_key"
$env:MODEL_NAME = "gpt-4o-mini"

Save the code as crates/core/examples/react_agent.rs, then run:

cargo run -p openjiuwen-core --example react_agent

Expected output:

ReActAgent output >>> The output depends on the model you configure.

Example 2: FFI (Java) build

The following creates the same ReActAgent through the Java API. The Java object invokes the Rust agent runtime through JNI/FFI; the model configuration, system prompt, user question, and output handling match Example 1.

First build the JNI native library and install the Java package into the local Maven repository:

./build.sh --install

Add the dependency to your Java project's pom.xml:

<dependency>
    <groupId>com.openjiuwen</groupId>
    <artifactId>agent-core-rust</artifactId>
    <version>0.1.12</version>
</dependency>

Create ReActAgentFfiDemo.java:

import com.openjiuwen.core.runner.Runner;
import com.openjiuwen.core.singleagent.ReActAgent;
import com.openjiuwen.core.singleagent.agents.ReActAgentConfig;
import com.openjiuwen.core.singleagent.schema.AgentCard;

import java.util.List;
import java.util.Map;

public class ReActAgentFfiDemo {
    public static void main(String[] args) {
        // Provide the LLM configuration through environment variables
        String provider = envOrDefault("MODEL_PROVIDER", "OpenAI");
        String apiKey = requireEnv("API_KEY");
        String apiBase = requireEnv("API_BASE");
        String modelName = requireEnv("MODEL_NAME");

        // Create the ReActAgent configuration
        ReActAgentConfig config = new ReActAgentConfig()
                .configureModelClient(provider, apiKey, apiBase, modelName, true)
                .configureMaxIterations(5)
                .configurePromptTemplate(List.of(Map.of(
                        "role", "system",
                        "content", "You are a concise AI assistant. Answer the user's question directly."
                )));

        // Create and configure the ReActAgent; JniReActAgent drives the Rust core underneath
        AgentCard card = AgentCard.builder()
                .id("hello_react_agent")
                .name("Hello ReAct Agent")
                .description("Generate text with a large language model")
                .build();
        ReActAgent agent = new ReActAgent(card);
        agent.configure(config);

        try {
            // Run the agent
            Object result = Runner.runAgent(
                    agent,
                    Map.of("query", "Tell me a joke in 20 characters or fewer"),
                    null,
                    null
            );

            if (!(result instanceof Map<?, ?> resultMap)) {
                throw new IllegalStateException("Runner returned an invalid result: " + result);
            }

            Object output = resultMap.get("output");
            System.out.println("ReActAgent output >>> "
                    + (output == null ? "" : output));
        } finally {
            agent.destroy();
        }
    }

    private static String requireEnv(String name) {
        String value = System.getenv(name);
        if (value == null || value.isBlank()) {
            throw new IllegalStateException("Please set the environment variable " + name);
        }
        return value;
    }

    private static String envOrDefault(String name, String defaultValue) {
        String value = System.getenv(name);
        return value == null || value.isBlank() ? defaultValue : value;
    }
}

Set the environment variables as in Example 1. Compile and run with Maven:

mvn compile exec:java -Dexec.mainClass=ReActAgentFfiDemo

Expected output:

ReActAgent output >>> The output depends on the model you configure.

Main modules

Agents and workflows

openjiuwen-core provides single agents, ReAct, workflows, duplex agents, and task scheduling, composable with model calls, tool calls, context management, and callback handling.

Models and tools

foundation::llm provides model clients and request configuration, supporting OpenAI-compatible endpoints and multiple providers. foundation::tool provides tool adapters such as function tools, MCP, and REST/OpenAPI.

Sessions, context, and persistence

session and context handle message history, streaming output, context compression, checkpointing, and recovery. Persistence backends include in-memory and SQLite implementations, with extensions such as Redis.

A2A and distributed execution

extension::a2a provides the A2A client, server, event conversion, and streaming mapping; runner provides the Runner, remote clients, message queues, and distributed execution interfaces.

Java and HarmonyOS bindings

  • openjiuwen-jni: exposes the Rust core through JNI and packages the com.openjiuwen Java API together with the native library.
  • openjiuwen-napi: exposes the Rust core as a HarmonyOS/ArkTS native module.

Testing and checks

cargo fmt --all -- --check
cargo check --workspace
cargo test -p openjiuwen-core
cargo test --workspace

Java package tests (spike tests that need external services or a native runtime environment are excluded by default):

cd crates/ffi/jni
mvn test

Logging and configuration

Rust logging compiles at the debug level by default; adjust the runtime level with RUST_LOG:

RUST_LOG=info cargo run -p openjiuwen-core --example a2a_echo_server

Production builds can choose a stricter compile level, for example:

cargo build --workspace --no-default-features --features max_level_info --release

Model configuration typically includes the provider, API endpoint, API key, model name, timeout, retry count, and TLS verification options. Never commit real credentials; inject them through environment variables or local configuration files.

Contributing

Contributions are welcome:

  • File issues and feature requests;
  • Improve documentation and examples;
  • Submit fixes and tests;
  • Share your experience integrating agents, MCP, or A2A.

Before submitting code, run at least cargo fmt --all -- --check, cargo check --workspace, and the tests for the modules you touched.

License

This project is released under the Apache License 2.0 (matching the workspace Cargo.toml); see LICENSE for the full text. The accompanying third-party open source copyright and license notices are in Open_Source_Software_Notice.txt.

This project provides agent and workflow orchestration capabilities and bundles no specific AI model. When integrating models into a concrete business scenario, users are responsible for data security, content safety, licensing, and compliance with applicable laws and regulations (including the EU AI Act).

About

jiuwen-agent-core-rust is the Rust implementation of openJiuwen Core, providing a comprehensive SDK for AI agent development, execution, tuning, and evolution.

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages