|
| 1 | +# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +from langchain.agents import AgentState |
| 18 | +from langchain.agents.middleware import after_agent |
| 19 | +from langchain_core.messages.ai import AIMessage |
| 20 | +from langchain_core.messages.human import HumanMessage |
| 21 | +from langgraph.runtime import Runtime |
| 22 | + |
| 23 | +from veadk.community.langchain_ai.store.memory.viking_memory import ( |
| 24 | + VikingMemoryStore, |
| 25 | +) |
| 26 | +from veadk.utils.logger import get_logger |
| 27 | + |
| 28 | +logger = get_logger(__name__) |
| 29 | + |
| 30 | + |
| 31 | +@after_agent |
| 32 | +def save_session(state: AgentState, runtime: Runtime) -> None: |
| 33 | + """Save the session to the memory store.""" |
| 34 | + store: VikingMemoryStore | None = runtime.store |
| 35 | + if not store: |
| 36 | + return |
| 37 | + |
| 38 | + app_name = store.index |
| 39 | + user_id = runtime.context.user_id |
| 40 | + session_id = runtime.context.session_id |
| 41 | + |
| 42 | + messages = state.get("messages", []) |
| 43 | + logger.debug( |
| 44 | + f"Save session {session_id} for user {user_id} with {len(messages)} messages. messages={messages}" |
| 45 | + ) |
| 46 | + |
| 47 | + events = {} |
| 48 | + for message in messages: |
| 49 | + print(type(message)) |
| 50 | + if isinstance(message, HumanMessage): |
| 51 | + event = {"role": "user", "parts": [{"text": message.content}]} |
| 52 | + |
| 53 | + elif isinstance(message, AIMessage): |
| 54 | + event = {"role": "assistant", "parts": [{"text": message.content}]} |
| 55 | + else: |
| 56 | + ... |
| 57 | + |
| 58 | + events[message.id] = event |
| 59 | + |
| 60 | + store.put(namespace=(app_name, user_id), key=session_id, value=events) |
0 commit comments