poe.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import argparse
  2. import logging
  3. import os
  4. from typing import List, Optional
  5. from fastapi_poe import PoeBot, run
  6. from embedchain.helper_classes.json_serializable import register_deserializable
  7. from .base import BaseBot
  8. def start_command():
  9. parser = argparse.ArgumentParser(description="EmbedChain PoeBot command line interface")
  10. # parser.add_argument("--host", default="0.0.0.0", help="Host IP to bind")
  11. parser.add_argument("--port", default=8080, type=int, help="Port to bind")
  12. parser.add_argument("--api-key", type=str, help="Poe API key")
  13. # parser.add_argument(
  14. # "--history-length",
  15. # default=5,
  16. # type=int,
  17. # help="Set the max size of the chat history. Multiplies cost, but improves conversation awareness.",
  18. # )
  19. args = parser.parse_args()
  20. # FIXME: Arguments are automatically loaded by Poebot's ArgumentParser which causes it to fail.
  21. # the port argument here is also just for show, it actually works because poe has the same argument.
  22. run(PoeBot(), api_key=args.api_key or os.environ.get("POE_API_KEY"))
  23. @register_deserializable
  24. class PoeBot(BaseBot, PoeBot):
  25. def __init__(self):
  26. self.history_length = 5
  27. super().__init__()
  28. async def get_response(self, query):
  29. last_message = query.query[-1].content
  30. try:
  31. history = (
  32. [f"{m.role}: {m.content}" for m in query.query[-(self.history_length + 1) : -1]]
  33. if len(query.query) > 0
  34. else None
  35. )
  36. except Exception as e:
  37. logging.error(f"Error when processing the chat history. Message is being sent without history. Error: {e}")
  38. answer = self.handle_message(last_message, history)
  39. yield self.text_event(answer)
  40. def handle_message(self, message, history: Optional[List[str]] = None):
  41. if message.startswith("/add "):
  42. response = self.add_data(message)
  43. else:
  44. response = self.ask_bot(message, history)
  45. return response
  46. # def add_data(self, message):
  47. # data = message.split(" ")[-1]
  48. # try:
  49. # self.add(data)
  50. # response = f"Added data from: {data}"
  51. # except Exception:
  52. # logging.exception(f"Failed to add data {data}.")
  53. # response = "Some error occurred while adding data."
  54. # return response
  55. def ask_bot(self, message, history: List[str]):
  56. try:
  57. self.app.llm.set_history(history=history)
  58. response = self.query(message)
  59. except Exception:
  60. logging.exception(f"Failed to query {message}.")
  61. response = "An error occurred. Please try again!"
  62. return response
  63. def start(self):
  64. start_command()
  65. if __name__ == "__main__":
  66. start_command()