Skip to content

Commit

Permalink
add jinja templates for all current tasks
Browse files Browse the repository at this point in the history
  • Loading branch information
andreaskoepf committed Dec 21, 2022
1 parent d20828e commit df62ee0
Show file tree
Hide file tree
Showing 9 changed files with 78 additions and 72 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
exclude: "build|stubs"
exclude: "build|stubs|bot/templates/.*msg"

default_language_version:
python: python3
Expand Down
91 changes: 26 additions & 65 deletions bot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ def __init__(self, template_dir="./templates"):

def render(self, template_name, **kwargs):
template = self.env.get_template(template_name)
return template.render(kwargs)
txt = template.render(kwargs)
logger.info(txt)
return txt


class OpenAssistantBot:
Expand Down Expand Up @@ -86,19 +88,18 @@ def __init__(
self.reply_handlers = {} # handlers by msg_id
self.tree = app_commands.CommandTree(self.client, fallback_to_global=True)

self.auto_archive_minutes = 60 # ToDo: add to bot config

@client.event
async def on_ready():
self.bot_channel = self.get_text_channel_by_name(bot_channel_name)
client.loop.create_task(self.background_timer(), name="OpenAssistantBot.background_timer()")
logger.info(f"{client.user} is now running!")

await self.delete_all_old_bot_messages()
if self.debug:
await self.post_boot_message()
await self.post_welcome_message()

client.loop.create_task(self.background_timer(), name="OpenAssistantBot.background_timer()")

@client.event
async def on_message(message: discord.Message):
# ignore own messages
Expand Down Expand Up @@ -131,11 +132,14 @@ async def post(self, content: str, view: discord.ui.View = None) -> discord.Mess
self.ensure_bot_channel()
return await self.bot_channel.send(content=content)

async def post_template(self, name: str, view: discord.ui.View = None, **kwargs: Any) -> discord.Message:
async def post_template_view(self, name: str, *, view: discord.ui.View, **kwargs: Any) -> discord.Message:
logger.info(f"rendering {name}")
text = self.templates.render(name, **kwargs)
return await self.post(text, view)

async def post_template(self, name: str, **kwargs: Any) -> discord.Message:
return await self.post_template_view(name=name, view=None, **kwargs)

async def post_boot_message(self) -> discord.Message:
return await self.post_template(
"boot.msg", bot_name=BOT_NAME, version=__version__, git_hash=get_git_head_hash(), debug=self.debug
Expand All @@ -162,9 +166,7 @@ async def print_separtor(self, title: str) -> discord.Message:
async def generate_summarize_story(self, task: protocol_schema.SummarizeStoryTask):
text = f"Summarize to the following story:\n{task.story}"
msg: discord.Message = await self.bot_channel.send(text)
await self.bot_channel.create_thread(
message=discord.Object(msg.id), name="Summaries", auto_archive_duration=self.auto_archive_minutes
)
await self.bot_channel.create_thread(message=discord.Object(msg.id), name="Summaries")

async def on_reply(message: discord.Message):
logger.info("on_summarize_story_reply", message)
Expand All @@ -180,24 +182,20 @@ async def rating_response_handler(score, interaction: discord.Interaction):
await interaction.response.send_message(f"got your feedback: {score}")

view = generate_rating_view(task.scale.min, task.scale.max, rating_response_handler)
msg: discord.Message = await self.post_template("rate_summary", task=task, view=view)
msg = await self.post_template_view("task_rate_summary.msg", view=view, task=task)

async def on_reply(message: discord.Message):
logger.info("on_summary_reply", message)
await message.add_reaction("")
await message.add_reaction("")

self.reply_handlers[msg.id] = on_reply

return msg

async def generate_initial_prompt(self, task: protocol_schema.InitialPromptTask):
text = "Please provide an initial prompt to the assistant."
if task.hint:
text += f"\nHint: {task.hint}"
msg: discord.Message = await self.bot_channel.send(text)
await self.bot_channel.create_thread(
message=discord.Object(msg.id), name="Prompts", auto_archive_duration=self.auto_archive_minutes
)
msg = await self.post_template("task_initial_prompt.msg", task=task)

await self.bot_channel.create_thread(message=discord.Object(msg.id), name="Prompts")

async def on_reply(message: discord.Message):
logger.info("on_initial_prompt_reply", message)
Expand All @@ -215,17 +213,8 @@ def _render_message(self, message: protocol_schema.ConversationMessage) -> str:
return f":person_red_hair: User:\n**{message.text}**"

async def generate_user_reply(self, task: protocol_schema.UserReplyTask):
s = ["Please provide a reply to the assistant.", "Here is the conversation so far:\n"]
for message in task.conversation.messages:
s.append(self._render_message(message))
s.append("")
if task.hint:
s.append(f"Hint: {task.hint}")
text = "\n".join(s)
msg: discord.Message = await self.bot_channel.send(text)
await self.bot_channel.create_thread(
message=discord.Object(msg.id), name="User responses", auto_archive_duration=self.auto_archive_minutes
)
msg = await self.post_template("task_user_reply.msg", task=task)
await self.bot_channel.create_thread(message=discord.Object(msg.id), name="User responses")

async def on_reply(message: discord.Message):
logger.info("on_user_reply_reply", message)
Expand All @@ -236,16 +225,8 @@ async def on_reply(message: discord.Message):
return msg

async def generate_assistant_reply(self, task: protocol_schema.AssistantReplyTask):
s = ["Act as the assistant and reply to the user.", "Here is the conversation so far\n:"]
for message in task.conversation.messages:
s.append(self._render_message(message))
s.append("")
s.append(":robot: Assistant: { human, pls help me! ... }")
text = "\n".join(s)
msg: discord.Message = await self.bot_channel.send(text)
await self.bot_channel.create_thread(
message=discord.Object(msg.id), name="Agent responses", auto_archive_duration=self.auto_archive_minutes
)
msg = await self.post_template("task_assistant_reply.msg", task=task)
await self.bot_channel.create_thread(message=discord.Object(msg.id), name="Agent responses")

async def on_reply(message: discord.Message):
logger.info("on_assistant_reply_reply", message)
Expand All @@ -256,16 +237,8 @@ async def on_reply(message: discord.Message):
return msg

async def generate_rank_initial_prompts(self, task: protocol_schema.RankInitialPromptsTask):
s = ["Rank the following prompts:"]
for idx, prompt in enumerate(task.prompts, start=1):
s.append(f"{idx}: {prompt}")
s.append("")
s.append(':scroll: Reply with the numbers of best to worst prompts separated by commas (example: "4,1,3,2").')
text = "\n".join(s)
msg: discord.Message = await self.bot_channel.send(text)
await self.bot_channel.create_thread(
message=discord.Object(msg.id), name="User responses", auto_archive_duration=self.auto_archive_minutes
)
msg = await self.post_template("task_rank_initial_prompts.msg", task=task)
await self.bot_channel.create_thread(message=discord.Object(msg.id), name="User responses")

async def on_reply(message: discord.Message):
logger.info("on_rank_initial_prompts_reply", message)
Expand All @@ -276,20 +249,8 @@ async def on_reply(message: discord.Message):
return msg

async def generate_rank_conversation(self, task: protocol_schema.RankConversationRepliesTask):
s = ["Here is the conversation so far:"]
for message in task.conversation.messages:
s.append(self._render_message(message))
s.append("")
s.append("Rank the following replies:")
for idx, reply in enumerate(task.replies, start=1):
s.append(f"{idx}: {reply}")
s.append("")
s.append(':scroll: Reply with the numbers of best to worst prompts separated by commas (example: "4,1,3,2").')
text = "\n".join(s)
msg: discord.Message = await self.bot_channel.send(text)
await self.bot_channel.create_thread(
message=discord.Object(msg.id), name="User responses", auto_archive_duration=self.auto_archive_minutes
)
msg = await self.post_template("task_rank_conversation_replies.msg", task=task)
await self.bot_channel.create_thread(message=discord.Object(msg.id), name="User responses")

async def on_reply(message: discord.Message):
logger.info("on_rank_conversation_reply", message)
Expand All @@ -301,8 +262,8 @@ async def on_reply(message: discord.Message):
return msg

async def next_task(self):
task = self.backend.fetch_task(protocol_schema.TaskRequestType.summarize_story, user=None)
# task = self.backend.fetch_random_task(user=None)
task_type = protocol_schema.TaskRequestType.random
task = self.backend.fetch_task(task_type, user=None)

await self.print_separtor("New Task")

Expand Down Expand Up @@ -335,7 +296,7 @@ async def background_timer(self):
await self.next_task()
except Exception:
logger.exception("fetching next task failed")
await asyncio.sleep(60)
await asyncio.sleep(5)

async def _sync(self, command: str, message: discord.Message):

Expand Down
11 changes: 5 additions & 6 deletions bot/templates/boot.msg
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
```
________ __
\_____ \ _____ _____ _______/ |_
/ | \\__ \ \__ \ / ___/\ __\
/ | \/ __ \_/ __ \_\___ \ | |
\_______ (____ (____ /____ > |__|
\_____ \ _____ ______ _______/ |_
/ | \\__ \ / ___// ___/\ __\
/ | \/ __ \_\___ \ \___ \ | |
\_______ (____ /____ >____ > |__|
\/ \/ \/ \/

{{bot_name}} {{version}}
git hash: {{git_hash}}
debug_mode: {{debug}}
```

https://github.com/LAION-AI/Open-Assistant
https://github.com/LAION-AI/Open-Assistant
12 changes: 12 additions & 0 deletions bot/templates/task_assistant_reply.msg
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
Act as the assistant and reply to the user.
Here is the conversation so far:
{% for message in task.conversation.messages %}
{% if message.is_assistant %}
:robot: Assistant:
{{ message.text }}
{% else %}
:person_red_hair: User:
**{{ message.text }}**"
{% endif %}
{% endfor %}
:robot: Assistant: { human, pls help me! ... }
4 changes: 4 additions & 0 deletions bot/templates/task_initial_prompt.msg
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Please provide an initial prompt to the assistant.
{% if task.hint %}
Hint: {task.hint}"
{% endif %}
13 changes: 13 additions & 0 deletions bot/templates/task_rank_conversation_replies.msg
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Here is the conversation so far:
{% for message in task.conversation.messages %}{% if message.is_assistant %}
:robot: Assistant:
{{ message.text }}
{% else %}
:person_red_hair: User:
**{{ message.text }}**"
{% endif %}{% endfor %}
Rank the following replies:
{% for reply in task.replies %}
{{loop.index}}: {{reply}}{% endfor %}

:scroll: Reply with the numbers of best to worst prompts separated by commas (example: "4,1,3,2").
5 changes: 5 additions & 0 deletions bot/templates/task_rank_initial_prompts.msg
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Rank the following prompts:
{% for prompt in task.prompts %}
{{loop.index}}: {{prompt}}{% endfor %}

:scroll: Reply with the numbers of best to worst prompts separated by commas (example: "4,1,3,2").
File renamed without changes.
12 changes: 12 additions & 0 deletions bot/templates/task_user_reply.msg
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
Please provide a reply to the assistant.
Here is the conversation so far:
{% for message in task.conversation.messages %}{% if message.is_assistant %}
:robot: Assistant:
{{ message.text }}
{% else %}
:person_red_hair: User:
**{{ message.text }}**"
{% endif %}{% endfor %}
{% if task.hint %}
Hint: {{ task.hint }}
{% endif %}

0 comments on commit df62ee0

Please sign in to comment.