1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Optional
if TYPE_CHECKING:
from autogpt.core.prompting import ChatPrompt
from autogpt.models.context_item import ContextItem
from ..base import BaseAgent
from autogpt.core.resource.model_providers import ChatMessage
class AgentContext:
items: list[ContextItem]
def __init__(self, items: Optional[list[ContextItem]] = None):
self.items = items or []
def __bool__(self) -> bool:
return len(self.items) > 0
def __contains__(self, item: ContextItem) -> bool:
return any([i.source == item.source for i in self.items])
def add(self, item: ContextItem) -> None:
self.items.append(item)
def close(self, index: int) -> None:
self.items.pop(index - 1)
def clear(self) -> None:
self.items.clear()
def format_numbered(self) -> str:
return "\n\n".join([f"{i}. {c.fmt()}" for i, c in enumerate(self.items, 1)])
class ContextMixin:
"""Mixin that adds context support to a BaseAgent subclass"""
context: AgentContext
def __init__(self, **kwargs: Any):
self.context = AgentContext()
super(ContextMixin, self).__init__(**kwargs)
def build_prompt(
self,
*args: Any,
extra_messages: Optional[list[ChatMessage]] = None,
**kwargs: Any,
) -> ChatPrompt:
if not extra_messages:
extra_messages = []
# Add context section to prompt
if self.context:
extra_messages.insert(
0,
ChatMessage.system(
"## Context\n"
+ self.context.format_numbered()
+ "\n\nWhen a context item is no longer needed and you are not done yet,"
" you can hide the item by specifying its number in the list above"
" to `hide_context_item`.",
),
)
return super(ContextMixin, self).build_prompt(
*args,
extra_messages=extra_messages,
**kwargs,
) # type: ignore
def get_agent_context(agent: BaseAgent) -> AgentContext | None:
if isinstance(agent, ContextMixin):
return agent.context
return None
|