Format Python code with psf/black push

github-actions 2 years ago
parent dba1f934a5
commit 2a57901559

@ -30,7 +30,13 @@ class IndexService(discord.Cog, name="IndexService"):
"""Command handler to rename a user index""" """Command handler to rename a user index"""
if not new_name: if not new_name:
await ctx.respond(await EmbedStatics.get_index_rename_failure_embed(user_index.split("/")[-1], "None", "Please provide a new name for this index")) await ctx.respond(
await EmbedStatics.get_index_rename_failure_embed(
user_index.split("/")[-1],
"None",
"Please provide a new name for this index",
)
)
return return
if await self.index_handler.rename_index( if await self.index_handler.rename_index(
@ -38,15 +44,31 @@ class IndexService(discord.Cog, name="IndexService"):
f"indexes/{ctx.user.id}/{user_index}", f"indexes/{ctx.user.id}/{user_index}",
f"indexes/{ctx.user.id}/{new_name}", f"indexes/{ctx.user.id}/{new_name}",
): ):
await ctx.respond(embed=EmbedStatics.get_index_rename_success_embed(user_index.split("/")[-1], new_name)) await ctx.respond(
embed=EmbedStatics.get_index_rename_success_embed(
user_index.split("/")[-1], new_name
)
)
else: else:
await ctx.respond(embed=EmbedStatics.get_index_rename_failure_embed(user_index.split("/")[-1], new_name, "Please check the server console for more details.")) await ctx.respond(
embed=EmbedStatics.get_index_rename_failure_embed(
user_index.split("/")[-1],
new_name,
"Please check the server console for more details.",
)
)
async def rename_server_index_command(self, ctx, server_index, new_name): async def rename_server_index_command(self, ctx, server_index, new_name):
"""Command handler to rename a user index""" """Command handler to rename a user index"""
if not new_name: if not new_name:
await ctx.respond(await EmbedStatics.get_index_rename_failure_embed(server_index.split("/")[-1], "None", "Please provide a new name for this index")) await ctx.respond(
await EmbedStatics.get_index_rename_failure_embed(
server_index.split("/")[-1],
"None",
"Please provide a new name for this index",
)
)
return return
if await self.index_handler.rename_index( if await self.index_handler.rename_index(
@ -54,13 +76,29 @@ class IndexService(discord.Cog, name="IndexService"):
f"indexes/{ctx.guild.id}/{server_index}", f"indexes/{ctx.guild.id}/{server_index}",
f"indexes/{ctx.guild.id}/{new_name}", f"indexes/{ctx.guild.id}/{new_name}",
): ):
await ctx.respond(embed=EmbedStatics.get_index_rename_success_embed(server_index.split("/")[-1], new_name)) await ctx.respond(
embed=EmbedStatics.get_index_rename_success_embed(
server_index.split("/")[-1], new_name
)
)
else: else:
await ctx.respond(embed=EmbedStatics.get_index_rename_failure_embed(server_index.split("/")[-1], new_name, "Please check the server console for more details.")) await ctx.respond(
embed=EmbedStatics.get_index_rename_failure_embed(
server_index.split("/")[-1],
new_name,
"Please check the server console for more details.",
)
)
async def rename_search_index_command(self, ctx, search_index, new_name): async def rename_search_index_command(self, ctx, search_index, new_name):
if not new_name: if not new_name:
await ctx.respond(await EmbedStatics.get_index_rename_failure_embed(search_index.split("/")[-1], "None", "Please provide a new name for this index")) await ctx.respond(
await EmbedStatics.get_index_rename_failure_embed(
search_index.split("/")[-1],
"None",
"Please provide a new name for this index",
)
)
return return
if await self.index_handler.rename_index( if await self.index_handler.rename_index(
@ -68,9 +106,19 @@ class IndexService(discord.Cog, name="IndexService"):
f"indexes/{ctx.user.id}_search/{search_index}", f"indexes/{ctx.user.id}_search/{search_index}",
f"indexes/{ctx.user.id}_search/{new_name}", f"indexes/{ctx.user.id}_search/{new_name}",
): ):
await ctx.respond(embed=EmbedStatics.get_index_rename_success_embed(search_index.split("/")[-1], new_name)) await ctx.respond(
embed=EmbedStatics.get_index_rename_success_embed(
search_index.split("/")[-1], new_name
)
)
else: else:
await ctx.respond(embed=EmbedStatics.get_index_rename_failure_embed(search_index.split("/")[-1], new_name, "Please check the server console for more details.")) await ctx.respond(
embed=EmbedStatics.get_index_rename_failure_embed(
search_index.split("/")[-1],
new_name,
"Please check the server console for more details.",
)
)
async def set_index_command( async def set_index_command(
self, ctx, file: discord.Attachment = None, link: str = None self, ctx, file: discord.Attachment = None, link: str = None

@ -115,7 +115,11 @@ class SearchService(discord.Cog, name="SearchService"):
not EnvService.get_google_search_api_key() not EnvService.get_google_search_api_key()
or not EnvService.get_google_search_engine_id() or not EnvService.get_google_search_engine_id()
): ):
await ctx.respond(embed=EmbedStatics.get_search_failure_embed(str("The search service is not enabled on this server.")),) await ctx.respond(
embed=EmbedStatics.get_search_failure_embed(
str("The search service is not enabled on this server.")
),
)
return return
try: try:
@ -227,7 +231,9 @@ class RedoButton(discord.ui.Button["SearchView"]):
async def callback(self, interaction: discord.Interaction): async def callback(self, interaction: discord.Interaction):
"""Redo the search""" """Redo the search"""
await interaction.response.send_message( await interaction.response.send_message(
embed=EmbedStatics.get_search_redo_progress_embed(), ephemeral=True, delete_after=15 embed=EmbedStatics.get_search_redo_progress_embed(),
ephemeral=True,
delete_after=15,
) )
await self.search_cog.search_command( await self.search_cog.search_command(
self.search_cog.redo_users[self.ctx.user.id].ctx, self.search_cog.redo_users[self.ctx.user.id].ctx,

@ -90,9 +90,7 @@ class EmbedStatics:
color=discord.Color.green(), color=discord.Color.green(),
) )
# thumbnail of https://i.imgur.com/7JF0oGD.png # thumbnail of https://i.imgur.com/7JF0oGD.png
embed.set_thumbnail( embed.set_thumbnail(url="https://i.imgur.com/7JF0oGD.png")
url="https://i.imgur.com/7JF0oGD.png"
)
return embed return embed
@staticmethod @staticmethod
@ -103,9 +101,7 @@ class EmbedStatics:
color=discord.Color.red(), color=discord.Color.red(),
) )
# thumbnail of https://i.imgur.com/VLJ32x7.png # thumbnail of https://i.imgur.com/VLJ32x7.png
embed.set_thumbnail( embed.set_thumbnail(url="https://i.imgur.com/VLJ32x7.png")
url="https://i.imgur.com/VLJ32x7.png"
)
return embed return embed
@staticmethod @staticmethod
@ -115,9 +111,7 @@ class EmbedStatics:
color=discord.Color.green(), color=discord.Color.green(),
) )
# thumbnail of https://i.imgur.com/7JF0oGD.png # thumbnail of https://i.imgur.com/7JF0oGD.png
embed.set_thumbnail( embed.set_thumbnail(url="https://i.imgur.com/7JF0oGD.png")
url="https://i.imgur.com/7JF0oGD.png"
)
return embed return embed
@staticmethod @staticmethod
@ -128,9 +122,7 @@ class EmbedStatics:
color=discord.Color.red(), color=discord.Color.red(),
) )
# thumbnail of https://i.imgur.com/VLJ32x7.png # thumbnail of https://i.imgur.com/VLJ32x7.png
embed.set_thumbnail( embed.set_thumbnail(url="https://i.imgur.com/VLJ32x7.png")
url="https://i.imgur.com/VLJ32x7.png"
)
return embed return embed
@staticmethod @staticmethod
@ -141,9 +133,7 @@ class EmbedStatics:
color=discord.Color.red(), color=discord.Color.red(),
) )
# thumbnail of https://i.imgur.com/VLJ32x7.png # thumbnail of https://i.imgur.com/VLJ32x7.png
embed.set_thumbnail( embed.set_thumbnail(url="https://i.imgur.com/VLJ32x7.png")
url="https://i.imgur.com/VLJ32x7.png"
)
return embed return embed
@staticmethod @staticmethod
@ -153,9 +143,7 @@ class EmbedStatics:
color=discord.Color.green(), color=discord.Color.green(),
) )
# thumbnail of https://i.imgur.com/7JF0oGD.png # thumbnail of https://i.imgur.com/7JF0oGD.png
embed.set_thumbnail( embed.set_thumbnail(url="https://i.imgur.com/7JF0oGD.png")
url="https://i.imgur.com/7JF0oGD.png"
)
return embed return embed
@staticmethod @staticmethod
@ -166,9 +154,7 @@ class EmbedStatics:
color=discord.Color.red(), color=discord.Color.red(),
) )
# thumbnail of https://i.imgur.com/VLJ32x7.png # thumbnail of https://i.imgur.com/VLJ32x7.png
embed.set_thumbnail( embed.set_thumbnail(url="https://i.imgur.com/VLJ32x7.png")
url="https://i.imgur.com/VLJ32x7.png"
)
return embed return embed
@staticmethod @staticmethod
@ -179,9 +165,7 @@ class EmbedStatics:
color=discord.Color.blurple(), color=discord.Color.blurple(),
) )
# thumbnail of https://i.imgur.com/VLJ32x7.png # thumbnail of https://i.imgur.com/VLJ32x7.png
embed.set_thumbnail( embed.set_thumbnail(url="https://i.imgur.com/txHhNzL.png")
url="https://i.imgur.com/txHhNzL.png"
)
return embed return embed
@staticmethod @staticmethod
@ -192,9 +176,7 @@ class EmbedStatics:
color=discord.Color.green(), color=discord.Color.green(),
) )
# thumbnail of https://i.imgur.com/7JF0oGD.png # thumbnail of https://i.imgur.com/7JF0oGD.png
embed.set_thumbnail( embed.set_thumbnail(url="https://i.imgur.com/7JF0oGD.png")
url="https://i.imgur.com/7JF0oGD.png"
)
return embed return embed
@staticmethod @staticmethod
@ -205,9 +187,7 @@ class EmbedStatics:
color=discord.Color.red(), color=discord.Color.red(),
) )
# thumbnail of https://i.imgur.com/VLJ32x7.png # thumbnail of https://i.imgur.com/VLJ32x7.png
embed.set_thumbnail( embed.set_thumbnail(url="https://i.imgur.com/VLJ32x7.png")
url="https://i.imgur.com/VLJ32x7.png"
)
return embed return embed
@staticmethod @staticmethod
@ -227,9 +207,7 @@ class EmbedStatics:
color=discord.Color.red(), color=discord.Color.red(),
) )
# thumbnail of https://i.imgur.com/VLJ32x7.png # thumbnail of https://i.imgur.com/VLJ32x7.png
embed.set_thumbnail( embed.set_thumbnail(url="https://i.imgur.com/VLJ32x7.png")
url="https://i.imgur.com/VLJ32x7.png"
)
return embed return embed
@staticmethod @staticmethod
@ -240,7 +218,5 @@ class EmbedStatics:
color=discord.Color.blurple(), color=discord.Color.blurple(),
) )
# thumbnail of https://i.imgur.com/VLJ32x7.png # thumbnail of https://i.imgur.com/VLJ32x7.png
embed.set_thumbnail( embed.set_thumbnail(url="https://i.imgur.com/txHhNzL.png")
url="https://i.imgur.com/txHhNzL.png"
)
return embed return embed

@ -360,7 +360,9 @@ class Index_handler:
pass # No suffix change pass # No suffix change
else: else:
await ctx.respond( await ctx.respond(
embed=EmbedStatics.get_index_set_failure_embed("Only accepts text, pdf, images, spreadheets, powerpoint, and audio/video files.") embed=EmbedStatics.get_index_set_failure_embed(
"Only accepts text, pdf, images, spreadheets, powerpoint, and audio/video files."
)
) )
return return
async with aiofiles.tempfile.TemporaryDirectory() as temp_path: async with aiofiles.tempfile.TemporaryDirectory() as temp_path:
@ -402,12 +404,20 @@ class Index_handler:
if response.status == 200: if response.status == 200:
content_type = response.headers.get("content-type") content_type = response.headers.get("content-type")
else: else:
await ctx.respond(embed=EmbedStatics.get_index_set_failure_embed("Invalid URL or could not connect to the provided URL.")) await ctx.respond(
embed=EmbedStatics.get_index_set_failure_embed(
"Invalid URL or could not connect to the provided URL."
)
)
return return
except Exception as e: except Exception as e:
traceback.print_exc() traceback.print_exc()
await ctx.respond(embed=EmbedStatics.get_index_set_failure_embed( await ctx.respond(
"Invalid URL or could not connect to the provided URL. "+str(e))) embed=EmbedStatics.get_index_set_failure_embed(
"Invalid URL or could not connect to the provided URL. "
+ str(e)
)
)
return return
# Check if the link contains youtube in it # Check if the link contains youtube in it
@ -724,7 +734,9 @@ class Index_handler:
except Exception: except Exception:
traceback.print_exc() traceback.print_exc()
await ctx.respond( await ctx.respond(
embed=EmbedStatics.get_index_query_failure_embed("Failed to send query. You may not have an index set, load an index with /index load"), embed=EmbedStatics.get_index_query_failure_embed(
"Failed to send query. You may not have an index set, load an index with /index load"
),
delete_after=10, delete_after=10,
) )
@ -813,7 +825,11 @@ class Index_handler:
os.environ["OPENAI_API_KEY"] = user_api_key os.environ["OPENAI_API_KEY"] = user_api_key
if not self.index_storage[ctx.user.id].has_indexes(ctx.user.id): if not self.index_storage[ctx.user.id].has_indexes(ctx.user.id):
await ctx.respond(embed=EmbedStatics.get_index_compose_failure_embed("You must have at least one index to compose.")) await ctx.respond(
embed=EmbedStatics.get_index_compose_failure_embed(
"You must have at least one index to compose."
)
)
return return
await ctx.respond( await ctx.respond(
@ -925,7 +941,10 @@ class ComposeModal(discord.ui.View):
if len(indexes) < 1: if len(indexes) < 1:
await interaction.response.send_message( await interaction.response.send_message(
embed=EmbedStatics.get_index_compose_failure_embed("You must select at least 1 index"), ephemeral=True embed=EmbedStatics.get_index_compose_failure_embed(
"You must select at least 1 index"
),
ephemeral=True,
) )
else: else:
composing_message = await interaction.response.send_message( composing_message = await interaction.response.send_message(
@ -950,14 +969,18 @@ class ComposeModal(discord.ui.View):
return False return False
except Exception as e: except Exception as e:
await interaction.followup.send( await interaction.followup.send(
embed=EmbedStatics.get_index_compose_failure_embed("An error occurred while composing the indexes: " + str(e)), embed=EmbedStatics.get_index_compose_failure_embed(
"An error occurred while composing the indexes: " + str(e)
),
ephemeral=True, ephemeral=True,
delete_after=180, delete_after=180,
) )
return False return False
await interaction.followup.send( await interaction.followup.send(
embed=EmbedStatics.get_index_compose_success_embed(), ephemeral=True, delete_after=180 embed=EmbedStatics.get_index_compose_success_embed(),
ephemeral=True,
delete_after=180,
) )
# Try to direct message the user that their composed index is ready # Try to direct message the user that their composed index is ready

@ -22,7 +22,7 @@ from gpt_index import (
SimpleDirectoryReader, SimpleDirectoryReader,
GPTTreeIndex, GPTTreeIndex,
MockLLMPredictor, MockLLMPredictor,
MockEmbedding MockEmbedding,
) )
from gpt_index.indices.knowledge_graph import GPTKnowledgeGraphIndex from gpt_index.indices.knowledge_graph import GPTKnowledgeGraphIndex
from gpt_index.prompts.prompt_type import PromptType from gpt_index.prompts.prompt_type import PromptType
@ -89,8 +89,7 @@ class Search:
def build_search_links_retrieved_embed(self, refined_query): def build_search_links_retrieved_embed(self, refined_query):
embed = discord.Embed( embed = discord.Embed(
title="Searching the web...", title="Searching the web...",
description="Refined query:\n" description="Refined query:\n" + f"`{refined_query}`"
+ f"`{refined_query}`"
"\nRetrieving webpages...", "\nRetrieving webpages...",
color=discord.Color.blurple(), color=discord.Color.blurple(),
) )
@ -101,9 +100,7 @@ class Search:
def build_search_webpages_retrieved_embed(self, refined_query): def build_search_webpages_retrieved_embed(self, refined_query):
embed = discord.Embed( embed = discord.Embed(
title="Searching the web...", title="Searching the web...",
description="Refined query:\n" description="Refined query:\n" + f"`{refined_query}`" "\nIndexing...",
+ f"`{refined_query}`"
"\nIndexing...",
color=discord.Color.blurple(), color=discord.Color.blurple(),
) )
embed.set_thumbnail(url="https://i.imgur.com/txHhNzL.png") embed.set_thumbnail(url="https://i.imgur.com/txHhNzL.png")
@ -113,8 +110,7 @@ class Search:
def build_search_indexed_embed(self, refined_query): def build_search_indexed_embed(self, refined_query):
embed = discord.Embed( embed = discord.Embed(
title="Searching the web...", title="Searching the web...",
description="Refined query:\n" description="Refined query:\n" + f"`{refined_query}`"
+ f"`{refined_query}`"
"\nThinking about your question...", "\nThinking about your question...",
color=discord.Color.blurple(), color=discord.Color.blurple(),
) )
@ -125,8 +121,7 @@ class Search:
def build_search_final_embed(self, refined_query, price): def build_search_final_embed(self, refined_query, price):
embed = discord.Embed( embed = discord.Embed(
title="Searching the web...", title="Searching the web...",
description="Refined query:\n" description="Refined query:\n" + f"`{refined_query}`"
+ f"`{refined_query}`"
"\nDone!\n||The total price was $" + price + "||", "\nDone!\n||The total price was $" + price + "||",
color=discord.Color.blurple(), color=discord.Color.blurple(),
) )
@ -222,10 +217,9 @@ class Search:
max_tokens=50, max_tokens=50,
temperature=0.25, temperature=0.25,
presence_penalty=0.65, presence_penalty=0.65,
model_name="text-davinci-003" model_name="text-davinci-003",
) )
# Refine a query to send to google custom search API # Refine a query to send to google custom search API
prompt = f"You are to be given a search query for google. Change the query such that putting it into the Google Custom Search API will return the most relevant websites to assist in answering the original query. If the original query is inferring knowledge about the current day, insert the current day into the refined prompt. If the original query is inferring knowledge about the current month, insert the current month and year into the refined prompt. If the original query is inferring knowledge about the current year, insert the current year into the refined prompt. Generally, if the original query is inferring knowledge about something that happened recently, insert the current month into the refined query. Avoid inserting a day, month, or year for queries that purely ask about facts and about things that don't have much time-relevance. The current date is {str(datetime.now().date())}. Do not insert the current date if not neccessary. Respond with only the refined query for the original query. Dont use punctuation or quotation marks.\n\nExamples:\n---\nOriginal Query: Who is Harald Baldr?\nRefined Query: Harald Baldr biography\n---\nOriginal Query: What happened today with the Ohio train derailment?\nRefined Query: Ohio train derailment details {str(datetime.now().date())}\n---\nOriginal Query: Is copper in drinking water bad for you?\nRefined Query: copper in drinking water adverse effects\n---\nOriginal Query: What's the current time in Mississauga?\nRefined Query: current time Mississauga\nNow, refine the user input query.\nOriginal Query: {query}\nRefined Query:" prompt = f"You are to be given a search query for google. Change the query such that putting it into the Google Custom Search API will return the most relevant websites to assist in answering the original query. If the original query is inferring knowledge about the current day, insert the current day into the refined prompt. If the original query is inferring knowledge about the current month, insert the current month and year into the refined prompt. If the original query is inferring knowledge about the current year, insert the current year into the refined prompt. Generally, if the original query is inferring knowledge about something that happened recently, insert the current month into the refined query. Avoid inserting a day, month, or year for queries that purely ask about facts and about things that don't have much time-relevance. The current date is {str(datetime.now().date())}. Do not insert the current date if not neccessary. Respond with only the refined query for the original query. Dont use punctuation or quotation marks.\n\nExamples:\n---\nOriginal Query: Who is Harald Baldr?\nRefined Query: Harald Baldr biography\n---\nOriginal Query: What happened today with the Ohio train derailment?\nRefined Query: Ohio train derailment details {str(datetime.now().date())}\n---\nOriginal Query: Is copper in drinking water bad for you?\nRefined Query: copper in drinking water adverse effects\n---\nOriginal Query: What's the current time in Mississauga?\nRefined Query: current time Mississauga\nNow, refine the user input query.\nOriginal Query: {query}\nRefined Query:"
query_refined = await llm_predictor_presearch.agenerate( query_refined = await llm_predictor_presearch.agenerate(
@ -233,7 +227,9 @@ class Search:
) )
query_refined_text = query_refined.generations[0][0].text query_refined_text = query_refined.generations[0][0].text
price += await self.usage_service.get_price(query_refined.llm_output.get("token_usage").get("total_tokens")) price += await self.usage_service.get_price(
query_refined.llm_output.get("token_usage").get("total_tokens")
)
except Exception as e: except Exception as e:
traceback.print_exc() traceback.print_exc()
@ -470,11 +466,14 @@ class Search:
await self.usage_service.update_usage( await self.usage_service.update_usage(
embedding_model.last_token_usage, embeddings=True embedding_model.last_token_usage, embeddings=True
) )
price += await self.usage_service.get_price(llm_predictor.last_token_usage) + await self.usage_service.get_price( price += await self.usage_service.get_price(
embedding_model.last_token_usage, True llm_predictor.last_token_usage
) ) + await self.usage_service.get_price(embedding_model.last_token_usage, True)
if ctx: if ctx:
await self.try_edit(in_progress_message, self.build_search_final_embed(query_refined_text, str(price))) await self.try_edit(
in_progress_message,
self.build_search_final_embed(query_refined_text, str(price)),
)
return response, query_refined_text return response, query_refined_text

@ -411,7 +411,9 @@ class TextService:
) )
elif from_edit_command: elif from_edit_command:
response_message = await ctx.respond( response_message = await ctx.respond(
embed=EmbedStatics.get_edit_command_output_embed(response_text), embed=EmbedStatics.get_edit_command_output_embed(
response_text
),
view=ConversationView( view=ConversationView(
ctx, ctx,
converser_cog, converser_cog,
@ -473,7 +475,9 @@ class TextService:
await response_message.edit(content=response_text) await response_message.edit(content=response_text)
else: else:
await response_message.edit( await response_message.edit(
embed=EmbedStatics.get_edit_command_output_embed(response_text) embed=EmbedStatics.get_edit_command_output_embed(
response_text
)
) )
await converser_cog.send_debug_message( await converser_cog.send_debug_message(

Loading…
Cancel
Save