kodeagent 0.13.0__tar.gz → 0.14.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {kodeagent-0.13.0/src/kodeagent.egg-info → kodeagent-0.14.0}/PKG-INFO +23 -7
- {kodeagent-0.13.0 → kodeagent-0.14.0}/README.md +22 -6
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/_version.py +1 -1
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/examples.py +26 -1
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/fca.py +42 -7
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/kodeagent.py +90 -33
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/kutils.py +179 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0/src/kodeagent.egg-info}/PKG-INFO +23 -7
- {kodeagent-0.13.0 → kodeagent-0.14.0}/LICENSE +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/MANIFEST.in +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/pyproject.toml +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/requirements.txt +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/setup.cfg +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/__init__.py +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/agents/__init__.py +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/agents/csv_agent.py +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/code_reviewer.py +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/code_runner.py +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/file_tracker.py +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/history_formatter.py +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/models.py +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/orchestrator.py +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/pattern_detector.py +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/prompts/agent_plan.txt +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/prompts/code_guardrail.txt +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/prompts/contextual_summary.txt +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/prompts/observation.txt +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/prompts/salvage_response.txt +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/prompts/system/codeact.txt +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/prompts/system/csv_analyst.txt +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/prompts/system/function_calling.txt +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/prompts/system/observer.txt +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/prompts/system/plan_updater.txt +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/prompts/system/planner.txt +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/prompts/system/react.txt +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/prompts/update_plan.txt +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/tools.py +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/tracer.py +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent/usage_tracker.py +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent.egg-info/SOURCES.txt +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent.egg-info/dependency_links.txt +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent.egg-info/requires.txt +0 -0
- {kodeagent-0.13.0 → kodeagent-0.14.0}/src/kodeagent.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: kodeagent
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.14.0
|
|
4
4
|
Summary: A minimalistic approach to building AI agents
|
|
5
5
|
Author-email: Barun Saha <your.email@example.com>
|
|
6
6
|
Project-URL: Homepage, https://github.com/barun-saha/kodeagent
|
|
@@ -73,8 +73,8 @@ Use KodeAgent because it offers:
|
|
|
73
73
|
Also, here are a few reasons why you shouldn't use KodeAgent:
|
|
74
74
|
|
|
75
75
|
- KodeAgent is actively evolving, meaning some aspects may change.
|
|
76
|
-
- You want to use some of the well-known frameworks.
|
|
77
|
-
- You need a full-fledged platform with built-in long-term, persistent memory management.
|
|
76
|
+
- You want to use some of the well-known frameworks or task-specific agents.
|
|
77
|
+
- You need a full-fledged platform with built-in **automated** long-term, persistent memory management (KodeAgent supports manual state injection, but does not provide a persistence layer).
|
|
78
78
|
|
|
79
79
|
|
|
80
80
|
## 🚀 Quick Start
|
|
@@ -184,9 +184,13 @@ async for response in agent.run(
|
|
|
184
184
|
|
|
185
185
|
Check out the [CSVAnalysisAgent documentation](https://kodeagent.readthedocs.io/en/latest/specialized_agents.html) for more details.
|
|
186
186
|
|
|
187
|
-
### Memory(less)
|
|
188
187
|
|
|
189
|
-
|
|
188
|
+
## 🧠 Memory and State Management
|
|
189
|
+
|
|
190
|
+
By default, any agent in KodeAgent is **memoryless** across tasks—each task begins with a clean slate. You have two ways to manage state across runs:
|
|
191
|
+
|
|
192
|
+
### 1. Recurrent Mode (Single-Task Context)
|
|
193
|
+
For simple follow-up tasks within the same session, use **Recurrent Mode**. This automatically appends the description and result of the *immediately preceding* task to the current context:
|
|
190
194
|
|
|
191
195
|
```python
|
|
192
196
|
# Enable recurrent mode to leverage context from the previous run
|
|
@@ -194,9 +198,21 @@ async for response in agent.run('Double the previous result', recurrent_mode=Tru
|
|
|
194
198
|
print_response(response)
|
|
195
199
|
```
|
|
196
200
|
|
|
197
|
-
|
|
201
|
+
### 2. Chat History Injection (Full Session Context)
|
|
202
|
+
For multi-session persistence or complex state management, you can manually inject an existing OpenAI-compliant **Chat History**. This allows you to resume conversations from external storage or database:
|
|
203
|
+
|
|
204
|
+
```python
|
|
205
|
+
history = [
|
|
206
|
+
{"role": "user", "content": "What is 5 + 5?"},
|
|
207
|
+
{"role": "assistant", "content": "10.0"}
|
|
208
|
+
]
|
|
209
|
+
|
|
210
|
+
# Resume with full external context
|
|
211
|
+
async for response in agent.run('Now add 20 to that', chat_history=history):
|
|
212
|
+
print_response(response)
|
|
213
|
+
```
|
|
198
214
|
|
|
199
|
-
For more examples,
|
|
215
|
+
For more examples, see the [examples.py](src/kodeagent/examples.py) module and [API documentation](https://kodeagent.readthedocs.io/en/latest/usage.html).
|
|
200
216
|
|
|
201
217
|
|
|
202
218
|
### API Configuration
|
|
@@ -38,8 +38,8 @@ Use KodeAgent because it offers:
|
|
|
38
38
|
Also, here are a few reasons why you shouldn't use KodeAgent:
|
|
39
39
|
|
|
40
40
|
- KodeAgent is actively evolving, meaning some aspects may change.
|
|
41
|
-
- You want to use some of the well-known frameworks.
|
|
42
|
-
- You need a full-fledged platform with built-in long-term, persistent memory management.
|
|
41
|
+
- You want to use some of the well-known frameworks or task-specific agents.
|
|
42
|
+
- You need a full-fledged platform with built-in **automated** long-term, persistent memory management (KodeAgent supports manual state injection, but does not provide a persistence layer).
|
|
43
43
|
|
|
44
44
|
|
|
45
45
|
## 🚀 Quick Start
|
|
@@ -149,9 +149,13 @@ async for response in agent.run(
|
|
|
149
149
|
|
|
150
150
|
Check out the [CSVAnalysisAgent documentation](https://kodeagent.readthedocs.io/en/latest/specialized_agents.html) for more details.
|
|
151
151
|
|
|
152
|
-
### Memory(less)
|
|
153
152
|
|
|
154
|
-
|
|
153
|
+
## 🧠 Memory and State Management
|
|
154
|
+
|
|
155
|
+
By default, any agent in KodeAgent is **memoryless** across tasks—each task begins with a clean slate. You have two ways to manage state across runs:
|
|
156
|
+
|
|
157
|
+
### 1. Recurrent Mode (Single-Task Context)
|
|
158
|
+
For simple follow-up tasks within the same session, use **Recurrent Mode**. This automatically appends the description and result of the *immediately preceding* task to the current context:
|
|
155
159
|
|
|
156
160
|
```python
|
|
157
161
|
# Enable recurrent mode to leverage context from the previous run
|
|
@@ -159,9 +163,21 @@ async for response in agent.run('Double the previous result', recurrent_mode=Tru
|
|
|
159
163
|
print_response(response)
|
|
160
164
|
```
|
|
161
165
|
|
|
162
|
-
|
|
166
|
+
### 2. Chat History Injection (Full Session Context)
|
|
167
|
+
For multi-session persistence or complex state management, you can manually inject an existing OpenAI-compliant **Chat History**. This allows you to resume conversations from external storage or database:
|
|
168
|
+
|
|
169
|
+
```python
|
|
170
|
+
history = [
|
|
171
|
+
{"role": "user", "content": "What is 5 + 5?"},
|
|
172
|
+
{"role": "assistant", "content": "10.0"}
|
|
173
|
+
]
|
|
174
|
+
|
|
175
|
+
# Resume with full external context
|
|
176
|
+
async for response in agent.run('Now add 20 to that', chat_history=history):
|
|
177
|
+
print_response(response)
|
|
178
|
+
```
|
|
163
179
|
|
|
164
|
-
For more examples,
|
|
180
|
+
For more examples, see the [examples.py](src/kodeagent/examples.py) module and [API documentation](https://kodeagent.readthedocs.io/en/latest/usage.html).
|
|
165
181
|
|
|
166
182
|
|
|
167
183
|
### API Configuration
|
|
@@ -148,6 +148,31 @@ async def _run_examples_async(
|
|
|
148
148
|
):
|
|
149
149
|
print_response(response, only_final=True)
|
|
150
150
|
|
|
151
|
+
print('\n\nDemonstrating Chat History Injection:\n')
|
|
152
|
+
# Initial history from a previous session or external storage
|
|
153
|
+
history = [
|
|
154
|
+
{'role': 'user', 'content': 'What is 5 + 5?'},
|
|
155
|
+
{
|
|
156
|
+
'role': 'assistant',
|
|
157
|
+
'content': 'I will calculate 5 + 5.',
|
|
158
|
+
'tool_calls': [
|
|
159
|
+
{
|
|
160
|
+
'id': 'call_123',
|
|
161
|
+
'type': 'function',
|
|
162
|
+
'function': {
|
|
163
|
+
'name': 'calculator',
|
|
164
|
+
'arguments': '{"expression": "5 + 5"}',
|
|
165
|
+
},
|
|
166
|
+
}
|
|
167
|
+
],
|
|
168
|
+
},
|
|
169
|
+
{'role': 'tool', 'tool_call_id': 'call_123', 'name': 'calculator', 'content': '10.0'},
|
|
170
|
+
{'role': 'assistant', 'content': 'The result is 10.0.'},
|
|
171
|
+
]
|
|
172
|
+
print('Resuming with existing history...')
|
|
173
|
+
async for response in agent.run('Now add 20 to that result', chat_history=history):
|
|
174
|
+
print_response(response, only_final=True)
|
|
175
|
+
|
|
151
176
|
atype = agent_type.lower()
|
|
152
177
|
|
|
153
178
|
if atype == 'codeact':
|
|
@@ -169,7 +194,7 @@ async def run_examples(
|
|
|
169
194
|
) -> None:
|
|
170
195
|
"""Run KodeAgent with a list of pre-defined tasks and the choice of agent.
|
|
171
196
|
Some of the tasks include files or URLs.
|
|
172
|
-
The
|
|
197
|
+
The demo includes demonstrations of `recurrent_mode` and `chat_history` injection.
|
|
173
198
|
|
|
174
199
|
Args:
|
|
175
200
|
agent_type: Which agent to run; one of `react`, `codeact`, or `fca`.
|
|
@@ -4,6 +4,7 @@ reproduced here to keep this module self-contained and optimized.
|
|
|
4
4
|
"""
|
|
5
5
|
|
|
6
6
|
import asyncio
|
|
7
|
+
import copy
|
|
7
8
|
import json
|
|
8
9
|
import logging
|
|
9
10
|
import re
|
|
@@ -353,6 +354,7 @@ class FunctionCallingAgent:
|
|
|
353
354
|
task_id: str | None = None,
|
|
354
355
|
use_planning: bool = True,
|
|
355
356
|
recurrent_mode: bool = False,
|
|
357
|
+
chat_history: list[dict] | None = None,
|
|
356
358
|
) -> None:
|
|
357
359
|
"""Initialize the running of a task.
|
|
358
360
|
|
|
@@ -362,7 +364,10 @@ class FunctionCallingAgent:
|
|
|
362
364
|
task_id: Optional task ID.
|
|
363
365
|
use_planning: If True, generate a simple plan at the beginning of the task.
|
|
364
366
|
recurrent_mode: If True, the agent will continue to run on the same task
|
|
365
|
-
|
|
367
|
+
until it decides to stop, allowing for more dynamic interactions.
|
|
368
|
+
chat_history: Optional pre-built OpenAI-compliant chat history to inject
|
|
369
|
+
as the base context. When provided, the new task message is appended
|
|
370
|
+
at the end of this history. Mutually exclusive with ``recurrent_mode``.
|
|
366
371
|
"""
|
|
367
372
|
if not task_desc or not task_desc.strip():
|
|
368
373
|
raise ValueError('Task description cannot be empty!')
|
|
@@ -384,10 +389,23 @@ class FunctionCallingAgent:
|
|
|
384
389
|
if task_id is not None:
|
|
385
390
|
task_kwargs['id'] = task_id
|
|
386
391
|
self.task = Task(**task_kwargs)
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
392
|
+
|
|
393
|
+
if chat_history is not None:
|
|
394
|
+
# Validate and deep-copy the injected history
|
|
395
|
+
ku.validate_chat_history(
|
|
396
|
+
chat_history,
|
|
397
|
+
tool_names=set(self.tool_map.keys()),
|
|
398
|
+
)
|
|
399
|
+
base_history = copy.deepcopy(chat_history)
|
|
400
|
+
# Ensure a system message is present at index 0
|
|
401
|
+
if not (base_history and base_history[0].get('role') == 'system'):
|
|
402
|
+
base_history.insert(0, {'role': 'system', 'content': self.system_prompt})
|
|
403
|
+
self.chat_history = base_history + list(user_task_msg)
|
|
404
|
+
else:
|
|
405
|
+
self.chat_history = [
|
|
406
|
+
{'role': 'system', 'content': self.system_prompt},
|
|
407
|
+
*user_task_msg,
|
|
408
|
+
]
|
|
391
409
|
|
|
392
410
|
if use_planning:
|
|
393
411
|
planner = Planner(
|
|
@@ -479,6 +497,7 @@ class FunctionCallingAgent:
|
|
|
479
497
|
use_planning: bool = True,
|
|
480
498
|
recurrent_mode: bool = False,
|
|
481
499
|
loop_threshold: int = 3,
|
|
500
|
+
chat_history: list[dict] | None = None,
|
|
482
501
|
) -> AsyncIterator[AgentResponse]:
|
|
483
502
|
"""Main loop for the agent to process input and execute tools until finished.
|
|
484
503
|
If an SLM call fails, it tries up to 3 times with a backoff before terminating.
|
|
@@ -494,13 +513,29 @@ class FunctionCallingAgent:
|
|
|
494
513
|
Note: not invoked after a hard-stop due to repeated SLM failures.
|
|
495
514
|
use_planning: If True, generate a simple plan at the beginning of the task.
|
|
496
515
|
recurrent_mode: If True, the agent continues from the previous task result,
|
|
497
|
-
allowing for multi-turn workflows.
|
|
516
|
+
allowing for multi-turn workflows. Mutually exclusive with ``chat_history``.
|
|
498
517
|
loop_threshold: Number of consecutive same tool calls before triggering loop detection.
|
|
518
|
+
chat_history: Optional pre-built OpenAI-compliant history to inject as the
|
|
519
|
+
base context for this run. The new task message is appended at the end.
|
|
520
|
+
Mutually exclusive with ``recurrent_mode``.
|
|
499
521
|
|
|
500
522
|
Yields:
|
|
501
523
|
AgentResponse: Streaming log, step, and final responses.
|
|
524
|
+
|
|
525
|
+
Raises:
|
|
526
|
+
ValueError: If both ``recurrent_mode`` and ``chat_history`` are set, or if
|
|
527
|
+
the provided history fails OpenAI compliance validation.
|
|
502
528
|
"""
|
|
503
|
-
|
|
529
|
+
if recurrent_mode and chat_history is not None:
|
|
530
|
+
raise ValueError(
|
|
531
|
+
'recurrent_mode and chat_history are mutually exclusive. '
|
|
532
|
+
'Use one or the other, not both.'
|
|
533
|
+
)
|
|
534
|
+
|
|
535
|
+
await self._run_init(
|
|
536
|
+
task, files, use_planning=use_planning, recurrent_mode=recurrent_mode,
|
|
537
|
+
chat_history=chat_history,
|
|
538
|
+
)
|
|
504
539
|
|
|
505
540
|
n_turns = 0
|
|
506
541
|
self.final_answer_found = False
|
|
@@ -3,6 +3,7 @@ Implements ReAct and CodeAct agents, supported by Planner and Observer.
|
|
|
3
3
|
"""
|
|
4
4
|
|
|
5
5
|
import asyncio
|
|
6
|
+
import copy
|
|
6
7
|
import inspect
|
|
7
8
|
import json
|
|
8
9
|
import random
|
|
@@ -203,7 +204,11 @@ class Agent(ABC):
|
|
|
203
204
|
return ''.join(context_parts)
|
|
204
205
|
|
|
205
206
|
def _run_init(
|
|
206
|
-
self,
|
|
207
|
+
self,
|
|
208
|
+
task: str,
|
|
209
|
+
files: list[str] | None = None,
|
|
210
|
+
task_id: str | None = None,
|
|
211
|
+
chat_history: list[dict] | None = None,
|
|
207
212
|
) -> None:
|
|
208
213
|
"""Initialize the running of a task by an agent.
|
|
209
214
|
|
|
@@ -211,9 +216,13 @@ class Agent(ABC):
|
|
|
211
216
|
task: Task description.
|
|
212
217
|
files: Optional files for the task.
|
|
213
218
|
task_id: Optional task ID.
|
|
219
|
+
chat_history: Optional pre-built OpenAI-compliant chat history to inject.
|
|
220
|
+
When provided, this history becomes the base of ``self.chat_history``
|
|
221
|
+
(deep-copied to avoid mutating the caller's object).
|
|
214
222
|
|
|
215
223
|
Raises:
|
|
216
|
-
ValueError: If task is empty
|
|
224
|
+
ValueError: If task is empty, files list is invalid, or the provided
|
|
225
|
+
history fails OpenAI compliance validation.
|
|
217
226
|
"""
|
|
218
227
|
if not task or not task.strip():
|
|
219
228
|
raise ValueError('Task description cannot be empty!')
|
|
@@ -222,6 +231,21 @@ class Agent(ABC):
|
|
|
222
231
|
if files and len(files) > MAX_TASK_FILES:
|
|
223
232
|
raise ValueError(f'Too many files provided for the task (max {MAX_TASK_FILES})!')
|
|
224
233
|
|
|
234
|
+
# Validate and apply injected history
|
|
235
|
+
if chat_history is not None:
|
|
236
|
+
ku.validate_chat_history(chat_history, tool_names=self.tool_names)
|
|
237
|
+
base = copy.deepcopy(chat_history)
|
|
238
|
+
# If it has no system message at index 0, prepend the agent's own system prompt.
|
|
239
|
+
if not (base and base[0].get('role') == 'system'):
|
|
240
|
+
base.insert(0, {'role': 'system', 'content': self.get_system_prompt_content()})
|
|
241
|
+
|
|
242
|
+
self.chat_history = base
|
|
243
|
+
# Track where injected context ends so new task messages are appended after
|
|
244
|
+
self.msg_idx_of_new_task = len(self.chat_history)
|
|
245
|
+
else:
|
|
246
|
+
self.init_history()
|
|
247
|
+
self.msg_idx_of_new_task = len(self.chat_history)
|
|
248
|
+
|
|
225
249
|
self.task = Task(description=task, files=files)
|
|
226
250
|
self.task_output_files = []
|
|
227
251
|
if task_id:
|
|
@@ -323,6 +347,7 @@ class Agent(ABC):
|
|
|
323
347
|
max_iterations: int | None = None,
|
|
324
348
|
recurrent_mode: bool = False,
|
|
325
349
|
summarize_progress_on_failure: bool = True,
|
|
350
|
+
chat_history: list[dict] | None = None,
|
|
326
351
|
) -> AsyncIterator[AgentResponse]:
|
|
327
352
|
"""Execute a task using the agent.
|
|
328
353
|
|
|
@@ -331,11 +356,19 @@ class Agent(ABC):
|
|
|
331
356
|
files: List of files associated with the task.
|
|
332
357
|
task_id: Optional task ID.
|
|
333
358
|
max_iterations: Optional maximum number of iterations.
|
|
334
|
-
recurrent_mode: Whether to run in recurrent mode
|
|
359
|
+
recurrent_mode: Whether to run in recurrent mode (augments task text
|
|
360
|
+
with the previous task description and result). Mutually exclusive
|
|
361
|
+
with ``chat_history``.
|
|
335
362
|
summarize_progress_on_failure: Whether to summarize progress on failure.
|
|
363
|
+
chat_history: Optional pre-built OpenAI-compliant history to inject as
|
|
364
|
+
the base context for this task run. Mutually exclusive with
|
|
365
|
+
``recurrent_mode``.
|
|
336
366
|
|
|
337
367
|
Returns:
|
|
338
368
|
AsyncIterator[AgentResponse]: An iterator yielding agent responses.
|
|
369
|
+
|
|
370
|
+
Raises:
|
|
371
|
+
ValueError: If both ``recurrent_mode`` and ``chat_history`` are provided.
|
|
339
372
|
"""
|
|
340
373
|
|
|
341
374
|
def response(
|
|
@@ -549,6 +582,21 @@ class Agent(ABC):
|
|
|
549
582
|
|
|
550
583
|
return '\n'.join(segments)
|
|
551
584
|
|
|
585
|
+
def get_system_prompt_content(self) -> str:
|
|
586
|
+
"""Return the formatted system prompt string for this agent.
|
|
587
|
+
|
|
588
|
+
Subclasses should override this to include additional format variables.
|
|
589
|
+
|
|
590
|
+
Returns:
|
|
591
|
+
The formatted system prompt.
|
|
592
|
+
"""
|
|
593
|
+
if not self.system_prompt:
|
|
594
|
+
return ''
|
|
595
|
+
|
|
596
|
+
return self.system_prompt.format(
|
|
597
|
+
persona=self.persona or '', tools=self.get_tools_description()
|
|
598
|
+
)
|
|
599
|
+
|
|
552
600
|
def clear_history(self):
|
|
553
601
|
"""Clear the agent's message history."""
|
|
554
602
|
self.chat_history = []
|
|
@@ -650,10 +698,7 @@ class ReActAgent(Agent):
|
|
|
650
698
|
|
|
651
699
|
def init_history(self):
|
|
652
700
|
"""Initialize the agent's message history with the system prompt."""
|
|
653
|
-
|
|
654
|
-
persona=self.persona or '', tools=self.get_tools_description()
|
|
655
|
-
)
|
|
656
|
-
self.chat_history = [{'role': 'system', 'content': content}]
|
|
701
|
+
self.chat_history = [{'role': 'system', 'content': self.get_system_prompt_content()}]
|
|
657
702
|
self.final_answer_found = False
|
|
658
703
|
|
|
659
704
|
async def _create_initial_plan(self):
|
|
@@ -677,13 +722,13 @@ class ReActAgent(Agent):
|
|
|
677
722
|
|
|
678
723
|
async def pre_run(self) -> AsyncIterator[AgentResponse]:
|
|
679
724
|
"""Perform setup before the main run loop.
|
|
680
|
-
- Initialize task and history.
|
|
725
|
+
- Initialize task and history (or ensure injected history has a system prompt).
|
|
681
726
|
- Create initial plan.
|
|
682
727
|
|
|
683
728
|
Returns:
|
|
684
729
|
AsyncIterator[AgentResponse]: Iterator of agent responses.
|
|
685
730
|
"""
|
|
686
|
-
self.
|
|
731
|
+
self.final_answer_found = False
|
|
687
732
|
|
|
688
733
|
yield self.response(
|
|
689
734
|
rtype='log', value=f'Solving task: `{self.task.description}`', channel='run'
|
|
@@ -763,6 +808,7 @@ class ReActAgent(Agent):
|
|
|
763
808
|
max_iterations: int | None = None,
|
|
764
809
|
recurrent_mode: bool = False,
|
|
765
810
|
summarize_progress_on_failure: bool = True,
|
|
811
|
+
chat_history: list[dict] | None = None,
|
|
766
812
|
) -> AsyncIterator[AgentResponse]:
|
|
767
813
|
"""Solve a task using ReAct's TAO loop (or CodeAct's TCO loop).
|
|
768
814
|
|
|
@@ -772,23 +818,36 @@ class ReActAgent(Agent):
|
|
|
772
818
|
task_id: Optional task ID.
|
|
773
819
|
max_iterations: Optional max iterations for the task.
|
|
774
820
|
recurrent_mode: If True, augment task with previous task context.
|
|
821
|
+
Mutually exclusive with ``chat_history``.
|
|
775
822
|
summarize_progress_on_failure: Whether to summarize progress if
|
|
776
|
-
|
|
823
|
+
the agent fails to solve the task in max iterations.
|
|
824
|
+
chat_history: Optional pre-built OpenAI-compliant history to inject
|
|
825
|
+
as the base context for this run. The new task message is appended
|
|
826
|
+
on top. Mutually exclusive with ``recurrent_mode``.
|
|
777
827
|
|
|
778
828
|
Returns:
|
|
779
829
|
Step updates on the task and the final response.
|
|
780
830
|
|
|
781
831
|
Raises:
|
|
782
|
-
ValueError: If task is empty
|
|
832
|
+
ValueError: If task is empty, too many files provided, both
|
|
833
|
+
``recurrent_mode`` and ``chat_history`` are set, or the provided
|
|
834
|
+
history fails OpenAI compliance validation.
|
|
783
835
|
RetryError: If LLM calls fail after max retries.
|
|
784
836
|
"""
|
|
837
|
+
if recurrent_mode and chat_history is not None:
|
|
838
|
+
raise ValueError(
|
|
839
|
+
'recurrent_mode and chat_history are mutually exclusive.'
|
|
840
|
+
' Use one or the other, not both.'
|
|
841
|
+
)
|
|
842
|
+
|
|
785
843
|
if recurrent_mode and self.task is not None:
|
|
786
844
|
task = await self._augment_task_with_previous(task)
|
|
787
845
|
logger.debug('Recurrent mode enabled: augmented task with previous context')
|
|
788
846
|
|
|
789
847
|
# 1. run() calls _run_init()
|
|
790
|
-
# 2. pre_run() calls init_history() and does
|
|
791
|
-
|
|
848
|
+
# 2. pre_run() calls init_history() (or applies injected history) and does
|
|
849
|
+
# the logging/planning
|
|
850
|
+
self._run_init(task, files, task_id, chat_history=chat_history)
|
|
792
851
|
|
|
793
852
|
# Execute pre-run hook
|
|
794
853
|
async for response in self.pre_run():
|
|
@@ -1241,13 +1300,11 @@ class ReActAgent(Agent):
|
|
|
1241
1300
|
tool_call_id = self._get_last_tool_call_id()
|
|
1242
1301
|
|
|
1243
1302
|
# Always use role='tool' for tool results
|
|
1244
|
-
self.add_to_history(
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
}
|
|
1250
|
-
)
|
|
1303
|
+
self.add_to_history({
|
|
1304
|
+
'role': 'tool',
|
|
1305
|
+
'content': str(result),
|
|
1306
|
+
'tool_call_id': tool_call_id,
|
|
1307
|
+
})
|
|
1251
1308
|
|
|
1252
1309
|
act_span.update(
|
|
1253
1310
|
status='success',
|
|
@@ -1289,13 +1346,11 @@ class ReActAgent(Agent):
|
|
|
1289
1346
|
tool_call_id = self._get_last_tool_call_id()
|
|
1290
1347
|
|
|
1291
1348
|
# Use role='tool' for tool errors too
|
|
1292
|
-
self.add_to_history(
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
}
|
|
1298
|
-
)
|
|
1349
|
+
self.add_to_history({
|
|
1350
|
+
'role': 'tool',
|
|
1351
|
+
'content': result,
|
|
1352
|
+
'tool_call_id': tool_call_id,
|
|
1353
|
+
})
|
|
1299
1354
|
yield self.response(
|
|
1300
1355
|
rtype='step',
|
|
1301
1356
|
value=result,
|
|
@@ -1538,15 +1593,17 @@ class CodeActAgent(ReActAgent):
|
|
|
1538
1593
|
f'Could not extract valid Code or Answer from response. Text: {text[:300]}...'
|
|
1539
1594
|
)
|
|
1540
1595
|
|
|
1541
|
-
def
|
|
1542
|
-
"""
|
|
1543
|
-
|
|
1596
|
+
def get_system_prompt_content(self) -> str:
|
|
1597
|
+
"""Return the formatted system prompt string for CodeAct agent."""
|
|
1598
|
+
return self.system_prompt.format(
|
|
1544
1599
|
persona=self.persona or '',
|
|
1545
1600
|
tools=self.get_tools_description(),
|
|
1546
|
-
authorized_imports='\n'.join([f'- {imp}' for imp in self.allowed_imports]),
|
|
1601
|
+
authorized_imports='\n'.join([f'- {imp}' for imp in (self.allowed_imports or [])]),
|
|
1547
1602
|
)
|
|
1548
|
-
|
|
1549
|
-
|
|
1603
|
+
|
|
1604
|
+
def init_history(self):
|
|
1605
|
+
"""Initialize message history with system prompt for CodeAct agent."""
|
|
1606
|
+
super().init_history()
|
|
1550
1607
|
|
|
1551
1608
|
async def _think(self) -> AsyncIterator[AgentResponse]:
|
|
1552
1609
|
"""Think step for CodeAct agent.
|
|
@@ -502,6 +502,185 @@ def parse_param_descriptions(doc: str) -> dict[str, str]:
|
|
|
502
502
|
return param_docs
|
|
503
503
|
|
|
504
504
|
|
|
505
|
+
VALID_ROLES = {'system', 'user', 'assistant', 'tool'}
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def validate_chat_history(history: list[dict], tool_names: set[str] | None = None) -> None:
|
|
509
|
+
"""Validate that a provided chat history is OpenAI-compliant.
|
|
510
|
+
|
|
511
|
+
Performs stringent structural and semantic checks on each message. Raises
|
|
512
|
+
``ValueError`` with a precise description on the first problem found.
|
|
513
|
+
|
|
514
|
+
Args:
|
|
515
|
+
history: The chat history to validate. Must be a non-empty ``list[dict]``.
|
|
516
|
+
tool_names: Optional set of tool names registered on the agent. When
|
|
517
|
+
provided, tool call names not in this set emit a ``logger.warning``.
|
|
518
|
+
|
|
519
|
+
Raises:
|
|
520
|
+
ValueError: If the history fails any structural or compliance check.
|
|
521
|
+
"""
|
|
522
|
+
if not isinstance(history, list):
|
|
523
|
+
raise ValueError(
|
|
524
|
+
f'chat_history must be a list[dict], got {type(history).__name__}.'
|
|
525
|
+
)
|
|
526
|
+
if not history:
|
|
527
|
+
raise ValueError('chat_history must not be empty.')
|
|
528
|
+
|
|
529
|
+
system_seen_at: int | None = None
|
|
530
|
+
requested_tool_call_ids: set[str] = set()
|
|
531
|
+
|
|
532
|
+
for idx, msg in enumerate(history):
|
|
533
|
+
if not isinstance(msg, dict):
|
|
534
|
+
raise ValueError(
|
|
535
|
+
f'chat_history[{idx}]: each message must be a dict, '
|
|
536
|
+
f'got {type(msg).__name__}.'
|
|
537
|
+
)
|
|
538
|
+
|
|
539
|
+
role = msg.get('role')
|
|
540
|
+
if role not in VALID_ROLES:
|
|
541
|
+
raise ValueError(
|
|
542
|
+
f"chat_history[{idx}]: 'role' must be one of {sorted(VALID_ROLES)}, "
|
|
543
|
+
f"got {role!r}."
|
|
544
|
+
)
|
|
545
|
+
|
|
546
|
+
# ── system message rules ──────────────────────────────────────────
|
|
547
|
+
if role == 'system':
|
|
548
|
+
if idx != 0:
|
|
549
|
+
raise ValueError(
|
|
550
|
+
f'chat_history[{idx}]: system message must be at index 0, '
|
|
551
|
+
f'not at index {idx}.'
|
|
552
|
+
)
|
|
553
|
+
system_seen_at = idx
|
|
554
|
+
if msg.get('content') is None:
|
|
555
|
+
raise ValueError(
|
|
556
|
+
f"chat_history[{idx}]: system message must have a non-None 'content'."
|
|
557
|
+
)
|
|
558
|
+
|
|
559
|
+
# ── user message rules ────────────────────────────────────────────
|
|
560
|
+
elif role == 'user':
|
|
561
|
+
if msg.get('content') is None:
|
|
562
|
+
raise ValueError(
|
|
563
|
+
f"chat_history[{idx}]: user message must have a non-None 'content'."
|
|
564
|
+
)
|
|
565
|
+
|
|
566
|
+
# ── assistant message rules ───────────────────────────────────────
|
|
567
|
+
elif role == 'assistant':
|
|
568
|
+
tool_calls = msg.get('tool_calls')
|
|
569
|
+
content = msg.get('content')
|
|
570
|
+
|
|
571
|
+
if tool_calls is None and content is None:
|
|
572
|
+
raise ValueError(
|
|
573
|
+
f'chat_history[{idx}]: assistant message must have either '
|
|
574
|
+
f"'content' or 'tool_calls'."
|
|
575
|
+
)
|
|
576
|
+
|
|
577
|
+
if tool_calls is not None:
|
|
578
|
+
if not isinstance(tool_calls, list):
|
|
579
|
+
raise ValueError(
|
|
580
|
+
f"chat_history[{idx}]: 'tool_calls' must be a list, "
|
|
581
|
+
f'got {type(tool_calls).__name__}.'
|
|
582
|
+
)
|
|
583
|
+
for tc_idx, tc in enumerate(tool_calls):
|
|
584
|
+
if not isinstance(tc, dict):
|
|
585
|
+
raise ValueError(
|
|
586
|
+
f'chat_history[{idx}].tool_calls[{tc_idx}]: '
|
|
587
|
+
f'each tool call must be a dict, got {type(tc).__name__}.'
|
|
588
|
+
)
|
|
589
|
+
tc_id = tc.get('id')
|
|
590
|
+
if not tc_id or not isinstance(tc_id, str):
|
|
591
|
+
raise ValueError(
|
|
592
|
+
f'chat_history[{idx}].tool_calls[{tc_idx}]: '
|
|
593
|
+
f"missing or empty 'id' (string required)."
|
|
594
|
+
)
|
|
595
|
+
|
|
596
|
+
# Track for subsequent tool result validation
|
|
597
|
+
requested_tool_call_ids.add(tc_id)
|
|
598
|
+
|
|
599
|
+
if tc.get('type') != 'function':
|
|
600
|
+
raise ValueError(
|
|
601
|
+
f'chat_history[{idx}].tool_calls[{tc_idx}]: '
|
|
602
|
+
f"'type' must be 'function', got {tc.get('type')!r}."
|
|
603
|
+
)
|
|
604
|
+
fn = tc.get('function')
|
|
605
|
+
if not isinstance(fn, dict):
|
|
606
|
+
raise ValueError(
|
|
607
|
+
f'chat_history[{idx}].tool_calls[{tc_idx}]: '
|
|
608
|
+
f"'function' must be a dict, got {type(fn).__name__}."
|
|
609
|
+
)
|
|
610
|
+
fn_name = fn.get('name')
|
|
611
|
+
if not fn_name or not isinstance(fn_name, str):
|
|
612
|
+
raise ValueError(
|
|
613
|
+
f'chat_history[{idx}].tool_calls[{tc_idx}]: '
|
|
614
|
+
f"'function.name' must be a non-empty string."
|
|
615
|
+
)
|
|
616
|
+
if not isinstance(fn.get('arguments'), str):
|
|
617
|
+
raise ValueError(
|
|
618
|
+
f'chat_history[{idx}].tool_calls[{tc_idx}]: '
|
|
619
|
+
f"'function.arguments' must be a string (JSON-encoded)."
|
|
620
|
+
)
|
|
621
|
+
# Warn about unknown tool names
|
|
622
|
+
if tool_names is not None and fn_name not in tool_names:
|
|
623
|
+
logger.warning(
|
|
624
|
+
'chat_history[%d].tool_calls[%d]: tool name %r not registered '
|
|
625
|
+
'on this agent (known: %s). The LLM will not re-call it.',
|
|
626
|
+
idx,
|
|
627
|
+
tc_idx,
|
|
628
|
+
fn_name,
|
|
629
|
+
sorted(tool_names),
|
|
630
|
+
)
|
|
631
|
+
|
|
632
|
+
# ── tool result message rules ─────────────────────────────────────
|
|
633
|
+
elif role == 'tool':
|
|
634
|
+
tc_id = msg.get('tool_call_id')
|
|
635
|
+
if not tc_id or not isinstance(tc_id, str):
|
|
636
|
+
raise ValueError(
|
|
637
|
+
f"chat_history[{idx}]: tool message missing or empty 'tool_call_id' "
|
|
638
|
+
f'(string required).'
|
|
639
|
+
)
|
|
640
|
+
name = msg.get('name')
|
|
641
|
+
if not name or not isinstance(name, str):
|
|
642
|
+
raise ValueError(
|
|
643
|
+
f"chat_history[{idx}]: tool message missing or empty 'name' "
|
|
644
|
+
f'(string required).'
|
|
645
|
+
)
|
|
646
|
+
if not isinstance(msg.get('content'), str):
|
|
647
|
+
raise ValueError(
|
|
648
|
+
f"chat_history[{idx}]: tool message 'content' must be a string, "
|
|
649
|
+
f"got {type(msg.get('content')).__name__}."
|
|
650
|
+
)
|
|
651
|
+
# Ensure this result refers to a tool call that was actually requested
|
|
652
|
+
if tc_id not in requested_tool_call_ids:
|
|
653
|
+
raise ValueError(
|
|
654
|
+
f"chat_history[{idx}]: tool message refers to unknown "
|
|
655
|
+
f"tool_call_id {tc_id!r}."
|
|
656
|
+
)
|
|
657
|
+
|
|
658
|
+
# ── pending tool call check ───────────────────────────────────────────
|
|
659
|
+
# Walk backwards; if the last assistant message has tool_calls, verify
|
|
660
|
+
# that every id appears in a subsequent tool message.
|
|
661
|
+
tool_result_ids: set[str] = set()
|
|
662
|
+
for msg in reversed(history):
|
|
663
|
+
role = msg.get('role')
|
|
664
|
+
if role == 'tool':
|
|
665
|
+
tool_result_ids.add(msg.get('tool_call_id', ''))
|
|
666
|
+
elif role == 'assistant':
|
|
667
|
+
pending = msg.get('tool_calls')
|
|
668
|
+
if pending:
|
|
669
|
+
unresolved = [
|
|
670
|
+
tc['id']
|
|
671
|
+
for tc in pending
|
|
672
|
+
if isinstance(tc, dict) and tc.get('id') not in tool_result_ids
|
|
673
|
+
]
|
|
674
|
+
if unresolved:
|
|
675
|
+
raise ValueError(
|
|
676
|
+
f'chat_history ends with unresolved tool call(s): '
|
|
677
|
+
f'{unresolved}. Each tool_call must have a corresponding '
|
|
678
|
+
f"'tool' message before appending new messages."
|
|
679
|
+
)
|
|
680
|
+
# Stop at the first assistant message from the end
|
|
681
|
+
break
|
|
682
|
+
|
|
683
|
+
|
|
505
684
|
def build_tool_schema(
|
|
506
685
|
fn: Callable, just_first_line: bool = False, as_text: bool = True
|
|
507
686
|
) -> dict[str, Any] | str:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: kodeagent
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.14.0
|
|
4
4
|
Summary: A minimalistic approach to building AI agents
|
|
5
5
|
Author-email: Barun Saha <your.email@example.com>
|
|
6
6
|
Project-URL: Homepage, https://github.com/barun-saha/kodeagent
|
|
@@ -73,8 +73,8 @@ Use KodeAgent because it offers:
|
|
|
73
73
|
Also, here are a few reasons why you shouldn't use KodeAgent:
|
|
74
74
|
|
|
75
75
|
- KodeAgent is actively evolving, meaning some aspects may change.
|
|
76
|
-
- You want to use some of the well-known frameworks.
|
|
77
|
-
- You need a full-fledged platform with built-in long-term, persistent memory management.
|
|
76
|
+
- You want to use some of the well-known frameworks or task-specific agents.
|
|
77
|
+
- You need a full-fledged platform with built-in **automated** long-term, persistent memory management (KodeAgent supports manual state injection, but does not provide a persistence layer).
|
|
78
78
|
|
|
79
79
|
|
|
80
80
|
## 🚀 Quick Start
|
|
@@ -184,9 +184,13 @@ async for response in agent.run(
|
|
|
184
184
|
|
|
185
185
|
Check out the [CSVAnalysisAgent documentation](https://kodeagent.readthedocs.io/en/latest/specialized_agents.html) for more details.
|
|
186
186
|
|
|
187
|
-
### Memory(less)
|
|
188
187
|
|
|
189
|
-
|
|
188
|
+
## 🧠 Memory and State Management
|
|
189
|
+
|
|
190
|
+
By default, any agent in KodeAgent is **memoryless** across tasks—each task begins with a clean slate. You have two ways to manage state across runs:
|
|
191
|
+
|
|
192
|
+
### 1. Recurrent Mode (Single-Task Context)
|
|
193
|
+
For simple follow-up tasks within the same session, use **Recurrent Mode**. This automatically appends the description and result of the *immediately preceding* task to the current context:
|
|
190
194
|
|
|
191
195
|
```python
|
|
192
196
|
# Enable recurrent mode to leverage context from the previous run
|
|
@@ -194,9 +198,21 @@ async for response in agent.run('Double the previous result', recurrent_mode=Tru
|
|
|
194
198
|
print_response(response)
|
|
195
199
|
```
|
|
196
200
|
|
|
197
|
-
|
|
201
|
+
### 2. Chat History Injection (Full Session Context)
|
|
202
|
+
For multi-session persistence or complex state management, you can manually inject an existing OpenAI-compliant **Chat History**. This allows you to resume conversations from external storage or database:
|
|
203
|
+
|
|
204
|
+
```python
|
|
205
|
+
history = [
|
|
206
|
+
{"role": "user", "content": "What is 5 + 5?"},
|
|
207
|
+
{"role": "assistant", "content": "10.0"}
|
|
208
|
+
]
|
|
209
|
+
|
|
210
|
+
# Resume with full external context
|
|
211
|
+
async for response in agent.run('Now add 20 to that', chat_history=history):
|
|
212
|
+
print_response(response)
|
|
213
|
+
```
|
|
198
214
|
|
|
199
|
-
For more examples,
|
|
215
|
+
For more examples, see the [examples.py](src/kodeagent/examples.py) module and [API documentation](https://kodeagent.readthedocs.io/en/latest/usage.html).
|
|
200
216
|
|
|
201
217
|
|
|
202
218
|
### API Configuration
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|