|
| 1 | +from strands.agent.conversation_manager import ConversationManager |
| 2 | +from strands.agent import Agent |
| 3 | +from strands.types.content import Messages |
| 4 | +from typing import Optional |
| 5 | +from kurrentdbclient import KurrentDBClient, NewEvent, StreamState |
| 6 | +from kurrentdbclient.exceptions import NotFoundError |
| 7 | +import json |
| 8 | + |
| 9 | +""" |
| 10 | +Example usage: |
| 11 | +from strands import Agent |
| 12 | +from strands.models.anthropic import AnthropicModel |
| 13 | +from kurrentdb_session_manager import KurrentDBConversationManager |
| 14 | +
|
| 15 | +unique_run_id = "run-01" |
| 16 | +kurrentdb_conversation_manager = ( |
| 17 | + KurrentDBConversationManager(unique_run_id, "esdb://localhost:2113?Tls=false") |
| 18 | +) # replace with your actual connection string |
| 19 | +
|
| 20 | +# kurrentdb_conversation_manager.set_max_window_age(60) # Set max window age to 60 seconds |
| 21 | +model = AnthropicModel( |
| 22 | + client_args={ |
| 23 | + "api_key": "Your API KEY here", # Replace with your actual API key |
| 24 | + }, |
| 25 | + # **model_config |
| 26 | + max_tokens= 4096, |
| 27 | + model_id="claude-3-5-haiku-latest", |
| 28 | + params={ |
| 29 | + "temperature": 0.7, |
| 30 | + } |
| 31 | + ) |
| 32 | +
|
| 33 | +poet_agent = Agent( |
| 34 | + system_prompt="You are a hungry poet who loves to write haikus about everything.", |
| 35 | + model=model, |
| 36 | + conversation_manager=kurrentdb_conversation_manager, # Assuming no specific conversation manager is needed |
| 37 | +) |
| 38 | +poet_agent("Write a haiku about the beauty of nature.") |
| 39 | +kurrentdb_conversation_manager.save_agent_state(unique_run_id=unique_run_id, |
| 40 | + state={"messages": poet_agent.messages, |
| 41 | + "system_prompt": poet_agent.system_prompt}) |
| 42 | +poet_agent("Based on the previous haiku, write another one about the changing seasons.") |
| 43 | +poet_agent = kurrentdb_conversation_manager.restore_agent_state(agent=poet_agent,unique_run_id=unique_run_id) |
| 44 | +poet_agent("What did we just talk about?") |
| 45 | +""" |
| 46 | +class KurrentDBConversationManager(ConversationManager): |
| 47 | + client: KurrentDBClient |
| 48 | + def __init__(self, unique_run_id:str, |
| 49 | + connection_string: str = "esdb://localhost:2113?Tls=false", |
| 50 | + window_size: int = 40, |
| 51 | + reducer_function = lambda x: x) -> None: |
| 52 | + """ |
| 53 | + Initializes the KurrentDB conversation manager with a connection string. |
| 54 | + :param connection_string: The connection string for KurrentDB. |
| 55 | + """ |
| 56 | + self.client = KurrentDBClient(connection_string) |
| 57 | + self.stream_id = unique_run_id |
| 58 | + self.checkpoint = -1 # Default checkpoint value, no messages processed yet |
| 59 | + self.window_size = window_size # Maximum number of messages to keep in the conversation |
| 60 | + self.reducer_function = reducer_function # Function to reduce messages if needed |
| 61 | + |
| 62 | + def apply_management(self, messages: Messages) -> None: |
| 63 | + """Apply management strategies to the messages list.""" |
| 64 | + justRestored = False |
| 65 | + try: |
| 66 | + events = self.client.get_stream( |
| 67 | + stream_name=self.stream_id, |
| 68 | + resolve_links=True, |
| 69 | + backwards=True, |
| 70 | + limit=1 |
| 71 | + ) # Get the last event in the stream |
| 72 | + if len(events) == 1 and events[0].type == "StateRestored": |
| 73 | + # then we don't need to remove any message |
| 74 | + justRestored = True |
| 75 | + self.checkpoint = events[0].stream_position |
| 76 | + |
| 77 | + except NotFoundError as e: |
| 78 | + #this means that the stream does not exist yet |
| 79 | + if self.checkpoint != -1: |
| 80 | + # Handle inconsistency in the outside the conversation manager |
| 81 | + raise Exception("Inconsistent state: Stream not found but checkpoint exists.") |
| 82 | + if self.checkpoint != -1 and justRestored == False: |
| 83 | + # remove already added messages from the messages list |
| 84 | + messages = messages[self.checkpoint + 1:] # Keep only new messages |
| 85 | + events = [] |
| 86 | + for message in messages: |
| 87 | + metadata = {} |
| 88 | + event = NewEvent(type=message["role"], data=bytes(json.dumps(message), 'utf-8'), |
| 89 | + content_type='application/json', |
| 90 | + metadata=bytes(json.dumps(metadata), 'utf-8')) |
| 91 | + events.append(event) |
| 92 | + self.client.append_to_stream( |
| 93 | + stream_name=self.stream_id, |
| 94 | + events=events, |
| 95 | + current_version=StreamState.ANY # TODO: tighten this up if needed if agent is called in parallel and order is important(is that possible?) |
| 96 | + ) |
| 97 | + self.checkpoint += len(events) # Update checkpoint after appending messages |
| 98 | + |
| 99 | + |
| 100 | + def reduce_context(self, messages: Messages, e: Optional[Exception] = None) -> Optional[Messages]: |
| 101 | + """Function to reduce the context window size when it exceeds the model's limit. |
| 102 | + """ |
| 103 | + return self.reducer_function(messages) |
| 104 | + |
| 105 | + def set_max_window_age(self, max_age: int) -> None: |
| 106 | + """Set the maximum age for messages in the conversation inside KurrentDB.""" |
| 107 | + self.client.set_stream_metadata(self.stream_id, |
| 108 | + metadata={"$maxAge": max_age}, |
| 109 | + current_version=StreamState.ANY |
| 110 | + ) |
| 111 | + |
| 112 | + def set_max_window_size(self, max_count: int) -> None: |
| 113 | + """Set the maximum size for the conversation history inside KurrentDB.""" |
| 114 | + self.client.set_stream_metadata(self.stream_id, |
| 115 | + metadata={"$maxCount": max_count}, |
| 116 | + current_version=StreamState.ANY |
| 117 | + ) |
| 118 | + |
| 119 | + def save_agent_state(self, unique_run_id: str, state: dict) -> None: |
| 120 | + """ |
| 121 | + Saves the agent state variables to a checkpoint stream in KurrentDB. |
| 122 | + This event contains which position in the stream the agent is at and other state variables. |
| 123 | + """ |
| 124 | + del state["messages"] # We already keep messages in the stream, so we don't need to save them again. |
| 125 | + state["kurrentdb_checkpoint"] = self.checkpoint |
| 126 | + state["kurrentdb_checkpoint_stream_id"] = unique_run_id |
| 127 | + event = NewEvent(type="agent_state", data=bytes(json.dumps(state), 'utf-8'), |
| 128 | + content_type='application/json') |
| 129 | + self.client.append_to_stream( |
| 130 | + stream_name="strands_checkpoint-" + unique_run_id, |
| 131 | + events=[event], |
| 132 | + current_version=StreamState.ANY) |
| 133 | + |
| 134 | + |
| 135 | + def restore_agent_state(self, agent: Agent, unique_run_id: str) -> Agent: |
| 136 | + """ |
| 137 | + Builds the agent state messages from a stream in KurrentDB. |
| 138 | + """ |
| 139 | + try: |
| 140 | + checkpoint_event = self.client.get_stream( |
| 141 | + stream_name="strands_checkpoint-" + unique_run_id, |
| 142 | + resolve_links=True, |
| 143 | + backwards=True, |
| 144 | + limit=1 |
| 145 | + ) |
| 146 | + if not checkpoint_event or len(checkpoint_event) == 0: |
| 147 | + return None # No state found |
| 148 | + |
| 149 | + state = json.loads(checkpoint_event[0].data.decode('utf-8')) |
| 150 | + self.stream_id = state["kurrentdb_checkpoint_stream_id"] |
| 151 | + self.checkpoint = state["kurrentdb_checkpoint"] |
| 152 | + |
| 153 | + messages = [] |
| 154 | + message_events = self.client.get_stream( |
| 155 | + stream_name=unique_run_id, |
| 156 | + resolve_links=True, |
| 157 | + backwards=True, |
| 158 | + stream_position=self.checkpoint, |
| 159 | + limit=self.window_size |
| 160 | + ) |
| 161 | + for event in message_events: |
| 162 | + if event.type == "StateRestored": |
| 163 | + break #reached of this state |
| 164 | + message = json.loads(event.data.decode('utf-8')) |
| 165 | + messages.insert(0,message) |
| 166 | + state["messages"] = messages |
| 167 | + agent.messages = messages |
| 168 | + |
| 169 | + #append an event to know restore state was called |
| 170 | + system_event = NewEvent( |
| 171 | + type="StateRestored", |
| 172 | + data=bytes("{}", 'utf-8'), |
| 173 | + content_type='application/json', |
| 174 | + metadata=bytes("{}", 'utf-8') |
| 175 | + ) |
| 176 | + self.client.append_to_stream( |
| 177 | + stream_name=unique_run_id, |
| 178 | + events=[system_event], |
| 179 | + current_version=StreamState.ANY |
| 180 | + ) |
| 181 | + return agent |
| 182 | + except NotFoundError as e: |
| 183 | + return agent #unchanged agent, no state to restore |
0 commit comments