Skip to content

Code Examples

This page provides example code for each feature module of NiteMoon AI Platform to help you get started with development quickly.

Workflow Creation

Create a Simple Workflow

java
@Service
public class WorkflowExampleService {
    
    @Autowired
    private WorkflowService workflowService;
    
    public WorkflowDefinition createSimpleWorkflow() {
        // Create workflow definition
        WorkflowDefinition workflow = new WorkflowDefinition();
        workflow.setName("Simple Chat Workflow");
        workflow.setDescription("A simple LLM chat workflow");
        
        // Add nodes
        WorkflowNode startNode = new WorkflowNode("START", "Start");
        WorkflowNode llmNode = new WorkflowNode("LLM", "AI Assistant");
        WorkflowNode endNode = new WorkflowNode("END", "End");
        
        // Configure LLM node
        llmNode.setConfig(Map.of(
            "model", "gpt-4",
            "systemPrompt", "You are a professional AI assistant",
            "temperature", 0.7
        ));
        
        // Add nodes to workflow
        workflow.addNode(startNode);
        workflow.addNode(llmNode);
        workflow.addNode(endNode);
        
        // Connect nodes
        workflow.addEdge(startNode.getId(), llmNode.getId());
        workflow.addEdge(llmNode.getId(), endNode.getId());
        
        // Save workflow
        return workflowService.save(workflow);
    }
}

Create a RAG Workflow

java
public WorkflowDefinition createRAGWorkflow() {
    WorkflowDefinition workflow = new WorkflowDefinition();
    workflow.setName("RAG Q&A Workflow");
    
    // Add nodes
    WorkflowNode startNode = new WorkflowNode("START", "Start");
    WorkflowNode ragNode = new WorkflowNode("KNOWLEDGE_RETRIEVAL", "Knowledge Retrieval");
    WorkflowNode llmNode = new WorkflowNode("LLM", "AI Answer");
    WorkflowNode endNode = new WorkflowNode("END", "End");
    
    // Configure RAG node
    ragNode.setConfig(Map.of(
        "knowledgeBaseId", 1,
        "topK", 5,
        "similarityThreshold", 0.7
    ));
    
    // Configure LLM node
    llmNode.setConfig(Map.of(
        "model", "gpt-4",
        "systemPrompt", "Answer the question based on the following context:\n{{context}}",
        "temperature", 0.3
    ));
    
    // Configure input mapping
    llmNode.setRefInputs(Map.of(
        "context", "{{KNOWLEDGE_RETRIEVAL.results}}"
    ));
    
    // Add nodes and edges
    workflow.addNode(startNode);
    workflow.addNode(ragNode);
    workflow.addNode(llmNode);
    workflow.addNode(endNode);
    
    workflow.addEdge(startNode.getId(), ragNode.getId());
    workflow.addEdge(ragNode.getId(), llmNode.getId());
    workflow.addEdge(llmNode.getId(), endNode.getId());
    
    return workflowService.save(workflow);
}

Create a Conditional Branch Workflow

java
public WorkflowDefinition createConditionalWorkflow() {
    WorkflowDefinition workflow = new WorkflowDefinition();
    workflow.setName("Conditional Branch Workflow");
    
    // Add nodes
    WorkflowNode startNode = new WorkflowNode("START", "Start");
    WorkflowNode classifyNode = new WorkflowNode("LLM", "Intent Classification");
    WorkflowNode ifElseNode = new WorkflowNode("IF_ELSE", "Condition Check");
    WorkflowNode techNode = new WorkflowNode("LLM", "Technical Answer");
    WorkflowNode generalNode = new WorkflowNode("LLM", "General Answer");
    WorkflowNode endNode = new WorkflowNode("END", "End");
    
    // Configure classification node
    classifyNode.setConfig(Map.of(
        "model", "gpt-4",
        "systemPrompt", "Classify the user question as: Technical Question, General Question. Return only the classification result."
    ));
    
    // Configure condition node
    ifElseNode.setConfig(Map.of(
        "conditions", List.of(
            Map.of("field", "classify", "operator", "equals", "value", "Technical Question"),
            Map.of("field", "classify", "operator", "equals", "value", "General Question")
        )
    ));
    
    // Add nodes and edges
    workflow.addNode(startNode);
    workflow.addNode(classifyNode);
    workflow.addNode(ifElseNode);
    workflow.addNode(techNode);
    workflow.addNode(generalNode);
    workflow.addNode(endNode);
    
    workflow.addEdge(startNode.getId(), classifyNode.getId());
    workflow.addEdge(classifyNode.getId(), ifElseNode.getId());
    workflow.addEdge(ifElseNode.getId(), techNode.getId(), "Condition 1");
    workflow.addEdge(ifElseNode.getId(), generalNode.getId(), "Condition 2");
    workflow.addEdge(techNode.getId(), endNode.getId());
    workflow.addEdge(generalNode.getId(), endNode.getId());
    
    return workflowService.save(workflow);
}

RAG Applications

Create Knowledge Base

java
@Service
public class RAGExampleService {
    
    @Autowired
    private KnowledgeBaseService knowledgeBaseService;
    
    @Autowired
    private DocumentService documentService;
    
    @Autowired
    private RAGService ragService;
    
    public KnowledgeBase createKnowledgeBase() {
        // Create knowledge base
        KnowledgeBase kb = new KnowledgeBase();
        kb.setName("Product Documentation");
        kb.setDescription("Product-related documents and FAQ");
        
        return knowledgeBaseService.save(kb);
    }
    
    public void uploadDocuments(Long kbId) throws Exception {
        // Upload a single document
        documentService.upload(kbId, new File("product-guide.pdf"));
        
        // Batch upload documents
        List<File> files = Arrays.asList(
            new File("faq.pdf"),
            new File("api-doc.md"),
            new File("changelog.txt")
        );
        documentService.batchUpload(kbId, files);
    }
}

RAG Query

java
public RAGResponse queryKnowledgeBase(Long kbId, String query) {
    // Configure retrieval parameters
    RAGConfig config = RAGConfig.builder()
        .topK(5)
        .similarityThreshold(0.7)
        .maxContextLength(4000)
        .build();
    
    // Execute query
    return ragService.query(kbId, query, config);
}

public RAGResponse queryWithHistory(Long kbId, String query, List<ChatMessage> history) {
    // Query with conversation history
    return ragService.queryWithHistory(kbId, query, history);
}

Streaming RAG Query

java
public Flux<RAGChunk> queryStream(Long kbId, String query) {
    return ragService.queryStream(kbId, query)
        .doOnNext(chunk -> {
            // Process each chunk
            System.out.print(chunk.getContent());
        })
        .doOnComplete(() -> {
            // Query complete
            System.out.println("\nQuery complete");
        });
}

Knowledge Graph Queries

Create Knowledge Graph

java
@Service
public class KGExampleService {
    
    @Autowired
    private KnowledgeGraphService kgService;
    
    @Autowired
    private EntityExtractionService entityService;
    
    @Autowired
    private RelationExtractionService relationService;
    
    public KnowledgeGraph createKnowledgeGraph() {
        KnowledgeGraph kg = new KnowledgeGraph();
        kg.setName("Product Knowledge Graph");
        kg.setDescription("Relationship network between products, technologies, and teams");
        
        return kgService.save(kg);
    }
    
    public void buildFromDocument(Long kgId, Long documentId) {
        // Build knowledge graph from document
        kgService.buildFromDocument(kgId, documentId);
    }
}

Query Knowledge Graph

java
public KGQueryResult queryKnowledgeGraph(Long kgId, String query) {
    // Execute query
    KGQueryResult result = kgService.query(kgId, query);
    
    // Get entities
    List<KGEntity> entities = result.getEntities();
    entities.forEach(entity -> {
        System.out.println("Entity: " + entity.getName());
        System.out.println("Type: " + entity.getType());
        System.out.println("Description: " + entity.getDescription());
    });
    
    // Get relations
    List<KGRelation> relations = result.getRelations();
    relations.forEach(relation -> {
        System.out.println("Relation: " + relation.getSourceName() 
            + " -> " + relation.getType() 
            + " -> " + relation.getTargetName());
    });
    
    return result;
}

Graph Traversal Queries

java
public List<KGEntity> findNeighbors(Long entityId, int hops) {
    // Find neighboring entities
    return kgService.findNeighbors(entityId, hops);
}

public List<KGRelation> findPath(Long startId, Long endId) {
    // Find path between two entities
    return kgService.findPath(startId, endId);
}

Digital Human Interaction

Create Digital Human

java
@Service
public class HumanExampleService {
    
    @Autowired
    private DigitalHumanService humanService;
    
    @Autowired
    private TtsService ttsService;
    
    public DigitalHuman createDigitalHuman() {
        DigitalHuman human = new DigitalHuman();
        human.setName("Assistant");
        human.setVoice("zh-CN-Neural");
        human.setTtsProvider("volcengine");
        human.setSpeed(1.0);
        human.setPitch(1.0);
        
        return humanService.save(human);
    }
}

Text-to-Speech

java
public byte[] synthesizeSpeech(Long humanId, String text) {
    // Get digital human configuration
    DigitalHuman human = humanService.findById(humanId);
    
    // Get TTS service
    TtsService ttsService = ttsProviderFactory.getProvider(human.getTtsProvider());
    
    // Synthesize speech
    return ttsService.synthesize(human.getVoice(), text);
}

public void saveAudioFile(byte[] audioData, String fileName) throws Exception {
    // Save audio file
    Path path = Paths.get("audio/" + fileName);
    Files.write(path, audioData);
}

Streaming Text-to-Speech

java
public Flux<byte[]> synthesizeSpeechStream(Long humanId, String text) {
    DigitalHuman human = humanService.findById(humanId);
    TtsService ttsService = ttsProviderFactory.getProvider(human.getTtsProvider());
    
    return ttsService.synthesizeStream(human.getVoice(), text);
}

AI Excel Generation

Generate Excel Report

java
@Service
public class ExcelExampleService {
    
    @Autowired
    private AiExcelService excelService;
    
    public ExcelFile generateReport(String request) {
        // Generate Excel from natural language
        return excelService.generate(request);
    }
    
    public ExcelFile generateFromTemplate(Long templateId, Map<String, Object> data) {
        // Generate Excel from template
        return excelService.generateFromTemplate(templateId, data);
    }
}

Conversational Generation

java
public ExcelChatResponse chatGenerate(String sessionId, String message) {
    // Generate Excel through conversation
    return excelChatService.chat(sessionId, message);
}

Complete Example: Smart Customer Service

java
@Service
public class SmartCustomerServiceExample {
    
    @Autowired
    private WorkflowService workflowService;
    
    @Autowired
    private KnowledgeBaseService kbService;
    
    @Autowired
    private RAGService ragService;
    
    @Autowired
    private ChatService chatService;
    
    /**
     * Initialize smart customer service system
     */
    public void init() {
        // 1. Create knowledge base
        KnowledgeBase kb = kbService.create("Customer Service Knowledge Base", "Frequently asked questions and solutions");
        
        // 2. Upload FAQ document
        documentService.upload(kb.getId(), new File("faq.pdf"));
        
        // 3. Create customer service workflow
        WorkflowDefinition workflow = createCustomerServiceWorkflow(kb.getId());
        
        // 4. Save workflow
        workflowService.save(workflow);
    }
    
    /**
     * Create customer service workflow
     */
    private WorkflowDefinition createCustomerServiceWorkflow(Long kbId) {
        WorkflowDefinition workflow = new WorkflowDefinition();
        workflow.setName("Smart Customer Service Workflow");
        
        // Add nodes
        WorkflowNode start = new WorkflowNode("START", "Start");
        WorkflowNode intent = new WorkflowNode("LLM", "Intent Recognition");
        WorkflowNode rag = new WorkflowNode("KNOWLEDGE_RETRIEVAL", "Knowledge Retrieval");
        WorkflowNode answer = new WorkflowNode("LLM", "Generate Answer");
        WorkflowNode end = new WorkflowNode("END", "End");
        
        // Configure nodes
        intent.setConfig(Map.of(
            "model", "gpt-4",
            "systemPrompt", "Identify user intent, return: Return, Inquiry, Complaint, Other"
        ));
        
        rag.setConfig(Map.of(
            "knowledgeBaseId", kbId,
            "topK", 3
        ));
        
        answer.setConfig(Map.of(
            "model", "gpt-4",
            "systemPrompt", "Answer the user's question based on the following knowledge base content:\n{{context}}"
        ));
        
        // Connect nodes
        workflow.addEdge(start, intent);
        workflow.addEdge(intent, rag);
        workflow.addEdge(rag, answer);
        workflow.addEdge(answer, end);
        
        return workflow;
    }
    
    /**
     * Handle customer message
     */
    public String handleCustomerMessage(String conversationId, String message) {
        // Execute workflow
        WorkflowExecution execution = workflowService.execute(
            workflowId,
            Map.of("userQuery", message)
        );
        
        return execution.getResult();
    }
}

Copyright © 2023-2026 nitemoon.cn All Rights Reserved