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

Add API mode #356

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
55 changes: 55 additions & 0 deletions classic/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,61 @@ To use the script, you will need to follow these steps:
6. Set the first task of the system in the YOUR_FIRST_TASK variable.
7. Run the script.

# API mode (via [e2b](https://www.e2b.dev/))
To start the server run:
```bash
python api.py
```

and then you can call the API using either the following commands:

To **create a task** run:
```bash
curl --request POST \
--url http://localhost:8000/agent/tasks \
--header 'Content-Type: application/json' \
--data '{
"input": "Find the Answer to the Ultimate Question of Life, the Universe, and Everything."
}'
```

You will get a response like this:
```json
{"input":"Find the Answer to the Ultimate Question of Life, the Universe, and Everything.","task_id":"d2c4e543-ae08-4a97-9ac5-5f9a4459cb19","artifacts":[]}
```

Then to **execute one step of the task** copy the `task_id` you got from the previous request and run:

```bash
curl --request POST \
--url http://localhost:8000/agent/tasks/<task-id>/steps
```

or you can use [Python client library](https://github.com/e2b-dev/agent-protocol/tree/main/agent_client/python):

```python
from agent_protocol_client import AgentApi, ApiClient, TaskRequestBody

...

prompt = "Find the Answer to the Ultimate Question of Life, the Universe, and Everything."

async with ApiClient() as api_client:
# Create an instance of the API class
api_instance = AgentApi(api_client)
task_request_body = TaskRequestBody(input=prompt)

task = await api_instance.create_agent_task(
task_request_body=task_request_body
)
task_id = task.task_id
response = await api_instance.execute_agent_task_step(task_id=task_id)

...

```


# Warning
This script is designed to be run continuously as part of a task management system. Running this script continuously can result in high API usage, so please use it responsibly. Additionally, the script requires the OpenAI and Pinecone APIs to be set up correctly, so make sure you have set up the APIs before running the script.

Expand Down
64 changes: 64 additions & 0 deletions classic/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
from agent_protocol import (
Agent,
Step,
Task,
)
from agent_protocol.models import Status

from babyagi import (
execution_agent,
YOUR_FIRST_TASK,
task_creation_agent,
prioritization_agent,
)


def _get_future_step_names(task: Task, step: Step) -> list[str]:
return [s.name for s in task.steps if s.status == Status.created and s != step]


async def task_handler(task: Task) -> None:
await Agent.db.create_step(task.task_id, YOUR_FIRST_TASK)


async def step_handler(step: Step) -> Step:
task = await Agent.db.get_task(step.task_id)
result = execution_agent(task.input, step.name)
step.output = result

# Plan new tasks
new_tasks = task_creation_agent(
task.input,
{"data": result},
step.name,
_get_future_step_names(task, step),
)

step_names = _get_future_step_names(task, step) + new_tasks
step_id = task.steps.index(step) + 1

# Prioritize
result = prioritization_agent(
[{"task_name": s} for s in step_names],
task.input,
step_id,
)

# Set up new steps
task.steps = list(
filter(lambda s: s.status == Status.completed or s == step, task.steps)
)
for i, new_step in enumerate(result):
await Agent.db.create_step(
task.task_id,
new_step["task_name"],
)

# End if everything's done
if len(result) == 0:
step.is_last = True

return step


Agent.setup_agent(task_handler, step_handler).start()
107 changes: 55 additions & 52 deletions classic/babyagi.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,7 @@
index = pinecone.Index(table_name)

# Task list
task_list = deque([])

def add_task(task: Dict):
task_list.append(task)

def get_ada_embedding(text):
text = text.replace("\n", " ")
Expand All @@ -49,23 +46,24 @@ def task_creation_agent(objective: str, result: Dict, task_description: str, tas
new_tasks = response.choices[0].text.strip().split('\n')
return [{"task_name": task_name} for task_name in new_tasks]

def prioritization_agent(this_task_id:int):
global task_list
def prioritization_agent(task_list, objective, this_task_id:int):
task_names = [t["task_name"] for t in task_list]
next_task_id = int(this_task_id)+1
prompt = f"""You are an task prioritization AI tasked with cleaning the formatting of and reprioritizing the following tasks: {task_names}. Consider the ultimate objective of your team:{OBJECTIVE}. Do not remove any tasks. Return the result as a numbered list, like:
prompt = f"""You are an task prioritization AI tasked with cleaning the formatting of and reprioritizing the following tasks: {task_names}. Consider the ultimate objective of your team:{objective}. Do not remove any tasks. Return the result as a numbered list, like:
#. First task
#. Second task
Start the task list with number {next_task_id}."""
response = openai.Completion.create(engine="text-davinci-003",prompt=prompt,temperature=0.5,max_tokens=1000,top_p=1,frequency_penalty=0,presence_penalty=0)
new_tasks = response.choices[0].text.strip().split('\n')
task_list = deque()
new_task_list = deque()
for task_string in new_tasks:
task_parts = task_string.strip().split(".", 1)
if len(task_parts) == 2:
task_id = task_parts[0].strip()
task_name = task_parts[1].strip()
task_list.append({"task_id": task_id, "task_name": task_name})
new_task_list.append({"task_id": task_id, "task_name": task_name})
return new_task_list


def execution_agent(objective:str,task: str) -> str:
#context = context_agent(index="quickstart", query="my_search_query", n=5)
Expand All @@ -90,49 +88,54 @@ def context_agent(query: str, index: str, n: int):
include_metadata=True)
#print("***** RESULTS *****")
#print(results)
sorted_results = sorted(results.matches, key=lambda x: x.score, reverse=True)
sorted_results = sorted(results.matches, key=lambda x: x.score, reverse=True)
return [(str(item.metadata['task'])) for item in sorted_results]

# Add the first task
first_task = {
"task_id": 1,
"task_name": YOUR_FIRST_TASK
}

add_task(first_task)
# Main loop
task_id_counter = 1
while True:
if task_list:
# Print the task list
print("\033[95m\033[1m"+"\n*****TASK LIST*****\n"+"\033[0m\033[0m")
for t in task_list:
print(str(t['task_id'])+": "+t['task_name'])

# Step 1: Pull the first task
task = task_list.popleft()
print("\033[92m\033[1m"+"\n*****NEXT TASK*****\n"+"\033[0m\033[0m")
print(str(task['task_id'])+": "+task['task_name'])

# Send to execution function to complete the task based on the context
result = execution_agent(OBJECTIVE,task["task_name"])
this_task_id = int(task["task_id"])
print("\033[93m\033[1m"+"\n*****TASK RESULT*****\n"+"\033[0m\033[0m")
print(result)

# Step 2: Enrich result and store in Pinecone
enriched_result = {'data': result} # This is where you should enrich the result if needed
result_id = f"result_{task['task_id']}"
vector = enriched_result['data'] # extract the actual result from the dictionary
index.upsert([(result_id, get_ada_embedding(vector),{"task":task['task_name'],"result":result})])

# Step 3: Create new tasks and reprioritize task list
new_tasks = task_creation_agent(OBJECTIVE,enriched_result, task["task_name"], [t["task_name"] for t in task_list])

for new_task in new_tasks:
task_id_counter += 1
new_task.update({"task_id": task_id_counter})
add_task(new_task)
prioritization_agent(this_task_id)

time.sleep(1) # Sleep before checking the task list again

def main():
# Task list
task_list = deque([])
# Add the first task
first_task = {
"task_id": 1,
"task_name": YOUR_FIRST_TASK
}

task_list.append(first_task)
# Main loop
task_id_counter = 1
while task_list:
if task_list:
# Print the task list
print("\033[95m\033[1m"+"\n*****TASK LIST*****\n"+"\033[0m\033[0m")
for t in task_list:
print(str(t['task_id'])+": "+t['task_name'])

# Step 1: Pull the first task
task = task_list.popleft()
print("\033[92m\033[1m"+"\n*****NEXT TASK*****\n"+"\033[0m\033[0m")
print(str(task['task_id'])+": "+task['task_name'])

# Send to execution function to complete the task based on the context
result = execution_agent(OBJECTIVE,task["task_name"])
this_task_id = int(task["task_id"])
print("\033[93m\033[1m"+"\n*****TASK RESULT*****\n"+"\033[0m\033[0m")
print(result)

# Step 2: Enrich result and store in Pinecone
enriched_result = {'data': result} # This is where you should enrich the result if needed
result_id = f"result_{task['task_id']}"
vector = enriched_result['data'] # extract the actual result from the dictionary

# Step 3: Create new tasks and reprioritize task list
new_tasks = task_creation_agent(OBJECTIVE,enriched_result, task["task_name"], [t["task_name"] for t in task_list])

for new_task in new_tasks:
task_id_counter += 1
new_task.update({"task_id": task_id_counter})
task_list.append(new_task)
task_list = prioritization_agent(task_list, this_task_id)


if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions classic/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
openai==0.27.2
pinecone-client==2.2.1
agent_protocol>=0.2.4