001/*
002 *  Copyright (c) 2023-2026, Agents-Flex (fuhai999@gmail.com).
003 *  <p>
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *  <p>
008 *  http://www.apache.org/licenses/LICENSE-2.0
009 *  <p>
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package com.agentsflex.core.memory;
017
018import com.agentsflex.core.message.Message;
019
020import java.util.ArrayList;
021import java.util.List;
022import java.util.UUID;
023
024public class DefaultChatMemory implements ChatMemory {
025    private final Object id;
026    private final List<Message> messages = new ArrayList<>();
027
028    public DefaultChatMemory() {
029        this.id = UUID.randomUUID().toString();
030    }
031
032    public DefaultChatMemory(Object id) {
033        this.id = id;
034    }
035
036    @Override
037    public Object id() {
038        return id;
039    }
040
041    @Override
042    public List<Message> getMessages(int count) {
043        if (count <= 0) {
044            throw new IllegalArgumentException("count must be greater than 0");
045        }
046        if (count >= messages.size()) {
047            // 返回副本,避免修改原始消息
048            return new ArrayList<>(messages);
049        } else {
050            return messages.subList(messages.size() - count, messages.size());
051        }
052    }
053
054    @Override
055    public void addMessage(Message message) {
056        messages.add(message);
057    }
058
059    @Override
060    public void clear() {
061        messages.clear();
062    }
063
064
065}