File size: 6,531 Bytes
107ff99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import gradio as gr
import openai
import requests
import json
import os
from duckduckgo_search import ddg

os.environ["OPENAI_API_KEY"] = "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"
openai.api_key = os.getenv("OPENAI_API_KEY")

def search_duckduckgo(query):

    keywords = query
    results = ddg(keywords, region='wt-wt', safesearch='Off', time='m')
    filtered_results = [{"title": res["title"], "body": res["body"]} for res in results]
    print(filtered_results)
    return filtered_results

def get_search_query(task):
    
    response = openai.ChatCompletion.create(
      model="gpt-3.5-turbo",
      messages=[
        {"role": "user", "content": f"Given the task: {task}. Generate a concise search query with 1-3 keywords."}
      ]
    )
    search_query = response.choices[0]['message']['content'].strip()
    print("Agent 2: ",search_query)
    return search_query

def summarize_search_result(task, search_result):
    
    response = openai.ChatCompletion.create(
      model="gpt-3.5-turbo",
      messages=[
        {"role": "user", "content":f"Given the task '{task}' and the search result '{json.dumps(search_result)}', provide a summarized result."}
      ]
    )
    summary = response.choices[0]['message']['content'].strip()
    return summary

def agent_1(objective):
    
    response = openai.ChatCompletion.create(
      model="gpt-3.5-turbo",
      messages=[
        {"role": "user", "content":f"Given the objective '{objective}', create a list of tasks that are closely related to the objective. If needed add specific key words from objective to the task sentence"}
      ]
    )
    tasks = response.choices[0]['message']['content'].strip().split('\n')
    return tasks

def agent_2(task):
    
    search_query = get_search_query(task)
    print("Agent 2")
    print(search_query)
    search_results = search_duckduckgo(search_query)
    summarized_result = summarize_search_result(task, search_results)
    print(summarized_result)
    return summarized_result

def agent_3(objective, last_result, tasks):
    
    task_list = '\n'.join(tasks)
    response = openai.ChatCompletion.create(
      model="gpt-3.5-turbo",
      messages=[
        {"role": "user", "content":f"Given the objective '{objective}', the last result '{json.dumps(last_result)}', and the task list:\n{task_list}\n\nRank the tasks based on their relevance to the objective."}
      ]
    )
    modified_tasks = response.choices[0]['message']['content'].strip().split('\n')
    print("Agent 3")
    print(modified_tasks)
    return modified_tasks

def summarize_result(objective, result):
    
    response = openai.ChatCompletion.create(
      model="gpt-3.5-turbo",
      messages=[
        {"role": "user", "content":f"Given the objective '{objective}' and the final result '{json.dumps(result)}', provide a summary."}
      ]
    )
    summary = response.choices[0]['message']['content'].strip()
    return summary

def generate_final_answer(objective, all_results):

    response = openai.ChatCompletion.create(
      model="gpt-3.5-turbo",
      messages=[
        {"role": "user", "content":f"Given the objective '{objective}' and the collected results '{json.dumps(all_results)}', provide a final answer addressing the objective."}
      ]
    )
    final_answer = response.choices[0]['message']['content'].strip()
    return final_answer

def main(objective, loop_count):
    tasks = agent_1(objective)
    all_results = []
    completed_tasks = []
    for i in range(loop_count):
        print(i+1)
        if i < len(tasks):
            print('NEXT TASK: ',tasks[i])
            completed_tasks.append(tasks[i])
            result = agent_2(tasks[i])
            all_results.append(result)
            tasks = agent_3(objective, result, tasks)
            print('*********************')
        else:
            break

    final_answer = generate_final_answer(objective, all_results)
    return final_answer,completed_tasks,tasks

def getbabyagianswer(objective,loop_count,openapikey):
    objective=objective

    loop_count = loop_count
    final_summary,completed_tasts,all_tasks = main(objective, loop_count)
    print("Final Summary:", final_summary)
    return final_summary,completed_tasts,all_tasks


with gr.Blocks() as demo:
    gr.Markdown("<h1><center>GPT4 created BabyAGI</center></h1>")
    gr.Markdown(
        """ This is part of a series of experiments using BabyAGI as a "framework" to construct focused use cases (ex: idea generation). In this GPT-4 was prompted to create a BabyAGI with task creation & execution agents but with constraints to give answer with a specified number of loops. Unlike the original BabyAGI concept, this is not open-ended. \n\nNote: This is a series of experiments to understand AI agents and hence do check the quality of output. OpenAI agents (gpt-3.5-turbo) & DuckDuckGo search are used. The analysis takes roughly 120 secs & may not always be consistent. An error occurs when the OpenAI Api key is not provided/ ChatGPT API is overloaded/ ChatGPT is unable to correctly decipher & format the output\n\n[visitors](https://visitor-badge.glitch.me/badge?page_id=hra/GPT4-makes-BabyAGI)"""
        )
    
    with gr.Row() as row:
        with gr.Column():
            textboxtopic = gr.Textbox(placeholder="Enter Topic for Curriculum...", lines=1,label='Topic')
        with gr.Column():
            textboxtopic = gr.Textbox(placeholder="Enter # of loops...", lines=1,label='Loop Count')
        with gr.Column():
            textboxopenapi = gr.Textbox(placeholder="Enter OpenAPI Key...", lines=1,label='OpenAPI Key')
    with gr.Row() as row:
        examples = gr.Examples(examples=['Give me a startup idea in healthcare technology for India','Which is a must see destination in Mysore?','Find me a unique cuisine restaurant in bangalore','Give me a startup idea for AI in music streaming'],
                           inputs=[textboxtopic])
    with gr.Row() as row:
        btn = gr.Button("Unleash AI Agent")
        
    with gr.Row() as row:
        with gr.Column():
            answer1 = gr.Textbox(placeholder="", lines=1,label='Answer')
        with gr.Column():
            fulltasklist1 = gr.Textbox(placeholder="", lines=1,label='Full Task List')
        with gr.Column():
            completedtasklist1 = gr.Textbox(placeholder="", lines=1,label='Completed Tasks')
    
    btn.click(getbabyagianswer, inputs=[textboxtopic,textboxloopcount,textboxopenapi,],outputs=[answer1,fulltasklist1,completedtasklist1])
    
demo.launch(debug=True)