kenken999 commited on
Commit
e91d22b
1 Parent(s): 2e3b8e2
AutoPrompt/babyagi.py ADDED
@@ -0,0 +1,677 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from dotenv import load_dotenv
3
+
4
+ # Load default environment variables (.env)
5
+ load_dotenv()
6
+
7
+ import os
8
+ import time
9
+ import logging
10
+ from collections import deque
11
+ from typing import Dict, List
12
+ import importlib
13
+ import openai
14
+ import chromadb
15
+ import tiktoken as tiktoken
16
+ from chromadb.utils.embedding_functions import OpenAIEmbeddingFunction
17
+ from chromadb.api.types import Documents, EmbeddingFunction, Embeddings
18
+ import re
19
+ from groq import Groq
20
+
21
+ # default opt out of chromadb telemetry.
22
+ from chromadb.config import Settings
23
+ from transformers import AutoTokenizer, AutoModel
24
+ import torch
25
+ import numpy
26
+
27
+ # モデル名を指定
28
+ model_name = "sentence-transformers/all-MiniLM-L6-v2"
29
+
30
+ # トークナイザーとモデルをロード
31
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
32
+ model = AutoModel.from_pretrained(model_name)
33
+ client = chromadb.Client(Settings(anonymized_telemetry=False))
34
+
35
+ # Engine configuration
36
+
37
+ # Model: GPT, LLAMA, HUMAN, etc.
38
+ LLM_MODEL = os.getenv("LLM_MODEL", os.getenv("OPENAI_API_MODEL", "gpt-3.5-turbo")).lower()
39
+
40
+ # API Keys
41
+ OPENAI_API_KEY = os.getenv("api_key", "")
42
+ if not (LLM_MODEL.startswith("llama") or LLM_MODEL.startswith("human")):
43
+ assert OPENAI_API_KEY, "\033[91m\033[1m" + "OPENAI_API_KEY environment variable is missing from .env" + "\033[0m\033[0m"
44
+
45
+ # Table config
46
+ RESULTS_STORE_NAME = os.getenv("RESULTS_STORE_NAME", os.getenv("TABLE_NAME", ""))
47
+ assert RESULTS_STORE_NAME, "\033[91m\033[1m" + "RESULTS_STORE_NAME environment variable is missing from .env" + "\033[0m\033[0m"
48
+
49
+ # Run configuration
50
+ INSTANCE_NAME = os.getenv("INSTANCE_NAME", os.getenv("BABY_NAME", "BabyAGI"))
51
+ COOPERATIVE_MODE = "none"
52
+ JOIN_EXISTING_OBJECTIVE = False
53
+
54
+ # Goal configuration
55
+ #OBJECTIVE = os.getenv("OBJECTIVE", "")
56
+ OBJECTIVE = "ボットの性能をよくする方法 日本語で説明"
57
+ INITIAL_TASK = os.getenv("INITIAL_TASK", os.getenv("FIRST_TASK", ""))
58
+
59
+ # Model configuration
60
+ OPENAI_TEMPERATURE = float(os.getenv("OPENAI_TEMPERATURE", 0.0))
61
+
62
+
63
+ # Extensions support begin
64
+
65
+ def can_import(module_name):
66
+ try:
67
+ importlib.import_module(module_name)
68
+ return True
69
+ except ImportError:
70
+ return False
71
+
72
+
73
+ DOTENV_EXTENSIONS = os.getenv("DOTENV_EXTENSIONS", "").split(" ")
74
+
75
+ # Command line arguments extension
76
+ # Can override any of the above environment variables
77
+ ENABLE_COMMAND_LINE_ARGS = (
78
+ os.getenv("ENABLE_COMMAND_LINE_ARGS", "false").lower() == "true"
79
+ )
80
+ if ENABLE_COMMAND_LINE_ARGS:
81
+ if can_import("extensions.argparseext"):
82
+ from extensions.argparseext import parse_arguments
83
+
84
+ OBJECTIVE, INITIAL_TASK, LLM_MODEL, DOTENV_EXTENSIONS, INSTANCE_NAME, COOPERATIVE_MODE, JOIN_EXISTING_OBJECTIVE = parse_arguments()
85
+
86
+ # Human mode extension
87
+ # Gives human input to babyagi
88
+ if LLM_MODEL.startswith("human"):
89
+ if can_import("extensions.human_mode"):
90
+ from extensions.human_mode import user_input_await
91
+
92
+ # Load additional environment variables for enabled extensions
93
+ # TODO: This might override the following command line arguments as well:
94
+ # OBJECTIVE, INITIAL_TASK, LLM_MODEL, INSTANCE_NAME, COOPERATIVE_MODE, JOIN_EXISTING_OBJECTIVE
95
+ if DOTENV_EXTENSIONS:
96
+ if can_import("extensions.dotenvext"):
97
+ from extensions.dotenvext import load_dotenv_extensions
98
+
99
+ load_dotenv_extensions(DOTENV_EXTENSIONS)
100
+
101
+ # TODO: There's still work to be done here to enable people to get
102
+ # defaults from dotenv extensions, but also provide command line
103
+ # arguments to override them
104
+
105
+ # Extensions support end
106
+
107
+ print("\033[95m\033[1m" + "\n*****CONFIGURATION*****\n" + "\033[0m\033[0m")
108
+ print(f"Name : {INSTANCE_NAME}")
109
+ print(f"Mode : {'alone' if COOPERATIVE_MODE in ['n', 'none'] else 'local' if COOPERATIVE_MODE in ['l', 'local'] else 'distributed' if COOPERATIVE_MODE in ['d', 'distributed'] else 'undefined'}")
110
+ print(f"LLM : {LLM_MODEL}")
111
+
112
+
113
+ # Check if we know what we are doing
114
+ assert OBJECTIVE, "\033[91m\033[1m" + "OBJECTIVE environment variable is missing from .env" + "\033[0m\033[0m"
115
+ assert INITIAL_TASK, "\033[91m\033[1m" + "INITIAL_TASK environment variable is missing from .env" + "\033[0m\033[0m"
116
+
117
+ LLAMA_MODEL_PATH = os.getenv("LLAMA_MODEL_PATH", "models/llama-13B/ggml-model.bin")
118
+ if LLM_MODEL.startswith("llama"):
119
+ if can_import("llama_cpp"):
120
+ from llama_cpp import Llama
121
+
122
+ print(f"LLAMA : {LLAMA_MODEL_PATH}" + "\n")
123
+ assert os.path.exists(LLAMA_MODEL_PATH), "\033[91m\033[1m" + f"Model can't be found." + "\033[0m\033[0m"
124
+
125
+ CTX_MAX = 1024
126
+ LLAMA_THREADS_NUM = int(os.getenv("LLAMA_THREADS_NUM", 8))
127
+
128
+ print('Initialize model for evaluation')
129
+ llm = Llama(
130
+ model_path=LLAMA_MODEL_PATH,
131
+ n_ctx=CTX_MAX,
132
+ n_threads=LLAMA_THREADS_NUM,
133
+ n_batch=512,
134
+ use_mlock=False,
135
+ )
136
+
137
+ print('\nInitialize model for embedding')
138
+ llm_embed = Llama(
139
+ model_path=LLAMA_MODEL_PATH,
140
+ n_ctx=CTX_MAX,
141
+ n_threads=LLAMA_THREADS_NUM,
142
+ n_batch=512,
143
+ embedding=True,
144
+ use_mlock=False,
145
+ )
146
+
147
+ print(
148
+ "\033[91m\033[1m"
149
+ + "\n*****USING LLAMA.CPP. POTENTIALLY SLOW.*****"
150
+ + "\033[0m\033[0m"
151
+ )
152
+ else:
153
+ print(
154
+ "\033[91m\033[1m"
155
+ + "\nLlama LLM requires package llama-cpp. Falling back to GPT-3.5-turbo."
156
+ + "\033[0m\033[0m"
157
+ )
158
+ LLM_MODEL = "gpt-3.5-turbo"
159
+
160
+ if LLM_MODEL.startswith("gpt-4"):
161
+ print(
162
+ "\033[91m\033[1m"
163
+ + "\n*****USING GPT-4. POTENTIALLY EXPENSIVE. MONITOR YOUR COSTS*****"
164
+ + "\033[0m\033[0m"
165
+ )
166
+
167
+ if LLM_MODEL.startswith("human"):
168
+ print(
169
+ "\033[91m\033[1m"
170
+ + "\n*****USING HUMAN INPUT*****"
171
+ + "\033[0m\033[0m"
172
+ )
173
+
174
+ print("\033[94m\033[1m" + "\n*****OBJECTIVE*****\n" + "\033[0m\033[0m")
175
+ print(f"{OBJECTIVE}")
176
+
177
+ if not JOIN_EXISTING_OBJECTIVE:
178
+ print("\033[93m\033[1m" + "\nInitial task:" + "\033[0m\033[0m" + f" {INITIAL_TASK}")
179
+ else:
180
+ print("\033[93m\033[1m" + f"\nJoining to help the objective" + "\033[0m\033[0m")
181
+
182
+ # Configure OpenAI
183
+ openai.api_key = os.getenv("api_key")
184
+
185
+
186
+ # Llama embedding function
187
+ class LlamaEmbeddingFunction(EmbeddingFunction):
188
+ def __init__(self):
189
+ return
190
+
191
+
192
+ def __call__(self, texts: Documents) -> Embeddings:
193
+ embeddings = []
194
+ for t in texts:
195
+ e = llm_embed.embed(t)
196
+ embeddings.append(e)
197
+ return embeddings
198
+
199
+
200
+ # Results storage using local ChromaDB
201
+ class DefaultResultsStorage:
202
+ def __init__(self):
203
+ logging.getLogger('chromadb').setLevel(logging.ERROR)
204
+ # Create Chroma collection
205
+ chroma_persist_dir = "chroma"
206
+ chroma_client = chromadb.PersistentClient(
207
+ settings=chromadb.config.Settings(
208
+ persist_directory=chroma_persist_dir,
209
+ )
210
+ )
211
+
212
+ metric = "cosine"
213
+ if LLM_MODEL.startswith("llama"):
214
+ embedding_function = LlamaEmbeddingFunction()
215
+ else:
216
+ embedding_function = OpenAIEmbeddingFunction(api_key=OPENAI_API_KEY)
217
+ self.collection = chroma_client.get_or_create_collection(
218
+ name=RESULTS_STORE_NAME,
219
+ metadata={"hnsw:space": metric},
220
+ embedding_function=embedding_function,
221
+ )
222
+
223
+
224
+
225
+ def add(self, task: Dict, result: str, result_id: str):
226
+
227
+ # Break the function if LLM_MODEL starts with "human" (case-insensitive)
228
+ if LLM_MODEL.startswith("human"):
229
+ return
230
+ return
231
+ #from langchain_community.chat_models import ChatOpenAI
232
+ # Continue with the rest of the function
233
+ #llm_embed = ChatOpenAI(model_name="lama3-70b-8192",
234
+ # openai_api_key="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",
235
+ # openai_api_base="https://api.groq.com/openai/v1",
236
+ # )
237
+ #import openai
238
+ #openai.api_key = "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"
239
+ #openai.api_base = "https://api.groq.com/openai/v1"
240
+ #response = openai.embeddings.create(input=result,
241
+ # model="lama3-70b-8192",
242
+ #
243
+ inputs = tokenizer(result, return_tensors="pt")
244
+ outputs = model(**inputs)
245
+ # [CLS]トークンの出力を取得
246
+ embeddings = outputs.last_hidden_state[:,0,:].squeeze().detach().cpu().numpy().tolist()
247
+ #cls_embedding = outputs.last_hidden_state[:, 0, :].squeeze()
248
+ # テンソルが CPU 上にあることを確認し、NumPy 配列に変換
249
+ #cls_embedding_np = cls_embedding.detach().cpu().numpy()
250
+
251
+ #embeddings = response['data'][0]['embedding']
252
+ embeddings = llm_embed.embed(result) if LLM_MODEL.startswith("llama") else None
253
+ if (
254
+ len(self.collection.get(ids=[result_id], include=[])["ids"]) > 0
255
+ ): # Check if the result already exists
256
+ self.collection.update(
257
+ ids=result_id,
258
+ embeddings=embeddings,
259
+ documents=result,
260
+ metadatas={"task": task["task_name"], "result": result},
261
+ )
262
+ else:
263
+ self.collection.add(
264
+ ids=result_id,
265
+ embeddings=embeddings,
266
+ documents=result,
267
+ metadatas={"task": task["task_name"], "result": result},
268
+ )
269
+
270
+ def query(self, query: str, top_results_num: int) -> List[dict]:
271
+ count: int = self.collection.count()
272
+ if count == 0:
273
+ return []
274
+ results = self.collection.query(
275
+ query_texts=query,
276
+ n_results=min(top_results_num, count),
277
+ include=["metadatas"]
278
+ )
279
+ return [item["task"] for item in results["metadatas"][0]]
280
+
281
+
282
+ # Initialize results storage
283
+ def try_weaviate():
284
+ WEAVIATE_URL = os.getenv("WEAVIATE_URL", "")
285
+ WEAVIATE_USE_EMBEDDED = os.getenv("WEAVIATE_USE_EMBEDDED", "False").lower() == "true"
286
+ if (WEAVIATE_URL or WEAVIATE_USE_EMBEDDED) and can_import("extensions.weaviate_storage"):
287
+ WEAVIATE_API_KEY = os.getenv("WEAVIATE_API_KEY", "")
288
+ from extensions.weaviate_storage import WeaviateResultsStorage
289
+ print("\nUsing results storage: " + "\033[93m\033[1m" + "Weaviate" + "\033[0m\033[0m")
290
+ return WeaviateResultsStorage(OPENAI_API_KEY, WEAVIATE_URL, WEAVIATE_API_KEY, WEAVIATE_USE_EMBEDDED, LLM_MODEL, LLAMA_MODEL_PATH, RESULTS_STORE_NAME, OBJECTIVE)
291
+ return None
292
+
293
+ def try_pinecone():
294
+ PINECONE_API_KEY = os.getenv("PINECONE_API_KEY", "")
295
+ if PINECONE_API_KEY and can_import("extensions.pinecone_storage"):
296
+ PINECONE_ENVIRONMENT = os.getenv("PINECONE_ENVIRONMENT", "")
297
+ assert (
298
+ PINECONE_ENVIRONMENT
299
+ ), "\033[91m\033[1m" + "PINECONE_ENVIRONMENT environment variable is missing from .env" + "\033[0m\033[0m"
300
+ from extensions.pinecone_storage import PineconeResultsStorage
301
+ print("\nUsing results storage: " + "\033[93m\033[1m" + "Pinecone" + "\033[0m\033[0m")
302
+ return PineconeResultsStorage(OPENAI_API_KEY, PINECONE_API_KEY, PINECONE_ENVIRONMENT, LLM_MODEL, LLAMA_MODEL_PATH, RESULTS_STORE_NAME, OBJECTIVE)
303
+ return None
304
+
305
+ def use_chroma():
306
+ print("\nUsing results storage: " + "\033[93m\033[1m" + "Chroma (Default)" + "\033[0m\033[0m")
307
+ return DefaultResultsStorage()
308
+
309
+ results_storage = try_weaviate() or try_pinecone() or use_chroma()
310
+
311
+ # Task storage supporting only a single instance of BabyAGI
312
+ class SingleTaskListStorage:
313
+ def __init__(self):
314
+ self.tasks = deque([])
315
+ self.task_id_counter = 0
316
+
317
+ def append(self, task: Dict):
318
+ self.tasks.append(task)
319
+
320
+ def replace(self, tasks: List[Dict]):
321
+ self.tasks = deque(tasks)
322
+
323
+ def popleft(self):
324
+ return self.tasks.popleft()
325
+
326
+ def is_empty(self):
327
+ return False if self.tasks else True
328
+
329
+ def next_task_id(self):
330
+ self.task_id_counter += 1
331
+ return self.task_id_counter
332
+
333
+ def get_task_names(self):
334
+ return [t["task_name"] for t in self.tasks]
335
+
336
+
337
+ # Initialize tasks storage
338
+ tasks_storage = SingleTaskListStorage()
339
+ if COOPERATIVE_MODE in ['l', 'local']:
340
+ if can_import("extensions.ray_tasks"):
341
+ import sys
342
+ from pathlib import Path
343
+
344
+ sys.path.append(str(Path(__file__).resolve().parent))
345
+ from extensions.ray_tasks import CooperativeTaskListStorage
346
+
347
+ tasks_storage = CooperativeTaskListStorage(OBJECTIVE)
348
+ print("\nReplacing tasks storage: " + "\033[93m\033[1m" + "Ray" + "\033[0m\033[0m")
349
+ elif COOPERATIVE_MODE in ['d', 'distributed']:
350
+ pass
351
+
352
+
353
+ def limit_tokens_from_string(string: str, model: str, limit: int) -> str:
354
+ """Limits the string to a number of tokens (estimated)."""
355
+
356
+ try:
357
+ encoding = tiktoken.encoding_for_model(model)
358
+ except:
359
+ encoding = tiktoken.encoding_for_model('gpt2') # Fallback for others.
360
+
361
+ encoded = encoding.encode(string)
362
+
363
+ return encoding.decode(encoded[:limit])
364
+
365
+
366
+ def openai_call(
367
+ prompt: str,
368
+ model: str = LLM_MODEL,
369
+ temperature: float = OPENAI_TEMPERATURE,
370
+ max_tokens: int = 100,
371
+ ):
372
+ while True:
373
+ messages=[
374
+ {
375
+ "role": "user",
376
+ "content": "prompt"
377
+ }
378
+ ],
379
+ client = Groq(api_key=os.getenv("api_key"))
380
+ res = ""
381
+ print(prompt)
382
+ completion = client.chat.completions.create(
383
+ model="llama3-8b-8192",
384
+ messages=[
385
+ {
386
+ "role": "user",
387
+ "content": prompt
388
+ }
389
+ ],
390
+ temperature=1,
391
+ max_tokens=1024,
392
+ top_p=1,
393
+ stream=True,
394
+ stop=None,
395
+ )
396
+ for chunk in completion:
397
+ #print(chunk.choices[0].delta.content)
398
+ #print(chunk.choices[0].delta.content or "", end="")
399
+ res += chunk.choices[0].delta.content or ""
400
+ return res
401
+
402
+ while True:
403
+
404
+
405
+ try:
406
+ if model.lower().startswith("llama"):
407
+ result = llm(prompt[:CTX_MAX],
408
+ stop=["### Human"],
409
+ echo=False,
410
+ temperature=0.2,
411
+ top_k=40,
412
+ top_p=0.95,
413
+ repeat_penalty=1.05,
414
+ max_tokens=200)
415
+ # print('\n*****RESULT JSON DUMP*****\n')
416
+ # print(json.dumps(result))
417
+ # print('\n')
418
+ for chunk in completion:
419
+ print(chunk.choices[0].delta.content or "", end="")
420
+ return result['choices'][0]['text'].strip()
421
+ elif model.lower().startswith("human"):
422
+ return user_input_await(prompt)
423
+ elif not model.lower().startswith("gpt-"):
424
+ # Use completion API
425
+ response = openai.Completion.create(
426
+ engine=model,
427
+ prompt=prompt,
428
+ temperature=temperature,
429
+ max_tokens=max_tokens,
430
+ top_p=1,
431
+ frequency_penalty=0,
432
+ presence_penalty=0,
433
+ )
434
+ return response.choices[0].text.strip()
435
+ else:
436
+ # Use 4000 instead of the real limit (4097) to give a bit of wiggle room for the encoding of roles.
437
+ # TODO: different limits for different models.
438
+
439
+ trimmed_prompt = limit_tokens_from_string(prompt, model, 4000 - max_tokens)
440
+
441
+ # Use chat completion API
442
+ messages = [{"role": "system", "content": trimmed_prompt}]
443
+ response = openai.ChatCompletion.create(
444
+ model=model,
445
+ messages=messages,
446
+ temperature=temperature,
447
+ max_tokens=max_tokens,
448
+ n=1,
449
+ stop=None,
450
+ )
451
+ return response.choices[0].message.content.strip()
452
+ except openai.error.RateLimitError:
453
+ print(
454
+ " *** The OpenAI API rate limit has been exceeded. Waiting 10 seconds and trying again. ***"
455
+ )
456
+ time.sleep(10) # Wait 10 seconds and try again
457
+ except openai.error.Timeout:
458
+ print(
459
+ " *** OpenAI API timeout occurred. Waiting 10 seconds and trying again. ***"
460
+ )
461
+ time.sleep(10) # Wait 10 seconds and try again
462
+ except openai.error.APIError:
463
+ print(
464
+ " *** OpenAI API error occurred. Waiting 10 seconds and trying again. ***"
465
+ )
466
+ time.sleep(10) # Wait 10 seconds and try again
467
+ except openai.error.APIConnectionError:
468
+ print(
469
+ " *** OpenAI API connection error occurred. Check your network settings, proxy configuration, SSL certificates, or firewall rules. Waiting 10 seconds and trying again. ***"
470
+ )
471
+ time.sleep(10) # Wait 10 seconds and try again
472
+ except openai.error.InvalidRequestError:
473
+ print(
474
+ " *** OpenAI API invalid request. Check the documentation for the specific API method you are calling and make sure you are sending valid and complete parameters. Waiting 10 seconds and trying again. ***"
475
+ )
476
+ time.sleep(10) # Wait 10 seconds and try again
477
+ except openai.error.ServiceUnavailableError:
478
+ print(
479
+ " *** OpenAI API service unavailable. Waiting 10 seconds and trying again. ***"
480
+ )
481
+ time.sleep(10) # Wait 10 seconds and try again
482
+ else:
483
+ break
484
+
485
+
486
+ def task_creation_agent(
487
+ objective: str, result: Dict, task_description: str, task_list: List[str]
488
+ ):
489
+ prompt = f"""
490
+ You are to use the result from an execution agent to create new tasks with the following objective: {objective}.
491
+ The last completed task has the result: \n{result["data"]}
492
+ This result was based on this task description: {task_description}.\n"""
493
+
494
+ if task_list:
495
+ prompt += f"These are incomplete tasks: {', '.join(task_list)}\n"
496
+ prompt += "Based on the result, return a list of tasks to be completed in order to meet the objective. "
497
+ if task_list:
498
+ prompt += "These new tasks must not overlap with incomplete tasks. "
499
+
500
+ prompt += """
501
+ Return one task per line in your response. The result must be a numbered list in the format:
502
+
503
+ #. First task
504
+ #. Second task
505
+
506
+ The number of each entry must be followed by a period. If your list is empty, write "There are no tasks to add at this time."
507
+ Unless your list is empty, do not include any headers before your numbered list or follow your numbered list with any other output."""
508
+
509
+ print(f'\n*****TASK CREATION AGENT PROMPT****\n{prompt}\n')
510
+ response = openai_call(prompt, max_tokens=4000)
511
+ print(f'\n****TASK CREATION AGENT RESPONSE****\n{response}\n')
512
+ new_tasks = response.split('\n')
513
+ new_tasks_list = []
514
+ for task_string in new_tasks:
515
+ task_parts = task_string.strip().split(".", 1)
516
+ if len(task_parts) == 2:
517
+ task_id = ''.join(s for s in task_parts[0] if s.isnumeric())
518
+ task_name = re.sub(r'[^\w\s_]+', '', task_parts[1]).strip()
519
+ if task_name.strip() and task_id.isnumeric():
520
+ new_tasks_list.append(task_name)
521
+ # print('New task created: ' + task_name)
522
+
523
+ out = [{"task_name": task_name} for task_name in new_tasks_list]
524
+ return out
525
+
526
+
527
+ def prioritization_agent():
528
+ task_names = tasks_storage.get_task_names()
529
+ bullet_string = '\n'
530
+
531
+ prompt = f"""
532
+ You are tasked with prioritizing the following tasks: {bullet_string + bullet_string.join(task_names)}
533
+ Consider the ultimate objective of your team: {OBJECTIVE}.
534
+ Tasks should be sorted from highest to lowest priority, where higher-priority tasks are those that act as pre-requisites or are more essential for meeting the objective.
535
+ Do not remove any tasks. Return the ranked tasks as a numbered list in the format:
536
+
537
+ #. First task
538
+ #. Second task
539
+
540
+ The entries must be consecutively numbered, starting with 1. The number of each entry must be followed by a period.
541
+ Do not include any headers before your ranked list or follow your list with any other output."""
542
+
543
+ print(f'\n****TASK PRIORITIZATION AGENT PROMPT****\n{prompt}\n')
544
+ response = openai_call(prompt, max_tokens=2000)
545
+ print(f'\n****TASK PRIORITIZATION AGENT RESPONSE****\n{response}\n')
546
+ if not response:
547
+ print('Received empty response from priotritization agent. Keeping task list unchanged.')
548
+ return
549
+ new_tasks = response.split("\n") if "\n" in response else [response]
550
+ new_tasks_list = []
551
+ for task_string in new_tasks:
552
+ task_parts = task_string.strip().split(".", 1)
553
+ if len(task_parts) == 2:
554
+ task_id = ''.join(s for s in task_parts[0] if s.isnumeric())
555
+ task_name = re.sub(r'[^\w\s_]+', '', task_parts[1]).strip()
556
+ if task_name.strip():
557
+ new_tasks_list.append({"task_id": task_id, "task_name": task_name})
558
+
559
+ return new_tasks_list
560
+
561
+
562
+ # Execute a task based on the objective and five previous tasks
563
+ def execution_agent(objective: str, task: str) -> str:
564
+ """
565
+ Executes a task based on the given objective and previous context.
566
+
567
+ Args:
568
+ objective (str): The objective or goal for the AI to perform the task.
569
+ task (str): The task to be executed by the AI.
570
+
571
+ Returns:
572
+ str: The response generated by the AI for the given task.
573
+
574
+ """
575
+
576
+ context = context_agent(query=objective, top_results_num=5)
577
+ # print("\n****RELEVANT CONTEXT****\n")
578
+ # print(context)
579
+ # print('')
580
+ prompt = f'Perform one task based on the following objective: {objective}.\n'
581
+ if context:
582
+ prompt += 'Take into account these previously completed tasks:' + '\n'.join(context)
583
+ prompt += f'\nYour task: {task}\nResponse:'
584
+ return openai_call(prompt, max_tokens=2000)
585
+
586
+
587
+ # Get the top n completed tasks for the objective
588
+ def context_agent(query: str, top_results_num: int):
589
+ """
590
+ Retrieves context for a given query from an index of tasks.
591
+
592
+ Args:
593
+ query (str): The query or objective for retrieving context.
594
+ top_results_num (int): The number of top results to retrieve.
595
+
596
+ Returns:
597
+ list: A list of tasks as context for the given query, sorted by relevance.
598
+
599
+ """
600
+ results = results_storage.query(query=query, top_results_num=top_results_num)
601
+ # print("****RESULTS****")
602
+ # print(results)
603
+ return results
604
+
605
+
606
+ # Add the initial task if starting new objective
607
+ if not JOIN_EXISTING_OBJECTIVE:
608
+ initial_task = {
609
+ "task_id": tasks_storage.next_task_id(),
610
+ "task_name": INITIAL_TASK
611
+ }
612
+ tasks_storage.append(initial_task)
613
+
614
+
615
+ def main():
616
+ loop = True
617
+ while loop:
618
+ # As long as there are tasks in the storage...
619
+ if not tasks_storage.is_empty():
620
+ #OBJECTIVE = "ボットの性能をよくする方法 日本語で説明"
621
+ # Print the task list
622
+ print("\033[95m\033[1m" + "\n*****TASK LIST*****\n" + "\033[0m\033[0m")
623
+ for t in tasks_storage.get_task_names():
624
+ print(" • " + str(t))
625
+
626
+ # Step 1: Pull the first incomplete task
627
+ task = tasks_storage.popleft()
628
+ print("\033[92m\033[1m" + "\n*****NEXT TASK*****\n" + "\033[0m\033[0m")
629
+ print(str(task["task_name"]))
630
+
631
+ # Send to execution function to complete the task based on the context
632
+ result = execution_agent(OBJECTIVE, str(task["task_name"]))
633
+ print("\033[93m\033[1m" + "\n*****TASK RESULT*****\n" + "\033[0m\033[0m")
634
+ print(result)
635
+
636
+ # Step 2: Enrich result and store in the results storage
637
+ # This is where you should enrich the result if needed
638
+ enriched_result = {
639
+ "data": result
640
+ }
641
+ # extract the actual result from the dictionary
642
+ # since we don't do enrichment currently
643
+ # vector = enriched_result["data"]
644
+
645
+ result_id = f"result_{task['task_id']}"
646
+
647
+ #results_storage.add(task, result, result_id)
648
+
649
+ # Step 3: Create new tasks and re-prioritize task list
650
+ # only the main instance in cooperative mode does that
651
+ new_tasks = task_creation_agent(
652
+ OBJECTIVE,
653
+ enriched_result,
654
+ task["task_name"],
655
+ tasks_storage.get_task_names(),
656
+ )
657
+
658
+ print('Adding new tasks to task_storage')
659
+ for new_task in new_tasks:
660
+ new_task.update({"task_id": tasks_storage.next_task_id()})
661
+ print(str(new_task))
662
+ tasks_storage.append(new_task)
663
+
664
+ if not JOIN_EXISTING_OBJECTIVE:
665
+ prioritized_tasks = prioritization_agent()
666
+ if prioritized_tasks:
667
+ tasks_storage.replace(prioritized_tasks)
668
+
669
+ # Sleep a bit before checking the task list again
670
+ time.sleep(5)
671
+ else:
672
+ print('Done.')
673
+ loop = False
674
+
675
+
676
+ if __name__ == "__main__":
677
+ main()
AutoPrompt/config/config_default.yml CHANGED
@@ -4,15 +4,16 @@ dataset:
4
  records_path: null
5
  initial_dataset: ''
6
  label_schema: ["Yes", "No"]
7
- max_samples: 50
8
  semantic_sampling: False # Change to True in case you don't have M1. Currently there is an issue with faiss and M1
9
 
 
10
  annotator:
11
  method : 'argilla'
12
  config:
13
  api_url: 'https://kenken999-arglira.hf.space'
14
- api_key: 'admin.apikey'
15
- workspace: 'admin'
16
  time_interval: 5
17
 
18
  predictor:
 
4
  records_path: null
5
  initial_dataset: ''
6
  label_schema: ["Yes", "No"]
7
+ max_samples: 10
8
  semantic_sampling: False # Change to True in case you don't have M1. Currently there is an issue with faiss and M1
9
 
10
+
11
  annotator:
12
  method : 'argilla'
13
  config:
14
  api_url: 'https://kenken999-arglira.hf.space'
15
+ api_key: '12345678'
16
+ workspace: 'team'
17
  time_interval: 5
18
 
19
  predictor:
AutoPrompt/prompt.py CHANGED
@@ -8,8 +8,22 @@ import subprocess
8
 
9
  command = [
10
  'python', 'run_pipeline.py',
11
- '--prompt', '金、ダイヤ、ブランドの中古品の買取の査定のプロです。正しい商品査定をして商品の詳細を出し買取金額を提示していますか? answer Yes or No',
12
- '--task_description', 'あなたは金、ダイヤ、ブランドの中古品の買取の査定のプロです。正しい商品査定をして商品の詳細を出し買取金額を提示するのが役割です',
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  '--num_steps', '30'
14
  ]
15
 
 
8
 
9
  command = [
10
  'python', 'run_pipeline.py',
11
+ '--prompt', '査定項目と金額があっているかを yes,noで答えて下さい',
12
+ '--task_description', 'あなたは金、ダイヤ、ブランドの査定者です 商品の査定項目を細かく出し 査定額を計算して提示します',
13
+ '--num_steps', '10'
14
+ ]
15
+
16
+ command3 = [
17
+ 'python', 'run_generation_pipeline.py',
18
+ '--prompt', 'この映画レビューにはネタバレが含まれていますか?YesまたはNoで答えてください',
19
+ '--task_description', 'アシスタントは、映画レビューを分類するエキスパートであり、レビューされた映画のネタバレが含まれているかどうかをユーザーに教えてくれます。',
20
+ #'--num_steps', '30'
21
+ ]
22
+
23
+ command2 = [
24
+ 'python', 'run_pipeline.py',
25
+ '--prompt', 'この映画レビューにはネタバレが含まれていますか?YesまたはNoで答えてください',
26
+ '--task_description', 'アシスタントは、映画レビューを分類するエキスパートであり、レビューされた映画のネタバレが含まれているかどうかをユーザーに教えてくれます。',
27
  '--num_steps', '30'
28
  ]
29
 
AutoPrompt/python ADDED
File without changes
AutoPrompt/run_generation_pipeline.py CHANGED
@@ -15,7 +15,7 @@ parser.add_argument('--task_description',
15
  parser.add_argument('--prompt',
16
  default='',
17
  required=False, type=str, help='Prompt to use as initial.')
18
- parser.add_argument('--load_dump', default='', required=False, type=str, help='In case of loading from checkpoint')
19
  parser.add_argument('--output_dump', default='dump', required=False, type=str, help='Output to save checkpoints')
20
  parser.add_argument('--num_ranker_steps', default=20, type=int, help='Number of iterations')
21
  parser.add_argument('--num_generation_steps', default=20, type=int, help='Number of iterations')
 
15
  parser.add_argument('--prompt',
16
  default='',
17
  required=False, type=str, help='Prompt to use as initial.')
18
+ parser.add_argument('--load_dump', default='dump', required=False, type=str, help='In case of loading from checkpoint')
19
  parser.add_argument('--output_dump', default='dump', required=False, type=str, help='Output to save checkpoints')
20
  parser.add_argument('--num_ranker_steps', default=20, type=int, help='Number of iterations')
21
  parser.add_argument('--num_generation_steps', default=20, type=int, help='Number of iterations')
AutoPrompt/utils/llm_chain.py CHANGED
@@ -66,15 +66,12 @@ class ChainWrapper:
66
  if self.parser_func is not None:
67
  result = self.parser_func(result)
68
  except Exception as e:
69
- print(e)
70
- logging.error(e)
71
- #Wlogging.error('Error in chain invoke: {}'.format(e.user_message))
72
- result = None
73
  #if e.http_status == 401:
74
  # raise e
75
  #else:
76
- # logging.error('Error in chain invoke: {}'.format(e.user_message))
77
- # result = None
78
  self.accumulate_usage += cb.total_cost
79
  return result
80
 
@@ -158,6 +155,7 @@ class ChainWrapper:
158
  Build the chain according to the LLM type
159
  """
160
  if (self.llm_config.type == 'OpenAI' or self.llm_config.type == 'Azure') and self.json_schema is not None:
 
161
  self.chain = create_structured_output_runnable(self.json_schema, self.llm, self.prompt)
162
  else:
163
  self.chain = LLMChain(llm=self.llm, prompt=self.prompt)
 
66
  if self.parser_func is not None:
67
  result = self.parser_func(result)
68
  except Exception as e:
69
+ #raise e
 
 
 
70
  #if e.http_status == 401:
71
  # raise e
72
  #else:
73
+ #logging.error('Error in chain invoke: {}'.format(e.user_message))
74
+ result = None
75
  self.accumulate_usage += cb.total_cost
76
  return result
77
 
 
155
  Build the chain according to the LLM type
156
  """
157
  if (self.llm_config.type == 'OpenAI' or self.llm_config.type == 'Azure') and self.json_schema is not None:
158
+ #self.chain = LLMChain(llm=self.llm, prompt=self.prompt)
159
  self.chain = create_structured_output_runnable(self.json_schema, self.llm, self.prompt)
160
  else:
161
  self.chain = LLMChain(llm=self.llm, prompt=self.prompt)
babyagi/_config.yml CHANGED
@@ -2,7 +2,7 @@ title: BabyAGI
2
  email:
3
  description: >-
4
  BabyAGI is an AI-powered task management system that uses OpenAI and Pinecone APIs to create, prioritize, and execute tasks.
5
- baseurl: ""
6
  url: "https://babyagi.org"
7
  logo: docs/babyagi.png
8
  twitter_username: babyagi_
 
2
  email:
3
  description: >-
4
  BabyAGI is an AI-powered task management system that uses OpenAI and Pinecone APIs to create, prioritize, and execute tasks.
5
+ baseurl: "https://api.groq.com/openai/v1"
6
  url: "https://babyagi.org"
7
  logo: docs/babyagi.png
8
  twitter_username: babyagi_
babyagi/babyagi copy.py ADDED
@@ -0,0 +1,643 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from dotenv import load_dotenv
3
+
4
+ # Load default environment variables (.env)
5
+ load_dotenv()
6
+
7
+ import os
8
+ import time
9
+ import logging
10
+ from collections import deque
11
+ from typing import Dict, List
12
+ import importlib
13
+ import openai
14
+ import chromadb
15
+ import tiktoken as tiktoken
16
+ from chromadb.utils.embedding_functions import OpenAIEmbeddingFunction
17
+ from chromadb.api.types import Documents, EmbeddingFunction, Embeddings
18
+ import re
19
+ from groq import Groq
20
+
21
+ # default opt out of chromadb telemetry.
22
+ from chromadb.config import Settings
23
+
24
+ client = chromadb.Client(Settings(anonymized_telemetry=False))
25
+
26
+ # Engine configuration
27
+
28
+ # Model: GPT, LLAMA, HUMAN, etc.
29
+ LLM_MODEL = os.getenv("LLM_MODEL", os.getenv("OPENAI_API_MODEL", "gpt-3.5-turbo")).lower()
30
+
31
+ # API Keys
32
+ OPENAI_API_KEY = os.getenv("api_key", "")
33
+ if not (LLM_MODEL.startswith("llama") or LLM_MODEL.startswith("human")):
34
+ assert OPENAI_API_KEY, "\033[91m\033[1m" + "OPENAI_API_KEY environment variable is missing from .env" + "\033[0m\033[0m"
35
+
36
+ # Table config
37
+ RESULTS_STORE_NAME = os.getenv("RESULTS_STORE_NAME", os.getenv("TABLE_NAME", ""))
38
+ assert RESULTS_STORE_NAME, "\033[91m\033[1m" + "RESULTS_STORE_NAME environment variable is missing from .env" + "\033[0m\033[0m"
39
+
40
+ # Run configuration
41
+ INSTANCE_NAME = os.getenv("INSTANCE_NAME", os.getenv("BABY_NAME", "BabyAGI"))
42
+ COOPERATIVE_MODE = "none"
43
+ JOIN_EXISTING_OBJECTIVE = False
44
+
45
+ # Goal configuration
46
+ OBJECTIVE = os.getenv("OBJECTIVE", "")
47
+ INITIAL_TASK = os.getenv("INITIAL_TASK", os.getenv("FIRST_TASK", ""))
48
+
49
+ # Model configuration
50
+ OPENAI_TEMPERATURE = float(os.getenv("OPENAI_TEMPERATURE", 0.0))
51
+
52
+
53
+ # Extensions support begin
54
+
55
+ def can_import(module_name):
56
+ try:
57
+ importlib.import_module(module_name)
58
+ return True
59
+ except ImportError:
60
+ return False
61
+
62
+
63
+ DOTENV_EXTENSIONS = os.getenv("DOTENV_EXTENSIONS", "").split(" ")
64
+
65
+ # Command line arguments extension
66
+ # Can override any of the above environment variables
67
+ ENABLE_COMMAND_LINE_ARGS = (
68
+ os.getenv("ENABLE_COMMAND_LINE_ARGS", "false").lower() == "true"
69
+ )
70
+ if ENABLE_COMMAND_LINE_ARGS:
71
+ if can_import("extensions.argparseext"):
72
+ from extensions.argparseext import parse_arguments
73
+
74
+ OBJECTIVE, INITIAL_TASK, LLM_MODEL, DOTENV_EXTENSIONS, INSTANCE_NAME, COOPERATIVE_MODE, JOIN_EXISTING_OBJECTIVE = parse_arguments()
75
+
76
+ # Human mode extension
77
+ # Gives human input to babyagi
78
+ if LLM_MODEL.startswith("human"):
79
+ if can_import("extensions.human_mode"):
80
+ from extensions.human_mode import user_input_await
81
+
82
+ # Load additional environment variables for enabled extensions
83
+ # TODO: This might override the following command line arguments as well:
84
+ # OBJECTIVE, INITIAL_TASK, LLM_MODEL, INSTANCE_NAME, COOPERATIVE_MODE, JOIN_EXISTING_OBJECTIVE
85
+ if DOTENV_EXTENSIONS:
86
+ if can_import("extensions.dotenvext"):
87
+ from extensions.dotenvext import load_dotenv_extensions
88
+
89
+ load_dotenv_extensions(DOTENV_EXTENSIONS)
90
+
91
+ # TODO: There's still work to be done here to enable people to get
92
+ # defaults from dotenv extensions, but also provide command line
93
+ # arguments to override them
94
+
95
+ # Extensions support end
96
+
97
+ print("\033[95m\033[1m" + "\n*****CONFIGURATION*****\n" + "\033[0m\033[0m")
98
+ print(f"Name : {INSTANCE_NAME}")
99
+ print(f"Mode : {'alone' if COOPERATIVE_MODE in ['n', 'none'] else 'local' if COOPERATIVE_MODE in ['l', 'local'] else 'distributed' if COOPERATIVE_MODE in ['d', 'distributed'] else 'undefined'}")
100
+ print(f"LLM : {LLM_MODEL}")
101
+
102
+
103
+ # Check if we know what we are doing
104
+ assert OBJECTIVE, "\033[91m\033[1m" + "OBJECTIVE environment variable is missing from .env" + "\033[0m\033[0m"
105
+ assert INITIAL_TASK, "\033[91m\033[1m" + "INITIAL_TASK environment variable is missing from .env" + "\033[0m\033[0m"
106
+
107
+ LLAMA_MODEL_PATH = os.getenv("LLAMA_MODEL_PATH", "models/llama-13B/ggml-model.bin")
108
+ if LLM_MODEL.startswith("llama"):
109
+ if can_import("llama_cpp"):
110
+ from llama_cpp import Llama
111
+
112
+ print(f"LLAMA : {LLAMA_MODEL_PATH}" + "\n")
113
+ assert os.path.exists(LLAMA_MODEL_PATH), "\033[91m\033[1m" + f"Model can't be found." + "\033[0m\033[0m"
114
+
115
+ CTX_MAX = 1024
116
+ LLAMA_THREADS_NUM = int(os.getenv("LLAMA_THREADS_NUM", 8))
117
+
118
+ print('Initialize model for evaluation')
119
+ llm = Llama(
120
+ model_path=LLAMA_MODEL_PATH,
121
+ n_ctx=CTX_MAX,
122
+ n_threads=LLAMA_THREADS_NUM,
123
+ n_batch=512,
124
+ use_mlock=False,
125
+ )
126
+
127
+ print('\nInitialize model for embedding')
128
+ llm_embed = Llama(
129
+ model_path=LLAMA_MODEL_PATH,
130
+ n_ctx=CTX_MAX,
131
+ n_threads=LLAMA_THREADS_NUM,
132
+ n_batch=512,
133
+ embedding=True,
134
+ use_mlock=False,
135
+ )
136
+
137
+ print(
138
+ "\033[91m\033[1m"
139
+ + "\n*****USING LLAMA.CPP. POTENTIALLY SLOW.*****"
140
+ + "\033[0m\033[0m"
141
+ )
142
+ else:
143
+ print(
144
+ "\033[91m\033[1m"
145
+ + "\nLlama LLM requires package llama-cpp. Falling back to GPT-3.5-turbo."
146
+ + "\033[0m\033[0m"
147
+ )
148
+ LLM_MODEL = "gpt-3.5-turbo"
149
+
150
+ if LLM_MODEL.startswith("gpt-4"):
151
+ print(
152
+ "\033[91m\033[1m"
153
+ + "\n*****USING GPT-4. POTENTIALLY EXPENSIVE. MONITOR YOUR COSTS*****"
154
+ + "\033[0m\033[0m"
155
+ )
156
+
157
+ if LLM_MODEL.startswith("human"):
158
+ print(
159
+ "\033[91m\033[1m"
160
+ + "\n*****USING HUMAN INPUT*****"
161
+ + "\033[0m\033[0m"
162
+ )
163
+
164
+ print("\033[94m\033[1m" + "\n*****OBJECTIVE*****\n" + "\033[0m\033[0m")
165
+ print(f"{OBJECTIVE}")
166
+
167
+ if not JOIN_EXISTING_OBJECTIVE:
168
+ print("\033[93m\033[1m" + "\nInitial task:" + "\033[0m\033[0m" + f" {INITIAL_TASK}")
169
+ else:
170
+ print("\033[93m\033[1m" + f"\nJoining to help the objective" + "\033[0m\033[0m")
171
+
172
+ # Configure OpenAI
173
+ openai.api_key = os.getenv("api_key")
174
+
175
+
176
+ # Llama embedding function
177
+ class LlamaEmbeddingFunction(EmbeddingFunction):
178
+ def __init__(self):
179
+ return
180
+
181
+
182
+ def __call__(self, texts: Documents) -> Embeddings:
183
+ embeddings = []
184
+ for t in texts:
185
+ e = llm_embed.embed(t)
186
+ embeddings.append(e)
187
+ return embeddings
188
+
189
+
190
+ # Results storage using local ChromaDB
191
+ class DefaultResultsStorage:
192
+ def __init__(self):
193
+ logging.getLogger('chromadb').setLevel(logging.ERROR)
194
+ # Create Chroma collection
195
+ chroma_persist_dir = "chroma"
196
+ chroma_client = chromadb.PersistentClient(
197
+ settings=chromadb.config.Settings(
198
+ persist_directory=chroma_persist_dir,
199
+ )
200
+ )
201
+
202
+ metric = "cosine"
203
+ if LLM_MODEL.startswith("llama"):
204
+ embedding_function = LlamaEmbeddingFunction()
205
+ else:
206
+ embedding_function = OpenAIEmbeddingFunction(api_key=OPENAI_API_KEY)
207
+ self.collection = chroma_client.get_or_create_collection(
208
+ name=RESULTS_STORE_NAME,
209
+ metadata={"hnsw:space": metric},
210
+ embedding_function=embedding_function,
211
+ )
212
+
213
+ def add(self, task: Dict, result: str, result_id: str):
214
+
215
+ # Break the function if LLM_MODEL starts with "human" (case-insensitive)
216
+ if LLM_MODEL.startswith("human"):
217
+ return
218
+ # Continue with the rest of the function
219
+
220
+ embeddings = llm_embed.embed(result) if LLM_MODEL.startswith("llama") else None
221
+ if (
222
+ len(self.collection.get(ids=[result_id], include=[])["ids"]) > 0
223
+ ): # Check if the result already exists
224
+ self.collection.update(
225
+ ids=result_id,
226
+ embeddings=embeddings,
227
+ documents=result,
228
+ metadatas={"task": task["task_name"], "result": result},
229
+ )
230
+ else:
231
+ self.collection.add(
232
+ ids=result_id,
233
+ embeddings=embeddings,
234
+ documents=result,
235
+ metadatas={"task": task["task_name"], "result": result},
236
+ )
237
+
238
+ def query(self, query: str, top_results_num: int) -> List[dict]:
239
+ count: int = self.collection.count()
240
+ if count == 0:
241
+ return []
242
+ results = self.collection.query(
243
+ query_texts=query,
244
+ n_results=min(top_results_num, count),
245
+ include=["metadatas"]
246
+ )
247
+ return [item["task"] for item in results["metadatas"][0]]
248
+
249
+
250
+ # Initialize results storage
251
+ def try_weaviate():
252
+ WEAVIATE_URL = os.getenv("WEAVIATE_URL", "")
253
+ WEAVIATE_USE_EMBEDDED = os.getenv("WEAVIATE_USE_EMBEDDED", "False").lower() == "true"
254
+ if (WEAVIATE_URL or WEAVIATE_USE_EMBEDDED) and can_import("extensions.weaviate_storage"):
255
+ WEAVIATE_API_KEY = os.getenv("WEAVIATE_API_KEY", "")
256
+ from extensions.weaviate_storage import WeaviateResultsStorage
257
+ print("\nUsing results storage: " + "\033[93m\033[1m" + "Weaviate" + "\033[0m\033[0m")
258
+ return WeaviateResultsStorage(OPENAI_API_KEY, WEAVIATE_URL, WEAVIATE_API_KEY, WEAVIATE_USE_EMBEDDED, LLM_MODEL, LLAMA_MODEL_PATH, RESULTS_STORE_NAME, OBJECTIVE)
259
+ return None
260
+
261
+ def try_pinecone():
262
+ PINECONE_API_KEY = os.getenv("PINECONE_API_KEY", "")
263
+ if PINECONE_API_KEY and can_import("extensions.pinecone_storage"):
264
+ PINECONE_ENVIRONMENT = os.getenv("PINECONE_ENVIRONMENT", "")
265
+ assert (
266
+ PINECONE_ENVIRONMENT
267
+ ), "\033[91m\033[1m" + "PINECONE_ENVIRONMENT environment variable is missing from .env" + "\033[0m\033[0m"
268
+ from extensions.pinecone_storage import PineconeResultsStorage
269
+ print("\nUsing results storage: " + "\033[93m\033[1m" + "Pinecone" + "\033[0m\033[0m")
270
+ return PineconeResultsStorage(OPENAI_API_KEY, PINECONE_API_KEY, PINECONE_ENVIRONMENT, LLM_MODEL, LLAMA_MODEL_PATH, RESULTS_STORE_NAME, OBJECTIVE)
271
+ return None
272
+
273
+ def use_chroma():
274
+ print("\nUsing results storage: " + "\033[93m\033[1m" + "Chroma (Default)" + "\033[0m\033[0m")
275
+ return DefaultResultsStorage()
276
+
277
+ results_storage = try_weaviate() or try_pinecone() or use_chroma()
278
+
279
+ # Task storage supporting only a single instance of BabyAGI
280
+ class SingleTaskListStorage:
281
+ def __init__(self):
282
+ self.tasks = deque([])
283
+ self.task_id_counter = 0
284
+
285
+ def append(self, task: Dict):
286
+ self.tasks.append(task)
287
+
288
+ def replace(self, tasks: List[Dict]):
289
+ self.tasks = deque(tasks)
290
+
291
+ def popleft(self):
292
+ return self.tasks.popleft()
293
+
294
+ def is_empty(self):
295
+ return False if self.tasks else True
296
+
297
+ def next_task_id(self):
298
+ self.task_id_counter += 1
299
+ return self.task_id_counter
300
+
301
+ def get_task_names(self):
302
+ return [t["task_name"] for t in self.tasks]
303
+
304
+
305
+ # Initialize tasks storage
306
+ tasks_storage = SingleTaskListStorage()
307
+ if COOPERATIVE_MODE in ['l', 'local']:
308
+ if can_import("extensions.ray_tasks"):
309
+ import sys
310
+ from pathlib import Path
311
+
312
+ sys.path.append(str(Path(__file__).resolve().parent))
313
+ from extensions.ray_tasks import CooperativeTaskListStorage
314
+
315
+ tasks_storage = CooperativeTaskListStorage(OBJECTIVE)
316
+ print("\nReplacing tasks storage: " + "\033[93m\033[1m" + "Ray" + "\033[0m\033[0m")
317
+ elif COOPERATIVE_MODE in ['d', 'distributed']:
318
+ pass
319
+
320
+
321
+ def limit_tokens_from_string(string: str, model: str, limit: int) -> str:
322
+ """Limits the string to a number of tokens (estimated)."""
323
+
324
+ try:
325
+ encoding = tiktoken.encoding_for_model(model)
326
+ except:
327
+ encoding = tiktoken.encoding_for_model('gpt2') # Fallback for others.
328
+
329
+ encoded = encoding.encode(string)
330
+
331
+ return encoding.decode(encoded[:limit])
332
+
333
+
334
+ def openai_call(
335
+ prompt: str,
336
+ model: str = LLM_MODEL,
337
+ temperature: float = OPENAI_TEMPERATURE,
338
+ max_tokens: int = 100,
339
+ ):
340
+
341
+ messages=[
342
+ {
343
+ "role": "user",
344
+ "content": "prompt"
345
+ }
346
+ ],
347
+ client = Groq(api_key=os.getenv("api_key"))
348
+ res = ""
349
+ completion = client.chat.completions.create(
350
+ model="llama3-8b-8192",
351
+ messages=[
352
+ {
353
+ "role": "user",
354
+ "content": str
355
+ }
356
+ ],
357
+ temperature=1,
358
+ max_tokens=1024,
359
+ top_p=1,
360
+ stream=True,
361
+ stop=None,
362
+ )
363
+ for chunk in completion:
364
+ print(chunk.choices[0].delta.content)
365
+ print(chunk.choices[0].delta.content or "", end="")
366
+ res += chunk.choices[0].delta.content or ""
367
+ return res
368
+
369
+ while True:
370
+
371
+
372
+ try:
373
+ if model.lower().startswith("llama"):
374
+ result = llm(prompt[:CTX_MAX],
375
+ stop=["### Human"],
376
+ echo=False,
377
+ temperature=0.2,
378
+ top_k=40,
379
+ top_p=0.95,
380
+ repeat_penalty=1.05,
381
+ max_tokens=200)
382
+ # print('\n*****RESULT JSON DUMP*****\n')
383
+ # print(json.dumps(result))
384
+ # print('\n')
385
+ for chunk in completion:
386
+ print(chunk.choices[0].delta.content or "", end="")
387
+ return result['choices'][0]['text'].strip()
388
+ elif model.lower().startswith("human"):
389
+ return user_input_await(prompt)
390
+ elif not model.lower().startswith("gpt-"):
391
+ # Use completion API
392
+ response = openai.Completion.create(
393
+ engine=model,
394
+ prompt=prompt,
395
+ temperature=temperature,
396
+ max_tokens=max_tokens,
397
+ top_p=1,
398
+ frequency_penalty=0,
399
+ presence_penalty=0,
400
+ )
401
+ return response.choices[0].text.strip()
402
+ else:
403
+ # Use 4000 instead of the real limit (4097) to give a bit of wiggle room for the encoding of roles.
404
+ # TODO: different limits for different models.
405
+
406
+ trimmed_prompt = limit_tokens_from_string(prompt, model, 4000 - max_tokens)
407
+
408
+ # Use chat completion API
409
+ messages = [{"role": "system", "content": trimmed_prompt}]
410
+ response = openai.ChatCompletion.create(
411
+ model=model,
412
+ messages=messages,
413
+ temperature=temperature,
414
+ max_tokens=max_tokens,
415
+ n=1,
416
+ stop=None,
417
+ )
418
+ return response.choices[0].message.content.strip()
419
+ except openai.error.RateLimitError:
420
+ print(
421
+ " *** The OpenAI API rate limit has been exceeded. Waiting 10 seconds and trying again. ***"
422
+ )
423
+ time.sleep(10) # Wait 10 seconds and try again
424
+ except openai.error.Timeout:
425
+ print(
426
+ " *** OpenAI API timeout occurred. Waiting 10 seconds and trying again. ***"
427
+ )
428
+ time.sleep(10) # Wait 10 seconds and try again
429
+ except openai.error.APIError:
430
+ print(
431
+ " *** OpenAI API error occurred. Waiting 10 seconds and trying again. ***"
432
+ )
433
+ time.sleep(10) # Wait 10 seconds and try again
434
+ except openai.error.APIConnectionError:
435
+ print(
436
+ " *** OpenAI API connection error occurred. Check your network settings, proxy configuration, SSL certificates, or firewall rules. Waiting 10 seconds and trying again. ***"
437
+ )
438
+ time.sleep(10) # Wait 10 seconds and try again
439
+ except openai.error.InvalidRequestError:
440
+ print(
441
+ " *** OpenAI API invalid request. Check the documentation for the specific API method you are calling and make sure you are sending valid and complete parameters. Waiting 10 seconds and trying again. ***"
442
+ )
443
+ time.sleep(10) # Wait 10 seconds and try again
444
+ except openai.error.ServiceUnavailableError:
445
+ print(
446
+ " *** OpenAI API service unavailable. Waiting 10 seconds and trying again. ***"
447
+ )
448
+ time.sleep(10) # Wait 10 seconds and try again
449
+ else:
450
+ break
451
+
452
+
453
+ def task_creation_agent(
454
+ objective: str, result: Dict, task_description: str, task_list: List[str]
455
+ ):
456
+ prompt = f"""
457
+ You are to use the result from an execution agent to create new tasks with the following objective: {objective}.
458
+ The last completed task has the result: \n{result["data"]}
459
+ This result was based on this task description: {task_description}.\n"""
460
+
461
+ if task_list:
462
+ prompt += f"These are incomplete tasks: {', '.join(task_list)}\n"
463
+ prompt += "Based on the result, return a list of tasks to be completed in order to meet the objective. "
464
+ if task_list:
465
+ prompt += "These new tasks must not overlap with incomplete tasks. "
466
+
467
+ prompt += """
468
+ Return one task per line in your response. The result must be a numbered list in the format:
469
+
470
+ #. First task
471
+ #. Second task
472
+
473
+ The number of each entry must be followed by a period. If your list is empty, write "There are no tasks to add at this time."
474
+ Unless your list is empty, do not include any headers before your numbered list or follow your numbered list with any other output."""
475
+
476
+ print(f'\n*****TASK CREATION AGENT PROMPT****\n{prompt}\n')
477
+ response = openai_call(prompt, max_tokens=2000)
478
+ print(f'\n****TASK CREATION AGENT RESPONSE****\n{response}\n')
479
+ new_tasks = response.split('\n')
480
+ new_tasks_list = []
481
+ for task_string in new_tasks:
482
+ task_parts = task_string.strip().split(".", 1)
483
+ if len(task_parts) == 2:
484
+ task_id = ''.join(s for s in task_parts[0] if s.isnumeric())
485
+ task_name = re.sub(r'[^\w\s_]+', '', task_parts[1]).strip()
486
+ if task_name.strip() and task_id.isnumeric():
487
+ new_tasks_list.append(task_name)
488
+ # print('New task created: ' + task_name)
489
+
490
+ out = [{"task_name": task_name} for task_name in new_tasks_list]
491
+ return out
492
+
493
+
494
+ def prioritization_agent():
495
+ task_names = tasks_storage.get_task_names()
496
+ bullet_string = '\n'
497
+
498
+ prompt = f"""
499
+ You are tasked with prioritizing the following tasks: {bullet_string + bullet_string.join(task_names)}
500
+ Consider the ultimate objective of your team: {OBJECTIVE}.
501
+ Tasks should be sorted from highest to lowest priority, where higher-priority tasks are those that act as pre-requisites or are more essential for meeting the objective.
502
+ Do not remove any tasks. Return the ranked tasks as a numbered list in the format:
503
+
504
+ #. First task
505
+ #. Second task
506
+
507
+ The entries must be consecutively numbered, starting with 1. The number of each entry must be followed by a period.
508
+ Do not include any headers before your ranked list or follow your list with any other output."""
509
+
510
+ print(f'\n****TASK PRIORITIZATION AGENT PROMPT****\n{prompt}\n')
511
+ response = openai_call(prompt, max_tokens=2000)
512
+ print(f'\n****TASK PRIORITIZATION AGENT RESPONSE****\n{response}\n')
513
+ if not response:
514
+ print('Received empty response from priotritization agent. Keeping task list unchanged.')
515
+ return
516
+ new_tasks = response.split("\n") if "\n" in response else [response]
517
+ new_tasks_list = []
518
+ for task_string in new_tasks:
519
+ task_parts = task_string.strip().split(".", 1)
520
+ if len(task_parts) == 2:
521
+ task_id = ''.join(s for s in task_parts[0] if s.isnumeric())
522
+ task_name = re.sub(r'[^\w\s_]+', '', task_parts[1]).strip()
523
+ if task_name.strip():
524
+ new_tasks_list.append({"task_id": task_id, "task_name": task_name})
525
+
526
+ return new_tasks_list
527
+
528
+
529
+ # Execute a task based on the objective and five previous tasks
530
+ def execution_agent(objective: str, task: str) -> str:
531
+ """
532
+ Executes a task based on the given objective and previous context.
533
+
534
+ Args:
535
+ objective (str): The objective or goal for the AI to perform the task.
536
+ task (str): The task to be executed by the AI.
537
+
538
+ Returns:
539
+ str: The response generated by the AI for the given task.
540
+
541
+ """
542
+
543
+ context = context_agent(query=objective, top_results_num=5)
544
+ # print("\n****RELEVANT CONTEXT****\n")
545
+ # print(context)
546
+ # print('')
547
+ prompt = f'Perform one task based on the following objective: {objective}.\n'
548
+ if context:
549
+ prompt += 'Take into account these previously completed tasks:' + '\n'.join(context)
550
+ prompt += f'\nYour task: {task}\nResponse:'
551
+ return openai_call(prompt, max_tokens=2000)
552
+
553
+
554
+ # Get the top n completed tasks for the objective
555
+ def context_agent(query: str, top_results_num: int):
556
+ """
557
+ Retrieves context for a given query from an index of tasks.
558
+
559
+ Args:
560
+ query (str): The query or objective for retrieving context.
561
+ top_results_num (int): The number of top results to retrieve.
562
+
563
+ Returns:
564
+ list: A list of tasks as context for the given query, sorted by relevance.
565
+
566
+ """
567
+ results = results_storage.query(query=query, top_results_num=top_results_num)
568
+ # print("****RESULTS****")
569
+ # print(results)
570
+ return results
571
+
572
+
573
+ # Add the initial task if starting new objective
574
+ if not JOIN_EXISTING_OBJECTIVE:
575
+ initial_task = {
576
+ "task_id": tasks_storage.next_task_id(),
577
+ "task_name": INITIAL_TASK
578
+ }
579
+ tasks_storage.append(initial_task)
580
+
581
+
582
+ def main():
583
+ loop = True
584
+ while loop:
585
+ # As long as there are tasks in the storage...
586
+ if not tasks_storage.is_empty():
587
+ # Print the task list
588
+ print("\033[95m\033[1m" + "\n*****TASK LIST*****\n" + "\033[0m\033[0m")
589
+ for t in tasks_storage.get_task_names():
590
+ print(" • " + str(t))
591
+
592
+ # Step 1: Pull the first incomplete task
593
+ task = tasks_storage.popleft()
594
+ print("\033[92m\033[1m" + "\n*****NEXT TASK*****\n" + "\033[0m\033[0m")
595
+ print(str(task["task_name"]))
596
+
597
+ # Send to execution function to complete the task based on the context
598
+ result = execution_agent(OBJECTIVE, str(task["task_name"]))
599
+ print("\033[93m\033[1m" + "\n*****TASK RESULT*****\n" + "\033[0m\033[0m")
600
+ print(result)
601
+
602
+ # Step 2: Enrich result and store in the results storage
603
+ # This is where you should enrich the result if needed
604
+ enriched_result = {
605
+ "data": result
606
+ }
607
+ # extract the actual result from the dictionary
608
+ # since we don't do enrichment currently
609
+ # vector = enriched_result["data"]
610
+
611
+ result_id = f"result_{task['task_id']}"
612
+
613
+ #results_storage.add(task, result, result_id)
614
+
615
+ # Step 3: Create new tasks and re-prioritize task list
616
+ # only the main instance in cooperative mode does that
617
+ new_tasks = task_creation_agent(
618
+ OBJECTIVE,
619
+ enriched_result,
620
+ task["task_name"],
621
+ tasks_storage.get_task_names(),
622
+ )
623
+
624
+ print('Adding new tasks to task_storage')
625
+ for new_task in new_tasks:
626
+ new_task.update({"task_id": tasks_storage.next_task_id()})
627
+ print(str(new_task))
628
+ tasks_storage.append(new_task)
629
+
630
+ if not JOIN_EXISTING_OBJECTIVE:
631
+ prioritized_tasks = prioritization_agent()
632
+ if prioritized_tasks:
633
+ tasks_storage.replace(prioritized_tasks)
634
+
635
+ # Sleep a bit before checking the task list again
636
+ time.sleep(5)
637
+ else:
638
+ print('Done.')
639
+ loop = False
640
+
641
+
642
+ if __name__ == "__main__":
643
+ main()
babyagi/babyagi.py CHANGED
@@ -351,7 +351,7 @@ def openai_call(
351
  messages=[
352
  {
353
  "role": "user",
354
- "content": "これじゃだめなのか?"
355
  }
356
  ],
357
  temperature=1,
@@ -589,15 +589,18 @@ def main():
589
  for t in tasks_storage.get_task_names():
590
  print(" • " + str(t))
591
 
 
592
  # Step 1: Pull the first incomplete task
593
  task = tasks_storage.popleft()
594
  print("\033[92m\033[1m" + "\n*****NEXT TASK*****\n" + "\033[0m\033[0m")
595
  print(str(task["task_name"]))
596
 
 
597
  # Send to execution function to complete the task based on the context
598
  result = execution_agent(OBJECTIVE, str(task["task_name"]))
599
  print("\033[93m\033[1m" + "\n*****TASK RESULT*****\n" + "\033[0m\033[0m")
600
  print(result)
 
601
 
602
  # Step 2: Enrich result and store in the results storage
603
  # This is where you should enrich the result if needed
 
351
  messages=[
352
  {
353
  "role": "user",
354
+ "content": prompt
355
  }
356
  ],
357
  temperature=1,
 
589
  for t in tasks_storage.get_task_names():
590
  print(" • " + str(t))
591
 
592
+
593
  # Step 1: Pull the first incomplete task
594
  task = tasks_storage.popleft()
595
  print("\033[92m\033[1m" + "\n*****NEXT TASK*****\n" + "\033[0m\033[0m")
596
  print(str(task["task_name"]))
597
 
598
+
599
  # Send to execution function to complete the task based on the context
600
  result = execution_agent(OBJECTIVE, str(task["task_name"]))
601
  print("\033[93m\033[1m" + "\n*****TASK RESULT*****\n" + "\033[0m\033[0m")
602
  print(result)
603
+ return
604
 
605
  # Step 2: Enrich result and store in the results storage
606
  # This is where you should enrich the result if needed