Skip to content

基于 LLM 的规划器

Beta

此功能属于 Beta 模块 (1.2.0-beta),其 API 可能在后续版本中发生变化。

有关详细信息,请参阅模块版本控制

基于 LLM 的规划器使用 LLM 来生成并评估计划。 它们在基于字符串的状态上运行,并通过 LLM 请求执行步骤。 基于字符串的状态意味着智能体状态是一个单一字符串。 在每一步中,智能体接收一个初始状态字符串,并返回最终状态字符串作为结果。

前置条件

确保您的开发环境和项目满足以下要求:

  • JDK 17+

  • Kotlin 2.2.0+

  • Gradle 8.0+ 或 Maven 3.8+ 添加 Koog 依赖项:


dependencies {

    // 稳定版

    implementation("ai.koog:koog-agents:1.2.0")

    // Beta 版

    implementation("ai.koog:koog-agents-additions:1.2.0-beta")

}

dependencies {

    // 稳定版

    implementation 'ai.koog:koog-agents:1.2.0'

    // Beta 版

    implementation 'ai.koog:koog-agents-additions:1.2.0-beta'

}
xml

<dependency>

    <!-- 稳定版 -->

    <dependency>

        <groupId>ai.koog</groupId>

        <artifactId>koog-agents-jvm</artifactId>

        <version>1.2.0</version>

    </dependency>

    <!-- Beta 版 -->

    <dependency>

        <groupId>ai.koog</groupId>

        <artifactId>koog-agents-additions-jvm</artifactId>

        <version>1.2.0-beta</version>

    </dependency>

</dependency>

从 LLM 提供商处获取 API 密钥,或者通过 Ollama 在本地运行 LLM。

有关详细信息,请参阅快速入门。 本页中的示例假设你已设置了 OPENAI_API_KEY 环境变量。

Koog 提供了两种简单的规划器:

  • SimpleLLMPlanner 仅在最开始生成一次计划,然后按照该计划执行直至完成。 要包含重新规划,请扩展 SimpleLLMPlanner 并重写 assessPlan 方法,以指示智能体何时应该重新规划。
  • SimpleLLMWithCriticPlanner 实现了 assessPlan 方法,该方法通过 LLM 请求使用 LLM 检查计划的有效性,并评估智能体是否应该重新规划。

以下示例展示了如何使用 SimpleLLMPlanner 创建一个简单的规划器智能体:

kotlin
// 创建规划器
val planner = SimpleLLMPlanner()

// 将其封装在规划器策略中
val strategy = AIAgentPlannerStrategy(
    name = "simple-planner",
    planner = planner
)

// 配置智能体
val agentConfig = AIAgentConfig(
    prompt = prompt("planner") {
        system("You are a helpful planning assistant.")
    },
    model = OpenAIModels.Chat.GPT4o,
    maxAgentIterations = 50
)

// 创建规划器智能体
val agent = PlannerAIAgent(
    promptExecutor = simpleOpenAIExecutor(System.getenv("OPENAI_API_KEY")),
    strategy = strategy,
    agentConfig = agentConfig
)

suspend fun main() {
    // 运行智能体以执行任务
    val result = agent.run("Create a plan to organize a team meeting")
    println(result)
}
java
// 使用基于 LLM 的规划器创建规划器策略
AIAgentPlannerStrategy<String, String> strategy =
    Planners.llmBased("simple-planner")
        .build();

// 创建 OpenAI 执行器
var promptExecutor = PromptExecutor.builder()
    .openAI("OPENAI_API_KEY")
    .build();

// 使用 AIAgent 构建器创建规划器智能体
AIAgent<String, String> agent = AIAgent.builder()
    .plannerStrategy(strategy)
    .promptExecutor(promptExecutor)
    .llmModel(OpenAIModels.Chat.GPT4o)
    .systemPrompt("You are a helpful planning assistant.")
    .maxIterations(50)
    .build();

// 运行智能体以执行任务
String result = agent.run("Create a plan to organize a team meeting");
System.out.println(result);

后续步骤