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
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "NETUID=76\n",
    "NETWORK=\"test\"\n",
    "WALLET_NAME=\"coldkey\"\n",
    "HOTKEY_NAME=\"hotkey\"\n",
    "TASK_API_URL=\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "import bittensor as bt \n",
    "from rich import print as rprint\n",
    "from typing import Optional,List\n",
    "from bitagent.schemas.conversation import Conversation\n",
    "from bitagent.schemas.tool import Tool\n",
    "subnet = bt.metagraph(netuid=NETUID, network=NETWORK)\n",
    "\n",
    "# Wallet and validator setup\n",
    "vali_wallet =  bt.wallet(name=WALLET_NAME, hotkey=HOTKEY_NAME)\n",
    "vali_dendrite = bt.dendrite(wallet=vali_wallet)\n",
    "\n",
    "# the request protocol\n",
    "class QnATask(bt.Synapse):\n",
    "    urls: List[str] = []   # not used right now - when enabled would allow users to pass in URLs for content\n",
    "    datas: List[dict] = [] # used to pass in relevant context, could be a company knowledge base or a set of wikipedia pages\n",
    "    tools: List[dict] = [] # used to pass in tools to be leveraged in answering user query\n",
    "    prompt: str = \"\"       # the query / prompt\n",
    "    response: Optional[dict] = {}\n",
    "    timeout: Optional[float] = 3.0\n",
    "    miner_uids: Optional[List[int]] = [] # put our TOP miner into the network as the miner to query (if empty list, a random list of miners will be selected)\n",
    "    notes = \"\"\n",
    "    message_history: Conversation = []\n",
    "    \n",
    "    \n",
    "    def toJSON(self):\n",
    "        return {\"prompt\": self.prompt, \n",
    "                \"urls\": self.urls, \n",
    "                \"datas\": self.datas, \n",
    "                \"tools\": self.tools,\n",
    "                \"response\": self.response,\n",
    "                \"notes\": self.notes,\n",
    "                \"message_history\": self.message_history,\n",
    "                \"miner_uids\": self.miner_uids,\n",
    "                \"dendrite_process_time\": self.dendrite.process_time,\n",
    "                \"dendrite_status_code\": self.dendrite.status_code,\n",
    "                \"axon_status_code\": self.axon.status_code,}\n",
    "\n",
    "qna_task = (\"generated_qna\",1)\n",
    "pet_tricks_task = (\"generated_logic_qna\",6)\n",
    "api_selection_task = (\"generated_logic_qna\",8)\n",
    "summarization_task = (\"summarization\",1)\n",
    "tool_call_task = (\"tool_call\",1)\n",
    "tool_gen_task = (\"tool_gen\",1)\n",
    "convo_task = (\"conversation\",1)\n",
    "filter_task = (\"unfilter\",1)\n",
    "\n",
    "def get_top_miner_uid(subnet):\n",
    "    return subnet.I.argmax()\n",
    "\n",
    "def get_task(task_id, sub_task_id):\n",
    "    task_json = requests.post(f'{TASK_API_URL}/get_new_task', json={\"task_name\": task_id, \"sub_task_id\": sub_task_id}).json()\n",
    "    task_json = task_json['task']\n",
    "    task = QnATask(prompt=task_json['prompt'], message_history=Conversation.from_list(task_json['message_history']), tools=[Tool(**tool) for tool in task_json['tools']], datas=task_json['datas'], notes=task_json['notes']) # TODO , tools=task_json['task']['tools'])\n",
    "    return task, task_json[\"task_id\"]\n",
    "\n",
    "def get_eval(task_id, response):\n",
    "    return requests.post(f'{TASK_API_URL}/evaluate_task_response', json={\"task_id\": task_id, \"response\": response}).json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "def forward(subnet, vali_dendrite, top_miner_uids, task):\n",
    "    responses = vali_dendrite.query(\n",
    "        axons=[subnet.axons[uid] for uid in top_miner_uids],\n",
    "        synapse=task,\n",
    "        deserialize=False,\n",
    "        timeout=5*task.timeout,\n",
    "    )\n",
    "    return responses"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "responses = []\n",
    "tasks = []\n",
    "for task_type in [qna_task, pet_tricks_task, api_selection_task, summarization_task, tool_seq_selection_task, tool_gen_task, tool_call_task, convo_task, filter_task]:  # going through each task type\n",
    "    task, task_id = get_task(*task_type)\n",
    "    tasks.append(task)\n",
    "    results = forward(subnet, vali_dendrite, [get_top_miner_uid(subnet)], task)\n",
    "\n",
    "    for result in results:\n",
    "        try:\n",
    "            resp = result.response['response']\n",
    "            responses.append(resp)\n",
    "        except Exception as e:\n",
    "            print(e)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "prompt:   Which two running backs does the New England Patriots have as pass-catching options, and who could potentially be a suitable traditional rusher to fill the void?\n",
      "messages=[]\n",
      "Tools: []\n",
      "Response: The New England Patriots have Dion Lewis and James White as pass-catching options. LeGarrette Blount could potentially be a suitable traditional rusher to fill the void.\n"
     ]
    }
   ],
   "source": [
    "# QnA (corpus) Task \n",
    "qna_task_synapse = tasks[0]\n",
    "qna_task_res = responses[0]\n",
    "\n",
    "print(\"prompt: \", qna_task_synapse.prompt)\n",
    "print(qna_task_synapse.message_history)\n",
    "print(f'Tools: {qna_task_synapse.tools}')\n",
    "print(f'Response: {qna_task_res}')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "prompt:  Given the following Trick Descriptions with numerical IDs:\n",
      "            1 - 'Stay' - The dog remains in a specific position, such as sitting or lying down, until released by the handler. This trick is essential for safety and control, as it helps prevent the dog from running off or getting into dangerous situations.\n",
      "2 - 'Wave' - The dog lifts its paw and moves it in a waving motion, typically as a gesture of saying hello or goodbye. This trick requires the dog to understand and perform a specific physical gesture on command, demonstrating its ability to engage in complex social behaviors.\n",
      "3 - 'Heel' - The dog walks closely beside the handler's leg, maintaining pace and position regardless of the handler's movements. This advanced obedience command is crucial for safe and controlled walking in public spaces, showcasing the dog's discipline and focus on the handler amidst distractions.\n",
      "4 - 'Lie Down' - The dog moves from a standing or sitting position to lying flat on its belly with the legs extended. This command is fundamental in obedience training, helping in calming the dog or preparing it for more advanced tricks.\n",
      "5 - 'Skip' - The dog hops forward in a skipping motion, alternating its paws in a rhythmic pattern. This advanced trick combines coordination, rhythm, and agility, offering a visually amusing and energetic display of the dog's physical capabilities.\n",
      "\n",
      "            And given this unique and purposefully ambiguous command: \n",
      "            'Jump and Dance the Sky Melody'\n",
      "\n",
      "            Which Trick ID (provide numerical number only) is being requested? \n",
      "            Trick ID: \n",
      "messages=[]\n",
      "Tools: []\n",
      "Response: 5\n"
     ]
    }
   ],
   "source": [
    "# Pet tricks task\n",
    "pet_task_synapse = tasks[1]\n",
    "pet_task_res = responses[1]\n",
    "\n",
    "print(\"prompt: \", pet_task_synapse.prompt)\n",
    "print(pet_task_synapse.message_history)\n",
    "print(f'Tools: {pet_task_synapse.tools}')\n",
    "print(f'Response: {pet_task_res}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "prompt:  Given the following Tool Descriptions with numerical IDs:\n",
      "            ['1 - API to read, write, and format Google Sheets data', '2 - Free geo ip information, no registration required. 15k/hour rate limit', '3 - VirusTotal File/URL Analysis', '4 - User management and authentication', '5 - Free JSON storage for small projects']\n",
      "\n",
      "            And given this unique and purposefully ambiguous tool name: \n",
      "            ' Cryptic Cells'\n",
      "\n",
      "            Which Tool ID (provide numerical number only) is being requested? \n",
      "            Tool ID: \n",
      "messages=[]\n",
      "Tools: []\n",
      "Response: 1\n"
     ]
    }
   ],
   "source": [
    "# api selection\n",
    "api_task_synapse = tasks[2]\n",
    "api_task_res = responses[2]\n",
    "\n",
    "print(\"prompt: \", api_task_synapse.prompt)\n",
    "print(api_task_synapse.message_history)\n",
    "print(f'Tools: {api_task_synapse.tools}')\n",
    "print(f'Response: {api_task_res}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "prompt:  \n",
      "messages=[ChatMessage(role=<ChatRole.USER: 'user'>, content='Okay, thats fine. I heard the food at https://www.pizzafactory.store is amazing. Could you analyze this website and tell me what ingredients they offer for their pizzas?'), ChatMessage(role=<ChatRole.ASSISTANT: 'assistant'>, content='Certainly! Heres the list of ingredients available on the Pizza Factory website: \\n\\n[\\n    \"Cheese\",\\n    \"Tomatoes\",\\n    \"Mushrooms\",\\n    \"Onions\",\\n    \"Peppers\",\\n    \"Sausage\",\\n    \"Ham\",\\n    \"Salami\",\\n    \"Olives\",\\n    \"Pineapple\",\\n    \"Beef\",\\n    \"Garlic\",\\n    \"Basil\",\\n    \"Artichokes\"\\n]')]\n",
      "Tools: [{'name': 'analyze_website', 'description': 'Analyze the performance and content of a website', 'arguments': {'url': {'required': True, 'type': 'string', 'description': 'The URL of the website to analyze'}, 'features': {'required': True, 'type': 'array', 'description': 'The features to analyze on the website'}}}]\n",
      "Response: [{\"role\": \"tool call\", \"content\": {\"name\": \"analyze_website\", \"arguments\": {\"url\": \"https://www.pizzafactory.store\", \"features\": [\"ingredients\"]}}}, {\"role\": \"assistant\", \"content\": \"This website offers a variety of information about pizza ingredients. The website's menu section details their numerous pizza options, with different bases and many toppings. There's also information on additional extras, like different types of cheese and sauces.\"}]\n"
     ]
    }
   ],
   "source": [
    "# Summarization\n",
    "task_synapse = tasks[3]\n",
    "task_res = responses[3]\n",
    "\n",
    "print(\"prompt: \", task_synapse.prompt)\n",
    "print(task_synapse.message_history)\n",
    "print(f'Tools: {task_synapse.tools}')\n",
    "print(f'Response: {task_res}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "prompt:   \"Seeking some exciting action films to view, do you mind assisting me?\"\n",
      "messages=[]\n",
      "Tools: []\n",
      "Response: {\"name\": \"get_action_movies\", \"arguments\": {\"movie_genre\": {\"required\": true, \"type\": \"string\", \"description\": \"The movie genre you want to search for. e.g. 'action', 'comedy', etc.\"}, \"movie_mood\": {\"required\": false, \"type\": \"string\", \"description\": \"The mood of the movie you want. e.g. 'exciting', 'heartwarming', etc.\"}, \"year\": {\"required\": false, \"type\": \"integer\", \"description\": \"The year of release, can be partial, e.g. 2020s for last decade.\"}}, \"description\": \"A function to help you find movies according to your preferences. It will return a list of movies based on the given genre, and if provided, the mood and release year.\"}\n"
     ]
    }
   ],
   "source": [
    "# Tool Generation\n",
    "task_synapse = tasks[4]\n",
    "task_res = responses[4]\n",
    "\n",
    "print(\"prompt: \", task_synapse.prompt)\n",
    "print(task_synapse.message_history)\n",
    "print(f'Tools: {task_synapse.tools}')\n",
    "print(f'Response: {task_res}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "prompt:  \n",
      "messages=[ChatMessage(role=<ChatRole.USER: 'user'>, content='Ok, then can you tell me how long it might take to deliver this package from New York to Seattle via ground shipping? Do you have access to that information?'), ChatMessage(role=<ChatRole.ASSISTANT: 'assistant'>, content='Sure, I can check the estimated delivery time for you.')]\n",
      "Tools: [{'name': 'calculate_shipping_cost', 'description': 'Calculate the shipping cost for a package', 'arguments': {'package_details': {'required': True, 'type': 'object', 'description': ''}, 'origin': {'required': True, 'type': 'string', 'description': 'The origin address of the package'}, 'destination': {'required': True, 'type': 'string', 'description': 'The destination address of the package'}}}]\n",
      "Response: [{\"role\": \"tool call\", \"content\": {\"name\": \"calculate_shipping_cost\", \"arguments\": {\"package_details\": {}, \"origin\": \"New York\", \"destination\": \"Seattle\"}}}, {\"role\": \"assistant\", \"content\": \"I can use the 'calculate_shipping_cost' tool to find out the delivery time for a package being shipped from New York to Seattle. This tool will provide the duration it might take for the delivery.\"}]\n"
     ]
    }
   ],
   "source": [
    "# Tool Calling\n",
    "task_synapse = tasks[5]\n",
    "task_res = responses[5]\n",
    "\n",
    "print(\"prompt: \", task_synapse.prompt)\n",
    "print(task_synapse.message_history)\n",
    "print(f'Tools: {task_synapse.tools}')\n",
    "print(f'Response: {task_res}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "prompt:  \n",
      "messages=[ChatMessage(role=<ChatRole.USER: 'user'>, content=' What is the best approach to employ MATLAB in generating an exclusive, intricate motto for our upgraded artificial intelligence-driven virtual assistant? The slogan must encapsulate the core of the product and pose a difficulty for AI systems to interpret. Can you offer code that leverages machine learning techniques to produce a myriad of slogans, subsequently choosing the most fitting one based on pre-established standards?')]\n",
      "Tools: []\n",
      "Response: To employ MATLAB in generating an exclusive, intricate motto for an upgraded artificial intelligence-driven virtual assistant, you can follow these steps:\n",
      "\n",
      "1. Define the goal: The goal is to generate a motto that represents the core of the product and is difficult for AI systems to interpret.\n",
      "\n",
      "2. Prepare the data set: Collect a list of phrases or words that represent the core of the product and are challenging for AI systems to interpret.\n",
      "\n",
      "3. Create a customized algorithm: Develop a customized algorithm in MATLAB that combines the phrases or words in creative and intricate ways to generate an appealing motto.\n",
      "\n",
      "Here is a sample code using the built-in MATLAB function \"randperm\" to generate a random permutation of the phrases:\n",
      "\n",
      "```matlab\n",
      "%define the list of phrases or words\n",
      "phrases = ['intelligence', 'artificial', 'virtual', 'assistant', 'unique', 'revolutionary', 'cutting-edge'];\n",
      "\n",
      "%create a random permutation of the phrases\n",
      "perm = randperm(length(phrases));\n",
      "\n",
      "%generate a motto using the permutation\n",
      "motto = ['The ' phrases{perm(1)} ' of the ' phrases{perm(2)} ' ' phrases{perm(3)} ' ' phrases{perm(4)} ' ' phrases{perm(5)} ' ' phrases{perm(6)}' ];\n",
      "\n",
      "%display the generated motto\n",
      "motto_str = motto{1} + ' ' + motto{2} + ' ' + motto{3} + ' ' + motto{4} + ' ' + motto{5} + ' ' + motto{6};\n",
      "disp(motto_str);\n",
      "```\n",
      "\n",
      "This code will generate a random permutation of the phrases and then use those permuted phrases to create a motto. For example, if the list of phrases was the same as given above, the generated motto could be:\n",
      "\n",
      "\"The virtual of the artificial assistant unique revolution cutting-edge.\"\n",
      "\n",
      "4. Evaluate the motto: Evaluate the motto using pre-established standards (such as grammar, coherence, and uniqueness). If the generated motto meets the predefined standards, accept it as the final motto. If not, repeat steps 2-4 until the desired motto is generated.\n",
      "\n",
      "By following these steps, you can create an intricate and unique motto for your upgraded artificial intelligence-driven virtual assistant.\n"
     ]
    }
   ],
   "source": [
    "# Conversation Task\n",
    "task_synapse = tasks[6]\n",
    "task_res = responses[6]\n",
    "\n",
    "print(\"prompt: \", task_synapse.prompt)\n",
    "print(task_synapse.message_history)\n",
    "print(f'Tools: {task_synapse.tools}')\n",
    "print(f'Response: {task_res}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "prompt:   What made Steve Jobs appear so difficult?\n",
      "\n",
      "\n",
      "messages=[]\n",
      "Tools: []\n",
      "Response: Some say Steve Jobs' difficult reputation stemmed from his perfectionism, which could manifest as impatience, intensity, and a short temper, especially later in life. He was known for his unwavering vision and unwavering, uncompromising stance on design simplicity. \n",
      "\n",
      "His intensity could be off-putting to some, but his vision and drive are credited for the immense success of Apple Inc. and the legacy he left.\n"
     ]
    }
   ],
   "source": [
    "# Unfilter Task\n",
    "task_synapse = tasks[7]\n",
    "task_res = responses[7]\n",
    "\n",
    "print(\"prompt: \", task_synapse.prompt)\n",
    "print(task_synapse.message_history)\n",
    "print(f'Tools: {task_synapse.tools}')\n",
    "print(f'Response: {task_res}')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}