Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

跨语言绑定

多语言 FFI 绑定示例。

Python 绑定

使用 UniFFI 从 Python 调用 MoFA。

位置: examples/python_bindings/

from mofa import LLMAgent, Tool

# 创建 LLM 智能体
agent = LLMAgent.builder() \
    .with_provider("openai") \
    .with_model("gpt-4o-mini") \
    .with_system_prompt("You are a helpful assistant.") \
    .build()

# 同步调用
response = agent.chat("Hello!")
print(response.text)

# 流式调用
for chunk in agent.stream("Tell me about Rust"):
    print(chunk, end="", flush=True)

定义工具

from mofa import Tool, ToolResult

class CalculatorTool(Tool):
    def name(self) -> str:
        return "calculator"

    def description(self) -> str:
        return "Performs arithmetic calculations"

    def execute(self, params: dict) -> ToolResult:
        expression = params.get("expression", "")
        try:
            result = eval(expression)  # 注意:生产环境需要安全验证
            return ToolResult.success({"result": result})
        except Exception as e:
            return ToolResult.error(str(e))

# 注册工具
agent.register_tool(CalculatorTool())

Java 绑定

从 Java 调用 MoFA。

位置: examples/java_bindings/

import io.mofa.sdk.*;

public class Example {
    public static void main(String[] args) {
        // 创建智能体
        LLMAgent agent = LLMAgent.builder()
            .withProvider("openai")
            .withModel("gpt-4o-mini")
            .withSystemPrompt("You are a helpful assistant.")
            .build();

        // 同步调用
        AgentOutput response = agent.chat("Hello!");
        System.out.println(response.getText());

        // 流式调用
        agent.stream("Tell me about Rust", chunk -> {
            System.out.print(chunk);
        });
    }
}

自定义工具

public class CalculatorTool implements Tool {
    @Override
    public String name() {
        return "calculator";
    }

    @Override
    public String description() {
        return "Performs arithmetic calculations";
    }

    @Override
    public ToolResult execute(Map<String, Object> params) {
        String expression = (String) params.get("expression");
        // 实现计算逻辑
        return ToolResult.success(result);
    }
}

Go 绑定

从 Go 调用 MoFA。

位置: examples/go_bindings/

package main

import (
    "fmt"
    "github.com/mofa-org/mofa/bindings/go/mofa"
)

func main() {
    // 创建智能体
    agent := mofa.NewLLMAgentBuilder().
        WithProvider("openai").
        WithModel("gpt-4o-mini").
        WithSystemPrompt("You are a helpful assistant.").
        Build()

    // 同步调用
    output := agent.Chat("Hello!")
    fmt.Println(output.Text())

    // 流式调用
    stream := agent.Stream("Tell me about Rust")
    for chunk := range stream {
        fmt.Print(chunk)
    }
}

自定义工具

type CalculatorTool struct{}

func (t *CalculatorTool) Name() string {
    return "calculator"
}

func (t *CalculatorTool) Description() string {
    return "Performs arithmetic calculations"
}

func (t *CalculatorTool) Execute(params map[string]interface{}) *mofa.ToolResult {
    expression := params["expression"].(string)
    // 实现计算逻辑
    return mofa.ToolResultSuccess(result)
}

构建绑定

# 构建 Python 绑定
cargo build -p mofa-ffi --features python

# 构建 Java 绑定
cargo build -p mofa-ffi --features java

# 构建 Go 绑定
cargo build -p mofa-ffi --features go

运行示例

# Python
cd examples/python_bindings && python main.py

# Java
cd examples/java_bindings && mvn compile exec:java

# Go
cd examples/go_bindings && go run main.go

可用示例

示例描述
python_bindingsPython UniFFI 绑定
java_bindingsJava UniFFI 绑定
go_bindingsGo UniFFI 绑定

相关链接