langchain4j-ai-services-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

LangChain4j AI Services Patterns

LangChain4j AI服务模式

This skill provides guidance for building declarative AI Services with LangChain4j using interface-based patterns, annotations for system and user messages, memory management, tools integration, and advanced AI application patterns that abstract away low-level LLM interactions.
本技能为使用LangChain4j构建声明式AI服务提供指导,涵盖基于接口的模式、系统与用户消息注解、内存管理、工具集成,以及可抽象底层LLM交互的高级AI应用模式。

When to Use

适用场景

Use this skill when:
  • Building declarative AI-powered interfaces with minimal boilerplate code
  • Creating type-safe AI services with Java interfaces and annotations
  • Implementing conversational AI systems with memory management
  • Designing AI services that can call external tools and functions
  • Building multi-agent systems with specialized AI components
  • Creating AI services with different personas and behaviors
  • Implementing RAG (Retrieval-Augmented Generation) patterns declaratively
  • Building production AI applications with proper error handling and validation
  • Creating AI services that return structured data types (enums, POJOs, lists)
  • Implementing streaming AI responses with reactive patterns
在以下场景中使用本技能:
  • 以极少的样板代码构建声明式AI驱动接口
  • 使用Java接口和注解创建类型安全的AI服务
  • 实现具备内存管理的对话式AI系统
  • 设计可调用外部工具与函数的AI服务
  • 构建包含专用AI组件的多Agent系统
  • 创建具备不同角色与行为的AI服务
  • 以声明式方式实现RAG(检索增强生成)模式
  • 构建具备完善错误处理与验证机制的生产级AI应用
  • 创建可返回结构化数据类型(枚举、POJO、列表)的AI服务
  • 使用响应式模式实现AI响应流式输出

Overview

概述

LangChain4j AI Services allow you to define AI-powered functionality using plain Java interfaces with annotations, eliminating the need for manual prompt construction and response parsing. This pattern provides type-safe, declarative AI capabilities with minimal boilerplate code.
LangChain4j AI服务允许你使用带注解的普通Java接口定义AI驱动功能,无需手动构建提示词和解析响应。该模式可提供类型安全、声明式的AI能力,且样板代码极少。

Quick Start

快速开始

Basic AI Service Definition

基础AI服务定义

java
interface Assistant {
    String chat(String userMessage);
}

// Create instance - LangChain4j generates implementation
Assistant assistant = AiServices.create(Assistant.class, chatModel);

// Use the service
String response = assistant.chat("Hello, how are you?");
java
interface Assistant {
    String chat(String userMessage);
}

// 创建实例 - LangChain4j自动生成实现
Assistant assistant = AiServices.create(Assistant.class, chatModel);

// 使用服务
String response = assistant.chat("Hello, how are you?");

System Message and Templates

系统消息与模板

java
interface CustomerSupportBot {
    @SystemMessage("You are a helpful customer support agent for TechCorp")
    String handleInquiry(String customerMessage);

    @UserMessage("Analyze sentiment: {{it}}")
    String analyzeSentiment(String feedback);
}

CustomerSupportBot bot = AiServices.create(CustomerSupportBot.class, chatModel);
java
interface CustomerSupportBot {
    @SystemMessage("You are a helpful customer support agent for TechCorp")
    String handleInquiry(String customerMessage);

    @UserMessage("Analyze sentiment: {{it}}")
    String analyzeSentiment(String feedback);
}

CustomerSupportBot bot = AiServices.create(CustomerSupportBot.class, chatModel);

Memory Management

内存管理

java
interface MultiUserAssistant {
    String chat(@MemoryId String userId, String userMessage);
}

Assistant assistant = AiServices.builder(MultiUserAssistant.class)
    .chatModel(model)
    .chatMemoryProvider(userId -> MessageWindowChatMemory.withMaxMessages(10))
    .build();
java
interface MultiUserAssistant {
    String chat(@MemoryId String userId, String userMessage);
}

Assistant assistant = AiServices.builder(MultiUserAssistant.class)
    .chatModel(model)
    .chatMemoryProvider(userId -> MessageWindowChatMemory.withMaxMessages(10))
    .build();

Tool Integration

工具集成

java
class Calculator {
    @Tool("Add two numbers") double add(double a, double b) { return a + b; }
}

interface MathGenius {
    String ask(String question);
}

MathGenius mathGenius = AiServices.builder(MathGenius.class)
    .chatModel(model)
    .tools(new Calculator())
    .build();
java
class Calculator {
    @Tool("Add two numbers") double add(double a, double b) { return a + b; }
}

interface MathGenius {
    String ask(String question);
}

MathGenius mathGenius = AiServices.builder(MathGenius.class)
    .chatModel(model)
    .tools(new Calculator())
    .build();

Examples

示例

See examples.md for comprehensive practical examples including:
  • Basic chat interfaces
  • Stateful assistants with memory
  • Multi-user scenarios
  • Structured output extraction
  • Tool calling and function execution
  • Streaming responses
  • Error handling
  • RAG integration
  • Production patterns
查看examples.md获取全面的实用示例,包括:
  • 基础聊天接口
  • 带内存的有状态助手
  • 多用户场景
  • 结构化输出提取
  • 工具调用与函数执行
  • 流式响应
  • 错误处理
  • RAG集成
  • 生产级模式

API Reference

API参考

Complete API documentation, annotations, interfaces, and configuration patterns are available in references.md.
完整的API文档、注解、接口和配置模式可在references.md中查看。

Best Practices

最佳实践

  1. Use type-safe interfaces instead of string-based prompts
  2. Implement proper memory management with appropriate limits
  3. Design clear tool descriptions with parameter documentation
  4. Handle errors gracefully with custom error handlers
  5. Use structured output for predictable responses
  6. Implement validation for user inputs
  7. Monitor performance for production deployments
  1. 使用类型安全接口替代基于字符串的提示词
  2. 实现合理的内存管理并设置适当限制
  3. 设计清晰的工具描述并添加参数文档
  4. 优雅处理错误,使用自定义错误处理器
  5. 使用结构化输出以获得可预测的响应
  6. 对用户输入进行验证
  7. 监控性能以适配生产部署

Dependencies

依赖

xml
<!-- Maven -->
<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j</artifactId>
    <version>1.8.0</version>
</dependency>
<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j-open-ai</artifactId>
    <version>1.8.0</version>
</dependency>
gradle
// Gradle
implementation 'dev.langchain4j:langchain4j:1.8.0'
implementation 'dev.langchain4j:langchain4j-open-ai:1.8.0'
xml
<!-- Maven -->
<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j</artifactId>
    <version>1.8.0</version>
</dependency>
<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j-open-ai</artifactId>
    <version>1.8.0</version>
</dependency>
gradle
// Gradle
implementation 'dev.langchain4j:langchain4j:1.8.0'
implementation 'dev.langchain4j:langchain4j-open-ai:1.8.0'

References

参考资料