kodeagent 0.12.3__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.12.3/src/kodeagent.egg-info → kodeagent-0.14.0}/PKG-INFO +23 -7
- {kodeagent-0.12.3 → kodeagent-0.14.0}/README.md +22 -6
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/_version.py +1 -1
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/agents/csv_agent.py +6 -3
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/examples.py +26 -1
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/fca.py +52 -47
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/kodeagent.py +168 -174
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/kutils.py +183 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0/src/kodeagent.egg-info}/PKG-INFO +23 -7
- {kodeagent-0.12.3 → kodeagent-0.14.0}/LICENSE +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/MANIFEST.in +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/pyproject.toml +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/requirements.txt +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/setup.cfg +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/__init__.py +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/agents/__init__.py +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/code_reviewer.py +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/code_runner.py +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/file_tracker.py +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/history_formatter.py +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/models.py +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/orchestrator.py +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/pattern_detector.py +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/prompts/agent_plan.txt +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/prompts/code_guardrail.txt +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/prompts/contextual_summary.txt +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/prompts/observation.txt +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/prompts/salvage_response.txt +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/prompts/system/codeact.txt +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/prompts/system/csv_analyst.txt +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/prompts/system/function_calling.txt +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/prompts/system/observer.txt +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/prompts/system/plan_updater.txt +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/prompts/system/planner.txt +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/prompts/system/react.txt +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/prompts/update_plan.txt +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/tools.py +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/tracer.py +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent/usage_tracker.py +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent.egg-info/SOURCES.txt +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent.egg-info/dependency_links.txt +0 -0
- {kodeagent-0.12.3 → kodeagent-0.14.0}/src/kodeagent.egg-info/requires.txt +0 -0
- {kodeagent-0.12.3 → 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
|
|
@@ -18,7 +18,6 @@ from dotenv import load_dotenv
|
|
|
18
18
|
|
|
19
19
|
load_dotenv()
|
|
20
20
|
|
|
21
|
-
from .. import kutils as ku
|
|
22
21
|
from ..kodeagent import ReActAgent
|
|
23
22
|
from ..models import AgentResponse
|
|
24
23
|
|
|
@@ -487,7 +486,11 @@ def sample_rows(filter_column: str, filter_value: str, n: int = 5) -> str:
|
|
|
487
486
|
|
|
488
487
|
n = min(n, 20)
|
|
489
488
|
try:
|
|
490
|
-
mask =
|
|
489
|
+
mask = (
|
|
490
|
+
df[filter_column]
|
|
491
|
+
.astype(str)
|
|
492
|
+
.str.contains(str(filter_value), case=False, na=False, regex=False)
|
|
493
|
+
)
|
|
491
494
|
subset = df[mask].head(n)
|
|
492
495
|
if len(subset) == 0:
|
|
493
496
|
return f'No rows found where {filter_column} contains "{filter_value}"'
|
|
@@ -635,4 +638,4 @@ async def main() -> None:
|
|
|
635
638
|
if __name__ == '__main__':
|
|
636
639
|
import asyncio
|
|
637
640
|
|
|
638
|
-
asyncio.run(main())
|
|
641
|
+
asyncio.run(main())
|
|
@@ -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,53 +4,23 @@ 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
|
|
10
11
|
from collections.abc import AsyncIterator, Callable
|
|
11
|
-
from
|
|
12
|
-
from typing import Any, Literal, TypedDict
|
|
12
|
+
from typing import Any, Literal
|
|
13
13
|
|
|
14
14
|
import litellm
|
|
15
15
|
|
|
16
16
|
from . import kutils as ku
|
|
17
17
|
from . import tools as dtools
|
|
18
|
+
from .models import AgentResponse, Task
|
|
18
19
|
from .orchestrator import Planner
|
|
19
20
|
|
|
20
21
|
logger = logging.getLogger(__name__)
|
|
21
22
|
|
|
22
23
|
|
|
23
|
-
@dataclass
|
|
24
|
-
class Task:
|
|
25
|
-
"""Represents a task for the agent to solve. A simplified version for SLMs."""
|
|
26
|
-
|
|
27
|
-
id: str | None
|
|
28
|
-
"""Optional unique identifier for the task."""
|
|
29
|
-
description: str
|
|
30
|
-
"""Text description of the task to be solved."""
|
|
31
|
-
result: str | None
|
|
32
|
-
"""Final result or answer after solving the task."""
|
|
33
|
-
steps_taken: int | None
|
|
34
|
-
"""Number of steps taken by the agent to solve the task."""
|
|
35
|
-
files: None = None
|
|
36
|
-
"""Unused placeholder only for compatibility with Planner."""
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
class AgentResponse(TypedDict):
|
|
40
|
-
"""Streaming response sent by an agent in the course of solving a task.
|
|
41
|
-
This class is reproduced here to keep this module self-contained and optimized.
|
|
42
|
-
"""
|
|
43
|
-
|
|
44
|
-
type: Literal['step', 'final', 'log']
|
|
45
|
-
"""Type of the response: 'step', 'final', or 'log'."""
|
|
46
|
-
channel: str | None
|
|
47
|
-
"""Optional channel name for the response."""
|
|
48
|
-
value: Any
|
|
49
|
-
"""Value of the response, varies by type."""
|
|
50
|
-
metadata: dict[str, Any] | None
|
|
51
|
-
"""Optional metadata associated with the response."""
|
|
52
|
-
|
|
53
|
-
|
|
54
24
|
FCA_SYSTEM_PROMPT = ku.read_prompt('system/function_calling.txt')
|
|
55
25
|
FINAL_ANSWER_TOOL_NAME = 'final_answer'
|
|
56
26
|
|
|
@@ -384,6 +354,7 @@ class FunctionCallingAgent:
|
|
|
384
354
|
task_id: str | None = None,
|
|
385
355
|
use_planning: bool = True,
|
|
386
356
|
recurrent_mode: bool = False,
|
|
357
|
+
chat_history: list[dict] | None = None,
|
|
387
358
|
) -> None:
|
|
388
359
|
"""Initialize the running of a task.
|
|
389
360
|
|
|
@@ -393,7 +364,10 @@ class FunctionCallingAgent:
|
|
|
393
364
|
task_id: Optional task ID.
|
|
394
365
|
use_planning: If True, generate a simple plan at the beginning of the task.
|
|
395
366
|
recurrent_mode: If True, the agent will continue to run on the same task
|
|
396
|
-
|
|
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``.
|
|
397
371
|
"""
|
|
398
372
|
if not task_desc or not task_desc.strip():
|
|
399
373
|
raise ValueError('Task description cannot be empty!')
|
|
@@ -411,11 +385,27 @@ class FunctionCallingAgent:
|
|
|
411
385
|
|
|
412
386
|
user_task_msg = ku.combine_user_messages(ku.make_user_message(task_description, task_files))
|
|
413
387
|
self.nudge_count = 0
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
388
|
+
task_kwargs: dict = {'description': task_desc}
|
|
389
|
+
if task_id is not None:
|
|
390
|
+
task_kwargs['id'] = task_id
|
|
391
|
+
self.task = Task(**task_kwargs)
|
|
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
|
+
]
|
|
419
409
|
|
|
420
410
|
if use_planning:
|
|
421
411
|
planner = Planner(
|
|
@@ -424,12 +414,10 @@ class FunctionCallingAgent:
|
|
|
424
414
|
)
|
|
425
415
|
await planner.create_plan(task=self.task, agent_type='fca')
|
|
426
416
|
formatted_plan = planner.get_formatted_plan()
|
|
427
|
-
self.chat_history.append(
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
}
|
|
432
|
-
)
|
|
417
|
+
self.chat_history.append({
|
|
418
|
+
'role': 'user',
|
|
419
|
+
'content': f'Here is a plan for this task:\n{formatted_plan}',
|
|
420
|
+
})
|
|
433
421
|
logger.info('Task plan:\n%s\n', formatted_plan)
|
|
434
422
|
|
|
435
423
|
def _format_history_as_text(self) -> str:
|
|
@@ -509,6 +497,7 @@ class FunctionCallingAgent:
|
|
|
509
497
|
use_planning: bool = True,
|
|
510
498
|
recurrent_mode: bool = False,
|
|
511
499
|
loop_threshold: int = 3,
|
|
500
|
+
chat_history: list[dict] | None = None,
|
|
512
501
|
) -> AsyncIterator[AgentResponse]:
|
|
513
502
|
"""Main loop for the agent to process input and execute tools until finished.
|
|
514
503
|
If an SLM call fails, it tries up to 3 times with a backoff before terminating.
|
|
@@ -524,13 +513,29 @@ class FunctionCallingAgent:
|
|
|
524
513
|
Note: not invoked after a hard-stop due to repeated SLM failures.
|
|
525
514
|
use_planning: If True, generate a simple plan at the beginning of the task.
|
|
526
515
|
recurrent_mode: If True, the agent continues from the previous task result,
|
|
527
|
-
allowing for multi-turn workflows.
|
|
516
|
+
allowing for multi-turn workflows. Mutually exclusive with ``chat_history``.
|
|
528
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``.
|
|
529
521
|
|
|
530
522
|
Yields:
|
|
531
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.
|
|
532
528
|
"""
|
|
533
|
-
|
|
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
|
+
)
|
|
534
539
|
|
|
535
540
|
n_turns = 0
|
|
536
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
|
|
@@ -11,6 +12,7 @@ import uuid
|
|
|
11
12
|
import warnings
|
|
12
13
|
from abc import ABC, abstractmethod
|
|
13
14
|
from collections.abc import AsyncIterator, Callable
|
|
15
|
+
from dataclasses import KW_ONLY, dataclass, field
|
|
14
16
|
from datetime import datetime
|
|
15
17
|
from json import JSONDecodeError
|
|
16
18
|
from typing import Any, ClassVar
|
|
@@ -72,95 +74,74 @@ MAX_RESPONSE_PARSING_ATTEMPTS = 3
|
|
|
72
74
|
MAX_TASK_FILES = 10
|
|
73
75
|
|
|
74
76
|
|
|
77
|
+
@dataclass
|
|
75
78
|
class Agent(ABC):
|
|
76
79
|
"""An abstract agent. Base class for all types of agents."""
|
|
77
80
|
|
|
81
|
+
model_name: str
|
|
82
|
+
_: KW_ONLY
|
|
83
|
+
name: str | None = None
|
|
84
|
+
description: str | None = None
|
|
85
|
+
tools: list[Callable] = field(default_factory=list)
|
|
86
|
+
litellm_params: dict = field(default_factory=dict)
|
|
87
|
+
persona: str | None = None
|
|
88
|
+
system_prompt: str | None = None
|
|
89
|
+
max_iterations: int = 20
|
|
90
|
+
filter_tools_for_task: bool = False
|
|
91
|
+
max_retries: int = ku.DEFAULT_MAX_LLM_RETRIES
|
|
92
|
+
work_dir: str | None = None
|
|
93
|
+
tracing_type: TRACING_TYPES | None = None
|
|
94
|
+
|
|
95
|
+
# Internal state (not in __init__)
|
|
96
|
+
id: uuid.UUID = field(init=False)
|
|
97
|
+
tool_name_to_func: dict[str, Callable] = field(init=False)
|
|
98
|
+
tool_names: set[str] = field(init=False)
|
|
99
|
+
task: Task | None = field(init=False, default=None)
|
|
100
|
+
chat_history: list[dict] = field(init=False, default_factory=list)
|
|
101
|
+
usage_tracker: UsageTracker = field(init=False, default_factory=UsageTracker)
|
|
102
|
+
tracer_manager: tracer.AbstractTracerManager = field(init=False)
|
|
103
|
+
current_trace: tracer.AbstractObservation | None = field(init=False, default=None)
|
|
104
|
+
planner: Planner | None = field(init=False, default=None)
|
|
105
|
+
observer: Observer = field(init=False)
|
|
106
|
+
is_visual_model: bool = field(init=False)
|
|
107
|
+
task_output_files: list[str] = field(init=False, default_factory=list)
|
|
108
|
+
|
|
109
|
+
msg_idx_of_new_task: int = field(init=False, default=0)
|
|
110
|
+
final_answer_found: bool = field(init=False, default=False)
|
|
111
|
+
|
|
112
|
+
_history_formatter: HistoryFormatter | None = field(init=False, default=None)
|
|
113
|
+
_tool_descriptions_cache: dict[frozenset[str], str] = field(init=False, default_factory=dict)
|
|
114
|
+
|
|
78
115
|
response_format_class: ClassVar[type[pyd.BaseModel]] = ChatMessage
|
|
79
116
|
HISTORY_TRUNCATE_CHARS: ClassVar[int] = 1000
|
|
80
117
|
|
|
81
|
-
def
|
|
82
|
-
|
|
83
|
-
name: str,
|
|
84
|
-
model_name: str,
|
|
85
|
-
description: str | None = None,
|
|
86
|
-
tools: list[Callable] | None = None,
|
|
87
|
-
litellm_params: dict | None = None,
|
|
88
|
-
persona: str | None = None,
|
|
89
|
-
system_prompt: str | None = None,
|
|
90
|
-
max_iterations: int = 20,
|
|
91
|
-
filter_tools_for_task: bool = False,
|
|
92
|
-
max_retries: int = ku.DEFAULT_MAX_LLM_RETRIES,
|
|
93
|
-
work_dir: str | None = None,
|
|
94
|
-
tracing_type: TRACING_TYPES | None = None,
|
|
95
|
-
):
|
|
96
|
-
"""Create an agent.
|
|
97
|
-
|
|
98
|
-
Args:
|
|
99
|
-
name: The name of the agent.
|
|
100
|
-
model_name: The (LiteLLM) model name to use.
|
|
101
|
-
description: Optional brief description about the agent.
|
|
102
|
-
tools: An optional list of tools available to the agent.
|
|
103
|
-
litellm_params: LiteLLM parameters.
|
|
104
|
-
persona: Optional persona for the agent. If provided, this gets added to
|
|
105
|
-
the system prompt.
|
|
106
|
-
system_prompt: Optional system prompt for the agent. If not provided, default is used.
|
|
107
|
-
This is mutually exclusive with persona.
|
|
108
|
-
max_iterations: The max iterations an agent can perform to solve a task.
|
|
109
|
-
filter_tools_for_task: Whether the tools should be filtered for a task. Unused.
|
|
110
|
-
max_retries: Maximum number of retries for LLM calls.
|
|
111
|
-
work_dir: Optional local workspace directory.
|
|
112
|
-
tracing_type: Type of tracing to use.
|
|
113
|
-
"""
|
|
118
|
+
def __post_init__(self):
|
|
119
|
+
"""Initialize the agent's internal state after fields are set."""
|
|
114
120
|
self.id = uuid.uuid4()
|
|
115
|
-
self.name: str = name
|
|
116
|
-
self.description = description
|
|
117
|
-
self.model_name: str = model_name
|
|
118
|
-
self.work_dir = work_dir
|
|
119
|
-
|
|
120
|
-
self.tools: list[Callable] = tools or []
|
|
121
|
-
self.filter_tools_for_task = filter_tools_for_task
|
|
122
|
-
self.litellm_params: dict = litellm_params or {}
|
|
123
|
-
self.persona = persona
|
|
124
|
-
self.system_prompt = system_prompt
|
|
125
|
-
self.max_iterations = max_iterations
|
|
126
|
-
self.max_retries = max_retries
|
|
127
|
-
|
|
128
121
|
self.tool_name_to_func = {fn.__name__: fn for fn in self.tools}
|
|
129
122
|
self.tool_names = set(self.tool_name_to_func)
|
|
130
123
|
|
|
131
|
-
|
|
132
|
-
self.
|
|
133
|
-
|
|
134
|
-
self._history_formatter: HistoryFormatter | None = None
|
|
135
|
-
self._tool_descriptions_cache: dict[frozenset[str], str] = {}
|
|
124
|
+
# Tracing initialization
|
|
125
|
+
self.tracer_manager = create_tracer_manager(self.tracing_type)
|
|
136
126
|
|
|
137
|
-
|
|
138
|
-
self.
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
# Tracing
|
|
143
|
-
self.tracer_manager: tracer.AbstractTracerManager = create_tracer_manager(tracing_type)
|
|
144
|
-
self.current_trace: tracer.AbstractObservation | None = None
|
|
145
|
-
|
|
146
|
-
self.planner: Planner | None = Planner(
|
|
147
|
-
model_name=model_name,
|
|
148
|
-
litellm_params=litellm_params,
|
|
127
|
+
# Components initialization
|
|
128
|
+
self.planner = Planner(
|
|
129
|
+
model_name=self.model_name,
|
|
130
|
+
litellm_params=self.litellm_params,
|
|
149
131
|
max_retries=self.max_retries,
|
|
150
132
|
usage_tracker=self.usage_tracker,
|
|
151
133
|
tracer_manager=self.tracer_manager,
|
|
152
134
|
)
|
|
153
135
|
self.observer = Observer(
|
|
154
|
-
model_name=model_name,
|
|
155
|
-
litellm_params=litellm_params,
|
|
136
|
+
model_name=self.model_name,
|
|
137
|
+
litellm_params=self.litellm_params,
|
|
156
138
|
tool_names=self.tool_names,
|
|
157
139
|
max_retries=self.max_retries,
|
|
158
140
|
usage_tracker=self.usage_tracker,
|
|
159
141
|
tracer_manager=self.tracer_manager,
|
|
160
142
|
)
|
|
161
143
|
|
|
162
|
-
self.is_visual_model
|
|
163
|
-
self.task_output_files: list[str] = []
|
|
144
|
+
self.is_visual_model = llm_vision_support([self.model_name])[0] or False
|
|
164
145
|
|
|
165
146
|
def __str__(self):
|
|
166
147
|
"""String representation of the agent."""
|
|
@@ -223,7 +204,11 @@ class Agent(ABC):
|
|
|
223
204
|
return ''.join(context_parts)
|
|
224
205
|
|
|
225
206
|
def _run_init(
|
|
226
|
-
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,
|
|
227
212
|
) -> None:
|
|
228
213
|
"""Initialize the running of a task by an agent.
|
|
229
214
|
|
|
@@ -231,9 +216,13 @@ class Agent(ABC):
|
|
|
231
216
|
task: Task description.
|
|
232
217
|
files: Optional files for the task.
|
|
233
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).
|
|
234
222
|
|
|
235
223
|
Raises:
|
|
236
|
-
ValueError: If task is empty
|
|
224
|
+
ValueError: If task is empty, files list is invalid, or the provided
|
|
225
|
+
history fails OpenAI compliance validation.
|
|
237
226
|
"""
|
|
238
227
|
if not task or not task.strip():
|
|
239
228
|
raise ValueError('Task description cannot be empty!')
|
|
@@ -242,6 +231,21 @@ class Agent(ABC):
|
|
|
242
231
|
if files and len(files) > MAX_TASK_FILES:
|
|
243
232
|
raise ValueError(f'Too many files provided for the task (max {MAX_TASK_FILES})!')
|
|
244
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
|
+
|
|
245
249
|
self.task = Task(description=task, files=files)
|
|
246
250
|
self.task_output_files = []
|
|
247
251
|
if task_id:
|
|
@@ -343,6 +347,7 @@ class Agent(ABC):
|
|
|
343
347
|
max_iterations: int | None = None,
|
|
344
348
|
recurrent_mode: bool = False,
|
|
345
349
|
summarize_progress_on_failure: bool = True,
|
|
350
|
+
chat_history: list[dict] | None = None,
|
|
346
351
|
) -> AsyncIterator[AgentResponse]:
|
|
347
352
|
"""Execute a task using the agent.
|
|
348
353
|
|
|
@@ -351,11 +356,19 @@ class Agent(ABC):
|
|
|
351
356
|
files: List of files associated with the task.
|
|
352
357
|
task_id: Optional task ID.
|
|
353
358
|
max_iterations: Optional maximum number of iterations.
|
|
354
|
-
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``.
|
|
355
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``.
|
|
356
366
|
|
|
357
367
|
Returns:
|
|
358
368
|
AsyncIterator[AgentResponse]: An iterator yielding agent responses.
|
|
369
|
+
|
|
370
|
+
Raises:
|
|
371
|
+
ValueError: If both ``recurrent_mode`` and ``chat_history`` are provided.
|
|
359
372
|
"""
|
|
360
373
|
|
|
361
374
|
def response(
|
|
@@ -569,6 +582,21 @@ class Agent(ABC):
|
|
|
569
582
|
|
|
570
583
|
return '\n'.join(segments)
|
|
571
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
|
+
|
|
572
600
|
def clear_history(self):
|
|
573
601
|
"""Clear the agent's message history."""
|
|
574
602
|
self.chat_history = []
|
|
@@ -603,44 +631,21 @@ class Agent(ABC):
|
|
|
603
631
|
}
|
|
604
632
|
|
|
605
633
|
|
|
634
|
+
@dataclass
|
|
606
635
|
class ReActAgent(Agent):
|
|
607
636
|
"""Reasoning and Acting agent with thought-action-observation loop."""
|
|
608
637
|
|
|
638
|
+
_: KW_ONLY
|
|
639
|
+
system_prompt: str = REACT_SYSTEM_PROMPT
|
|
640
|
+
|
|
609
641
|
response_format_class: ClassVar[type[pyd.BaseModel]] = ReActChatMessage
|
|
610
642
|
|
|
611
|
-
def
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
model_name: str,
|
|
615
|
-
tools: list,
|
|
616
|
-
description: str | None = None,
|
|
617
|
-
litellm_params: dict | None = None,
|
|
618
|
-
persona: str | None = None,
|
|
619
|
-
system_prompt: str | None = None,
|
|
620
|
-
max_iterations: int = 20,
|
|
621
|
-
filter_tools_for_task: bool = False,
|
|
622
|
-
max_retries: int = ku.DEFAULT_MAX_LLM_RETRIES,
|
|
623
|
-
work_dir: str | None = None,
|
|
624
|
-
tracing_type: TRACING_TYPES | None = None,
|
|
625
|
-
):
|
|
626
|
-
"""Create a ReAct agent."""
|
|
627
|
-
super().__init__(
|
|
628
|
-
name=name,
|
|
629
|
-
model_name=model_name,
|
|
630
|
-
tools=tools,
|
|
631
|
-
litellm_params=litellm_params,
|
|
632
|
-
description=description,
|
|
633
|
-
persona=persona,
|
|
634
|
-
system_prompt=system_prompt or REACT_SYSTEM_PROMPT,
|
|
635
|
-
max_iterations=max_iterations,
|
|
636
|
-
filter_tools_for_task=filter_tools_for_task,
|
|
637
|
-
max_retries=max_retries,
|
|
638
|
-
work_dir=work_dir,
|
|
639
|
-
tracing_type=tracing_type,
|
|
640
|
-
)
|
|
643
|
+
def __post_init__(self):
|
|
644
|
+
"""Perform ReAct-specific setup."""
|
|
645
|
+
super().__post_init__()
|
|
641
646
|
|
|
642
|
-
if tools:
|
|
643
|
-
logger.info('Created agent: %s; tools: %s', name, [t.__name__ for t in tools])
|
|
647
|
+
if self.tools:
|
|
648
|
+
logger.info('Created agent: %s; tools: %s', self.name, [t.__name__ for t in self.tools])
|
|
644
649
|
|
|
645
650
|
self._history_formatter = ReActHistoryFormatter()
|
|
646
651
|
|
|
@@ -693,10 +698,7 @@ class ReActAgent(Agent):
|
|
|
693
698
|
|
|
694
699
|
def init_history(self):
|
|
695
700
|
"""Initialize the agent's message history with the system prompt."""
|
|
696
|
-
|
|
697
|
-
persona=self.persona or '', tools=self.get_tools_description()
|
|
698
|
-
)
|
|
699
|
-
self.chat_history = [{'role': 'system', 'content': content}]
|
|
701
|
+
self.chat_history = [{'role': 'system', 'content': self.get_system_prompt_content()}]
|
|
700
702
|
self.final_answer_found = False
|
|
701
703
|
|
|
702
704
|
async def _create_initial_plan(self):
|
|
@@ -720,13 +722,13 @@ class ReActAgent(Agent):
|
|
|
720
722
|
|
|
721
723
|
async def pre_run(self) -> AsyncIterator[AgentResponse]:
|
|
722
724
|
"""Perform setup before the main run loop.
|
|
723
|
-
- Initialize task and history.
|
|
725
|
+
- Initialize task and history (or ensure injected history has a system prompt).
|
|
724
726
|
- Create initial plan.
|
|
725
727
|
|
|
726
728
|
Returns:
|
|
727
729
|
AsyncIterator[AgentResponse]: Iterator of agent responses.
|
|
728
730
|
"""
|
|
729
|
-
self.
|
|
731
|
+
self.final_answer_found = False
|
|
730
732
|
|
|
731
733
|
yield self.response(
|
|
732
734
|
rtype='log', value=f'Solving task: `{self.task.description}`', channel='run'
|
|
@@ -806,6 +808,7 @@ class ReActAgent(Agent):
|
|
|
806
808
|
max_iterations: int | None = None,
|
|
807
809
|
recurrent_mode: bool = False,
|
|
808
810
|
summarize_progress_on_failure: bool = True,
|
|
811
|
+
chat_history: list[dict] | None = None,
|
|
809
812
|
) -> AsyncIterator[AgentResponse]:
|
|
810
813
|
"""Solve a task using ReAct's TAO loop (or CodeAct's TCO loop).
|
|
811
814
|
|
|
@@ -815,23 +818,36 @@ class ReActAgent(Agent):
|
|
|
815
818
|
task_id: Optional task ID.
|
|
816
819
|
max_iterations: Optional max iterations for the task.
|
|
817
820
|
recurrent_mode: If True, augment task with previous task context.
|
|
821
|
+
Mutually exclusive with ``chat_history``.
|
|
818
822
|
summarize_progress_on_failure: Whether to summarize progress if
|
|
819
|
-
|
|
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``.
|
|
820
827
|
|
|
821
828
|
Returns:
|
|
822
829
|
Step updates on the task and the final response.
|
|
823
830
|
|
|
824
831
|
Raises:
|
|
825
|
-
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.
|
|
826
835
|
RetryError: If LLM calls fail after max retries.
|
|
827
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
|
+
|
|
828
843
|
if recurrent_mode and self.task is not None:
|
|
829
844
|
task = await self._augment_task_with_previous(task)
|
|
830
845
|
logger.debug('Recurrent mode enabled: augmented task with previous context')
|
|
831
846
|
|
|
832
847
|
# 1. run() calls _run_init()
|
|
833
|
-
# 2. pre_run() calls init_history() and does
|
|
834
|
-
|
|
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)
|
|
835
851
|
|
|
836
852
|
# Execute pre-run hook
|
|
837
853
|
async for response in self.pre_run():
|
|
@@ -1284,13 +1300,11 @@ class ReActAgent(Agent):
|
|
|
1284
1300
|
tool_call_id = self._get_last_tool_call_id()
|
|
1285
1301
|
|
|
1286
1302
|
# Always use role='tool' for tool results
|
|
1287
|
-
self.add_to_history(
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
}
|
|
1293
|
-
)
|
|
1303
|
+
self.add_to_history({
|
|
1304
|
+
'role': 'tool',
|
|
1305
|
+
'content': str(result),
|
|
1306
|
+
'tool_call_id': tool_call_id,
|
|
1307
|
+
})
|
|
1294
1308
|
|
|
1295
1309
|
act_span.update(
|
|
1296
1310
|
status='success',
|
|
@@ -1332,9 +1346,11 @@ class ReActAgent(Agent):
|
|
|
1332
1346
|
tool_call_id = self._get_last_tool_call_id()
|
|
1333
1347
|
|
|
1334
1348
|
# Use role='tool' for tool errors too
|
|
1335
|
-
self.add_to_history(
|
|
1336
|
-
|
|
1337
|
-
|
|
1349
|
+
self.add_to_history({
|
|
1350
|
+
'role': 'tool',
|
|
1351
|
+
'content': result,
|
|
1352
|
+
'tool_call_id': tool_call_id,
|
|
1353
|
+
})
|
|
1338
1354
|
yield self.response(
|
|
1339
1355
|
rtype='step',
|
|
1340
1356
|
value=result,
|
|
@@ -1464,67 +1480,43 @@ class ReActAgent(Agent):
|
|
|
1464
1480
|
)
|
|
1465
1481
|
|
|
1466
1482
|
|
|
1483
|
+
@dataclass
|
|
1467
1484
|
class CodeActAgent(ReActAgent):
|
|
1468
1485
|
"""CodeAct agent using Thought-Code-Observation loop."""
|
|
1469
1486
|
|
|
1487
|
+
_: KW_ONLY
|
|
1488
|
+
run_env: CODE_ENV_NAMES = 'host'
|
|
1489
|
+
allowed_imports: list[str] | None = None
|
|
1490
|
+
pip_packages: str | None = None
|
|
1491
|
+
timeout: int = 30
|
|
1492
|
+
env_vars_to_set: dict[str, str] | None = None
|
|
1493
|
+
system_prompt: str = CODE_ACT_SYSTEM_PROMPT
|
|
1494
|
+
|
|
1470
1495
|
response_format_class: ClassVar[type[pyd.BaseModel]] = CodeActChatMessage
|
|
1471
1496
|
|
|
1472
|
-
def
|
|
1473
|
-
self,
|
|
1474
|
-
name: str,
|
|
1475
|
-
model_name: str,
|
|
1476
|
-
run_env: CODE_ENV_NAMES,
|
|
1477
|
-
tools: list[Callable] | None = None,
|
|
1478
|
-
description: str | None = None,
|
|
1479
|
-
litellm_params: dict | None = None,
|
|
1480
|
-
persona: str | None = None,
|
|
1481
|
-
system_prompt: str | None = None,
|
|
1482
|
-
max_iterations: int = 20,
|
|
1483
|
-
allowed_imports: list[str] | None = None,
|
|
1484
|
-
pip_packages: str | None = None,
|
|
1485
|
-
timeout: int = 30,
|
|
1486
|
-
env_vars_to_set: dict[str, str] | None = None,
|
|
1487
|
-
filter_tools_for_task: bool = False,
|
|
1488
|
-
max_retries: int = ku.DEFAULT_MAX_LLM_RETRIES,
|
|
1489
|
-
work_dir: str | None = None,
|
|
1490
|
-
tracing_type: TRACING_TYPES | None = None,
|
|
1491
|
-
):
|
|
1497
|
+
def __post_init__(self):
|
|
1492
1498
|
"""Initialize CodeAct agent."""
|
|
1493
|
-
super().
|
|
1494
|
-
|
|
1495
|
-
model_name=model_name,
|
|
1496
|
-
tools=tools,
|
|
1497
|
-
litellm_params=litellm_params,
|
|
1498
|
-
max_iterations=max_iterations,
|
|
1499
|
-
persona=persona,
|
|
1500
|
-
system_prompt=system_prompt or CODE_ACT_SYSTEM_PROMPT,
|
|
1501
|
-
description=description,
|
|
1502
|
-
filter_tools_for_task=filter_tools_for_task,
|
|
1503
|
-
max_retries=max_retries,
|
|
1504
|
-
work_dir=work_dir,
|
|
1505
|
-
tracing_type=tracing_type,
|
|
1506
|
-
)
|
|
1499
|
+
super().__post_init__()
|
|
1500
|
+
|
|
1507
1501
|
self._history_formatter = CodeActHistoryFormatter()
|
|
1508
1502
|
self.tools_source_code: str = 'from typing import *\n\n'
|
|
1509
1503
|
|
|
1510
|
-
if tools:
|
|
1504
|
+
if self.tools:
|
|
1511
1505
|
for t in self.tools:
|
|
1512
1506
|
self.tools_source_code += inspect.getsource(t).replace('@tool\n', '', 1) + '\n'
|
|
1513
1507
|
|
|
1514
|
-
self.
|
|
1515
|
-
|
|
1516
|
-
if not allowed_imports:
|
|
1517
|
-
allowed_imports = []
|
|
1508
|
+
if not self.allowed_imports:
|
|
1509
|
+
self.allowed_imports = []
|
|
1518
1510
|
|
|
1519
|
-
self.allowed_imports = allowed_imports + ['datetime', 'typing', 'mimetypes']
|
|
1511
|
+
self.allowed_imports = self.allowed_imports + ['datetime', 'typing', 'mimetypes']
|
|
1520
1512
|
self.code_runner = CodeRunner(
|
|
1521
|
-
env=run_env,
|
|
1513
|
+
env=self.run_env,
|
|
1522
1514
|
allowed_imports=self.allowed_imports,
|
|
1523
|
-
model_name=model_name,
|
|
1524
|
-
pip_packages=pip_packages,
|
|
1525
|
-
timeout=timeout,
|
|
1526
|
-
env_vars_to_set=env_vars_to_set,
|
|
1527
|
-
litellm_params=litellm_params,
|
|
1515
|
+
model_name=self.model_name,
|
|
1516
|
+
pip_packages=self.pip_packages,
|
|
1517
|
+
timeout=self.timeout,
|
|
1518
|
+
env_vars_to_set=self.env_vars_to_set,
|
|
1519
|
+
litellm_params=self.litellm_params,
|
|
1528
1520
|
work_dir=self.work_dir,
|
|
1529
1521
|
usage_tracker=self.usage_tracker,
|
|
1530
1522
|
tool_names=self.tool_names,
|
|
@@ -1601,15 +1593,17 @@ class CodeActAgent(ReActAgent):
|
|
|
1601
1593
|
f'Could not extract valid Code or Answer from response. Text: {text[:300]}...'
|
|
1602
1594
|
)
|
|
1603
1595
|
|
|
1604
|
-
def
|
|
1605
|
-
"""
|
|
1606
|
-
|
|
1596
|
+
def get_system_prompt_content(self) -> str:
|
|
1597
|
+
"""Return the formatted system prompt string for CodeAct agent."""
|
|
1598
|
+
return self.system_prompt.format(
|
|
1607
1599
|
persona=self.persona or '',
|
|
1608
1600
|
tools=self.get_tools_description(),
|
|
1609
|
-
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 [])]),
|
|
1610
1602
|
)
|
|
1611
|
-
|
|
1612
|
-
|
|
1603
|
+
|
|
1604
|
+
def init_history(self):
|
|
1605
|
+
"""Initialize message history with system prompt for CodeAct agent."""
|
|
1606
|
+
super().init_history()
|
|
1613
1607
|
|
|
1614
1608
|
async def _think(self) -> AsyncIterator[AgentResponse]:
|
|
1615
1609
|
"""Think step for CodeAct agent.
|
|
@@ -45,13 +45,17 @@ LOGGERS_TO_SUPPRESS = [
|
|
|
45
45
|
'hpack',
|
|
46
46
|
'httpx',
|
|
47
47
|
'httpcore',
|
|
48
|
+
'hyper_util',
|
|
49
|
+
'h2',
|
|
48
50
|
'langfuse',
|
|
49
51
|
'LiteLLM',
|
|
50
52
|
'litellm',
|
|
51
53
|
'openai',
|
|
52
54
|
'pdfminer',
|
|
53
55
|
'primp',
|
|
56
|
+
'reqwest',
|
|
54
57
|
'rquest',
|
|
58
|
+
'rustls',
|
|
55
59
|
'urllib3',
|
|
56
60
|
'urllib3.connectionpool',
|
|
57
61
|
]
|
|
@@ -498,6 +502,185 @@ def parse_param_descriptions(doc: str) -> dict[str, str]:
|
|
|
498
502
|
return param_docs
|
|
499
503
|
|
|
500
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
|
+
|
|
501
684
|
def build_tool_schema(
|
|
502
685
|
fn: Callable, just_first_line: bool = False, as_text: bool = True
|
|
503
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
|