Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Agent API updates and doc file #28

Merged
merged 1 commit into from
Apr 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions loopgpt/agent.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Agent

This file describes how to use Agent objects.

## Agent State

An Agent's state can be one of the following:
- `START`: Agent is initialized.
- `IDLE`: No tool is staged and Agent is waiting for input.
- `TOOL_STAGED`: Agent has staged a tool for execution.
- `STOP`: If `task_complete` is executed.

## Initialize Agent

An agent can be initialized using:
```python
import loopgpt
agent = loopgpt.Agent()
```

## Chat with Agent

`agent.chat()` deals with sending prompts to the agent and executing commands. It returns the Agent's response (see [loopgpt/constants.py](https://github.com/farizrahman4u/loopgpt/blob/main/loopgpt/constants.py) for the response format).

It takes two arguments:
- **`**message: Optional[str]`**: The message to send to the agent. Defaults to `None`.
- **`run_tool: bool`**: If specified as `True`, any staged command will be executed. Defaults to `False`.

### Prompts

There are two kinds of prompts that are attached with the `message` argument:
- **`agent.init_prompt`**: This prompt is sent along with the first message and in case `message` is `None`.
- **`agent.next_prompt`**: This prompt is sent along with the subsequent messages.

### Staged tool

The staged tool (if any), can be accessed through `agent.staging_tool` and the response that staged the tool is stored in `agent.staging_response`.
You can see the name and arguments of the staged tool using `agent.staging_tool.get("name")` and `agent.staging_tool.get("args")` respectively.

To run the staged tool, just do:

```python
agent.chat(run_tool=True)
```

The tool's response can be found at `agent.tool_response`.
44 changes: 34 additions & 10 deletions loopgpt/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
DEFAULT_AGENT_DESCRIPTION,
NEXT_PROMPT,
NEXT_PROMPT_SMALL,
AgentStates
)
from loopgpt.memory import from_config as memory_from_config
from loopgpt.models import OpenAIModel, from_config as model_from_config
Expand Down Expand Up @@ -59,6 +60,7 @@ def __init__(
self.progress = []
self.plan = []
self.constraints = []
self.state = AgentStates.START

def _get_non_user_messages(self, n):
msgs = [
Expand Down Expand Up @@ -130,24 +132,35 @@ def _get_compressed_history(self):
user_msgs = [i for i in range(len(hist)) if hist[i]["role"] == "user"]
hist = [hist[i] for i in range(len(hist)) if i not in user_msgs]
return hist

def get_full_message(self, message: Optional[str]):
if self.state == AgentStates.START:
return self.init_prompt + "\n\n" + (message or "")
else:
return self.next_prompt + "\n\n" + (message or "")

@spinner
def chat(self, message: Optional[str] = None, run_tool=False) -> Union[str, Dict]:
if message is None:
message = self.init_prompt
def chat(self, message: Optional[str] = None, run_tool=False) -> Optional[Union[str, Dict]]:
if self.state == AgentStates.STOP:
raise ValueError(
"This agent has completed its tasks. It will not accept any more messages."
" You can do `agent.clear_state()` to start over with the same goals."
)
message = self.get_full_message(message)
if self.staging_tool:
tool = self.staging_tool
if run_tool:
output = self.run_staging_tool()
self.tool_response = output
if tool.get("name") == "task_complete":
self.history.append(
{
"role": "system",
"content": "Completed all user specified tasks.",
}
)
message = ""
output = self.run_staging_tool()
self.tool_response = output
self.state = AgentStates.STOP
return
if tool.get("name") != "do_nothing":
pass
# TODO We dont have enough space for this in gpt3
Expand Down Expand Up @@ -186,11 +199,19 @@ def chat(self, message: Optional[str] = None, run_tool=False) -> Union[str, Dict
):
self.staging_tool = {"name": "task_complete", "args": {}}
self.staging_response = resp
self.state = AgentStates.STOP
else:
if "name" in resp:
resp = {"command": resp}
self.staging_tool = resp["command"]
self.staging_response = resp
if isinstance(resp, dict):
if "name" in resp:
resp = {"command": resp}
if "command" in resp:
self.staging_tool = resp["command"]
self.staging_response = resp
self.state = AgentStates.TOOL_STAGED
else:
self.state = AgentStates.IDLE
else:
self.state = AgentStates.IDLE

progress = resp.get("thoughts", {}).get("progress")
if progress:
Expand Down Expand Up @@ -321,6 +342,7 @@ def clear_state(self):
self.staging_response = None
self.tool_response = None
self.progress = None
self.state = AgentStates.START
self.history.clear()
self.sub_agents.clear()
self.memory.clear()
Expand Down Expand Up @@ -407,6 +429,7 @@ def config(self, include_state=True):
"description": self.description,
"goals": self.goals[:],
"constraints": self.constraints[:],
"state": self.state,
"model": self.model.config(),
"temperature": self.temperature,
"tools": [tool.config() for tool in self.tools.values()],
Expand Down Expand Up @@ -435,6 +458,7 @@ def from_config(cls, config):
agent.description = config["description"]
agent.goals = config["goals"][:]
agent.constraints = config["constraints"][:]
agent.state = config["state"]
agent.temperature = config["temperature"]
agent.model = model_from_config(config["model"])
agent.tools = {tool.id: tool for tool in map(tool_from_config, config["tools"])}
Expand Down
6 changes: 6 additions & 0 deletions loopgpt/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,12 @@
"Always execute plans to completion",
]

class AgentStates:
START = "START"
IDLE = "IDLE"
TOOL_STAGED = "TOOL_STAGED"
STOP = "STOP"

# SPINNER
SPINNER_ENABLED = True
SPINNER_START_DELAY = 2
6 changes: 2 additions & 4 deletions loopgpt/loops/repl.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,21 +171,19 @@ def cli(agent, continuous=False):
if cmd == "task_complete":
return
print_line("system", f"Executing command: {cmd}")
resp = agent.chat(agent.next_prompt, True)
resp = agent.chat(run_tool=True)
print_line("system", f"{cmd} output: {agent.tool_response}")
elif yn == "n":
feedback = input(
"Enter feedback (Why not execute the command?): "
)
if feedback.lower().strip() == "exit":
return
next_prompt = agent.next_prompt
feedback = next_prompt + "\n\n" + feedback
resp = agent.chat(feedback, False)
write_divider()
continue
write_divider()
inp = input(INPUT_PROMPT)
if inp.lower().strip() == "exit":
return
resp = agent.chat(agent.next_prompt + "\n\n" + inp)
resp = agent.chat(inp)