Repository navigation
feat(core,tools): add conversation memory, thought preservation, and interactive chat CLI #5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
0d7401d
bd71400
4b7fe52
36fc019
b9de295
2b2dfd5
04bced1
f06a7b7
6c773a8
cb52963
e35a973
c8cb925
c67f9ee
426d86c
47fea60
318bb6c
cf708e4
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,6 +5,7 @@ | |
| from dotenv import load_dotenv | ||
| from openai import OpenAI | ||
|
|
||
| from agentoffice.core.memory import AgentMemory | ||
| from agentoffice.core.tool import BaseTool | ||
|
|
||
| load_dotenv() | ||
|
|
@@ -16,14 +17,26 @@ def __init__( | |
| model: str = "gemini-3.5-flash-lite", | ||
| system_prompt: str = "", | ||
| tools: list[BaseTool] | None = None, | ||
| history: list[dict] | None = None, | ||
| on_tool_call=None, | ||
| memory=None, | ||
| client: OpenAI | None = None, | ||
| ): | ||
| self.client = OpenAI( | ||
| self.client = client or OpenAI( | ||
| api_key=os.getenv("GEMINI_API_KEY"), | ||
| base_url="https://generativelanguage.googleapis.com/v1beta/openai/", | ||
| ) | ||
| self.model = model | ||
| self.system_prompt = system_prompt | ||
| self.tool_map: dict[str, BaseTool] = {} | ||
| self.on_tool_call = on_tool_call | ||
| if memory is not None: | ||
| self.memory = memory | ||
| else: | ||
| self.memory = AgentMemory(system_prompt=system_prompt) | ||
| if history: | ||
| self.memory.history = list(history) | ||
|
|
||
| if tools: | ||
| for tool in tools: | ||
| self.register_tool(tool) | ||
|
|
@@ -44,35 +57,80 @@ def execute_tool(self, name: str, arguments: str) -> str: | |
| return json.dumps({"error": f"{type(e).__name__}: {e}"}) | ||
|
|
||
| def run(self, message: str, max_iterations: int = 10) -> str: | ||
| messages = [] | ||
| if self.system_prompt: | ||
| messages.append({"role": "system", "content": self.system_prompt}) | ||
| messages.append({"role": "user", "content": message}) | ||
| prev_history_len = len(self.memory.history) | ||
| self.memory.add_user_message(message) | ||
|
|
||
| tools_schema = [tool.to_schema() for tool in self.tool_map.values()] or None | ||
|
|
||
| for turn in range(max_iterations): | ||
| response = self.client.chat.completions.create( | ||
| model=self.model, | ||
| messages=messages, | ||
| tools=tools_schema, | ||
| ) | ||
| try: | ||
| for turn in range(max_iterations): | ||
| # Check token budget before each LLM call to prevent exceeding limits | ||
| self.compact(force=False) | ||
|
|
||
| response_message = response.choices[0].message | ||
| messages.append(response_message) | ||
| response = self.client.chat.completions.create( | ||
| model=self.model, | ||
| tools=tools_schema, | ||
| messages=self.memory.history, | ||
| ) | ||
|
|
||
| if not response_message.tool_calls: | ||
| return response_message.content | ||
| response_message = response.choices[0].message | ||
| if response.usage: | ||
| self.memory.record_usage(response.usage) | ||
| self.memory.add_assistant_message(response_message) | ||
|
|
||
| for tool_call in response_message.tool_calls: | ||
| result = self.execute_tool( | ||
| tool_call.function.name, tool_call.function.arguments | ||
| ) | ||
| messages.append( | ||
| { | ||
| "role": "tool", | ||
| "tool_call_id": tool_call.id, | ||
| "name": tool_call.function.name, | ||
| "content": result, | ||
| } | ||
| ) | ||
| return "Max iterations reached" | ||
| if not response_message.tool_calls: | ||
| return response_message.content | ||
|
|
||
| for tool_call in response_message.tool_calls: | ||
| try: | ||
| result = self.execute_tool( | ||
| tool_call.function.name, tool_call.function.arguments | ||
| ) | ||
| except Exception as exc: | ||
| # Record the error so the conversation history remains valid | ||
| result = f"Error executing {tool_call.function.name}: {exc}" | ||
|
|
||
| self.memory.add_tool_message( | ||
| tool_call.id, tool_call.function.name, result | ||
| ) | ||
|
|
||
| if self.on_tool_call: | ||
| try: | ||
| print(f"Tool called: {tool_call.function.name}") | ||
| self.on_tool_call( | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Notify callbacks only after the tool batch is complete. If a response requests two tools and the first callback calls Record the entire batch before invoking callbacks. If a callback resets history, stop the old run before it sends another model request. Keep callback exceptions isolated so an observer failure still cannot interrupt tool execution. As per path instructions, conversation history must “never orphan a
|
||
| tool_call.function.name, | ||
| tool_call.function.arguments, | ||
| result, | ||
| ) | ||
| except Exception: | ||
| # Callback failures should never crash other tool executions | ||
| pass | ||
| return "Max tool calls reached" | ||
| except Exception: | ||
| # If the request failed before completing an assistant turn, remove | ||
| # the unanswered user message so history maintains a valid role sequence | ||
| if ( | ||
| len(self.memory.history) == prev_history_len + 1 | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Remove the unanswered turn by identity, not by history length. If compaction replaces an older user/assistant pair with one summary, the history can shrink before the first conversation request fails. This length check then leaves the new, unanswered user message in history. The next run sends it with the next user message. Track the exact user entry and whether its first assistant response was stored. On a first-request failure, remove that entry from the current history. Keep the compacted prefix and any tool exchange that already completed. As per path instructions, “Conversation history must maintain valid OpenAI/Gemini message role sequences.”
|
||
| and self.memory.history[-1].get("role") == "user" | ||
| ): | ||
| self.memory.history.pop() | ||
| raise | ||
|
|
||
| def clear_history(self): | ||
| self.memory.clear_history() | ||
| return self.memory.history | ||
|
|
||
| @property | ||
| def history(self) -> list[dict]: | ||
| return self.memory.history | ||
|
|
||
| @property | ||
| def session_usage(self) -> dict: | ||
| return self.memory.session_usage | ||
|
|
||
| @property | ||
| def last_usage(self) -> dict: | ||
| return self.memory.last_usage | ||
|
|
||
| def compact(self, force: bool = True): | ||
| return self.memory.compact(self.client, self.model, force=force) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,219 @@ | ||
| class AgentMemory: | ||
| def __init__( | ||
| self, | ||
| system_prompt: str = "", | ||
| token_threshold: int = 12000, | ||
| max_tool_chars: int = 40000, | ||
| ): | ||
| self.system_prompt = system_prompt | ||
| self.token_threshold = token_threshold | ||
| self.max_tool_chars = max_tool_chars | ||
| self.history: list[dict] = [] | ||
|
|
||
| if self.system_prompt: | ||
| self.history.append({"role": "system", "content": self.system_prompt}) | ||
|
|
||
| self.last_usage = { | ||
| "prompt_tokens": 0, | ||
| "completion_tokens": 0, | ||
| "cached_tokens": 0, | ||
| "total_tokens": 0, | ||
| } | ||
| self.session_usage = { | ||
| "prompt_tokens": 0, | ||
| "completion_tokens": 0, | ||
| "cached_tokens": 0, | ||
| "total_tokens": 0, | ||
| "compactions": 0, | ||
| "tokens_saved": 0, | ||
| } | ||
|
|
||
| def add_user_message(self, content: str) -> None: | ||
| self.history.append({"role": "user", "content": content}) | ||
|
|
||
| def add_tool_message(self, tool_call_id: str, name: str, content: str) -> None: | ||
| if len(content) > self.max_tool_chars: | ||
| content = ( | ||
| content[: self.max_tool_chars] + "\n... [Truncated: output too large]" | ||
| ) | ||
|
|
||
| self.history.append( | ||
| { | ||
| "role": "tool", | ||
| "tool_call_id": tool_call_id, | ||
| "name": name, | ||
| "content": content, | ||
| } | ||
| ) | ||
|
|
||
| def add_assistant_message(self, message) -> None: | ||
| if isinstance(message, dict): | ||
| self.history.append(message) | ||
| return | ||
|
|
||
| msg_dict: dict = { | ||
| "role": "assistant", | ||
| "content": getattr(message, "content", None) or "", | ||
| } | ||
|
|
||
| tool_calls = getattr(message, "tool_calls", None) | ||
| if tool_calls: | ||
| msg_dict["tool_calls"] = [] | ||
| for tc in tool_calls: | ||
| tc_data = { | ||
| "id": tc.id, | ||
| "type": "function", | ||
| "function": { | ||
| "name": tc.function.name, | ||
| "arguments": tc.function.arguments, | ||
| }, | ||
| } | ||
| extra_content = getattr(tc, "extra_content", None) | ||
| if extra_content: | ||
| tc_data["extra_content"] = extra_content | ||
| msg_dict["tool_calls"].append(tc_data) | ||
|
|
||
| self.history.append(msg_dict) | ||
|
|
||
| def record_usage(self, usage) -> None: | ||
| if not usage: | ||
| return | ||
|
|
||
| cached = ( | ||
| getattr(usage.prompt_tokens_details, "cached_tokens", 0) | ||
| if hasattr(usage, "prompt_tokens_details") and usage.prompt_tokens_details | ||
| else 0 | ||
| ) or 0 | ||
|
|
||
| self.last_usage = { | ||
| "prompt_tokens": usage.prompt_tokens, | ||
| "completion_tokens": usage.completion_tokens, | ||
| "cached_tokens": cached, | ||
| "total_tokens": usage.total_tokens, | ||
| } | ||
| self.session_usage["count"] = self.session_usage.get("count", 0) + 1 | ||
| for key in self.last_usage: | ||
| self.session_usage[key] = ( | ||
| self.session_usage.get(key, 0) + self.last_usage[key] | ||
| ) | ||
|
|
||
| def clear_history(self): | ||
| self.history = [] | ||
| if self.system_prompt: | ||
| self.history.append({"role": "system", "content": self.system_prompt}) | ||
| return self.history | ||
|
|
||
| def get_history(self): | ||
| return self.history | ||
|
|
||
| def get_last_usage(self): | ||
| return self.last_usage | ||
|
|
||
| def get_session_usage(self): | ||
| return self.session_usage | ||
|
|
||
| def compact(self, client, model: str, force: bool = True): | ||
| if not force and self.last_usage.get("prompt_tokens", 0) < self.token_threshold: | ||
| return None | ||
| slice_index = self._find_safe_slice_index() | ||
| if slice_index is None: | ||
| return None | ||
| start_index = ( | ||
| 1 if (self.history and self.history[0].get("role") == "system") else 0 | ||
| ) | ||
| old_messages = self.history[start_index:slice_index] | ||
|
|
||
| if not old_messages: | ||
| return None | ||
|
|
||
| text_for_compaction = [] | ||
| for msg in old_messages: | ||
| role = msg.get("role", "") | ||
| content = msg.get("content", "") | ||
| if content: | ||
| text_for_compaction.append(f"{role.upper()}: {content}") | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
| # Include tool calls even if content is empty/None | ||
| if msg.get("tool_calls"): | ||
| tool_info = [] | ||
| for tc in msg["tool_calls"]: | ||
| tool_name = tc.get("function", {}).get("name", "") | ||
| tool_args = str(tc.get("function", {}).get("arguments", "")) | ||
| tool_info.append(f"{tool_name}({tool_args})") | ||
| if tool_info: | ||
| text_for_compaction.append( | ||
| f"{role.upper()}: called {'; '.join(tool_info)}" | ||
| ) | ||
|
|
||
| transcript = "\n\n".join(text_for_compaction) | ||
|
|
||
| summary_messages = [ | ||
| { | ||
| "role": "system", | ||
| "content": ( | ||
| "You are a helpful assistant. Summarize the following conversation history concisely. " | ||
| "Crucially preserve: any file names, paths, identifiers, technical decisions, key " | ||
| "results, and the current task status." | ||
| ), | ||
| }, | ||
| {"role": "user", "content": f"Conversation:\n{transcript}"}, | ||
| ] | ||
|
|
||
| tokens_before = self.last_usage.get("total_tokens", 0) | ||
|
|
||
| response = client.chat.completions.create( | ||
| model=model, | ||
| messages=summary_messages, | ||
| ) | ||
| if response.usage: | ||
| # Record summary usage into session totals only without corrupting last_usage | ||
| self.session_usage["count"] = self.session_usage.get("count", 0) + 1 | ||
| self.session_usage["prompt_tokens"] += ( | ||
| getattr(response.usage, "prompt_tokens", 0) or 0 | ||
| ) | ||
| self.session_usage["completion_tokens"] += ( | ||
| getattr(response.usage, "completion_tokens", 0) or 0 | ||
| ) | ||
| cached = ( | ||
| getattr(response.usage.prompt_tokens_details, "cached_tokens", 0) | ||
| if hasattr(response.usage, "prompt_tokens_details") | ||
| and response.usage.prompt_tokens_details | ||
| else 0 | ||
| ) or 0 | ||
| self.session_usage["cached_tokens"] += cached | ||
| self.session_usage["total_tokens"] += ( | ||
| getattr(response.usage, "total_tokens", 0) or 0 | ||
| ) | ||
|
|
||
| summary = (response.choices[0].message.content or "").strip() | ||
| if not summary: | ||
| return None | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
| new_history = ( | ||
| self.history[:1] | ||
| if self.history and self.history[0].get("role") == "system" | ||
| else [] | ||
| ) | ||
| new_history.append( | ||
| { | ||
| "role": "assistant", | ||
| "content": f"[Summary of previous conversation]\n{summary}", | ||
| } | ||
| ) | ||
| new_history.extend(self.history[slice_index:]) | ||
| self.history = new_history | ||
| self.session_usage["compactions"] += 1 | ||
| self.session_usage["tokens_saved"] += tokens_before | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do not report the entire previous completion as tokens saved. The test credits 15,500 saved tokens, including 500 completion tokens. The new prompt still contains the retained turns and the summary, but neither affects this counter. A compaction that makes the prompt larger would get the same credit. Compare prompt sizes before and after compaction under the same counting method. If those sizes are unavailable, omit the savings figure or label it as an estimate. Update the test to check the reduction rather than the previous request’s total.
|
||
| return summary | ||
|
|
||
| def _find_safe_slice_index(self, keep_ratio: float = 0.25) -> int: | ||
|
|
||
| if len(self.history) <= 3: | ||
| return None | ||
|
|
||
| target = int(len(self.history) * (1 - keep_ratio)) | ||
|
|
||
| for i in range(target, 0, -1): | ||
| if self.history[i]["role"] == "user": | ||
| return i | ||
| return None | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do not persist a user turn when no iteration can run.
With
max_iterations=0,run()stores the user message and returns"Max tool calls reached"without making a model request. The next run sends the undispatched prompt alongside the new prompt. Reject a nonpositive iteration limit before appending to memory, or return the limit result before the append. Leave positive iteration limits unchanged.