app.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. from dotenv import load_dotenv
  2. from fastapi import Body, FastAPI, responses
  3. from modal import Image, Secret, Stub, asgi_app
  4. from embedchain import App
  5. load_dotenv(".env")
  6. image = Image.debian_slim().pip_install(
  7. "embedchain",
  8. "lanchain_community==0.2.6",
  9. "youtube-transcript-api==0.6.1",
  10. "pytube==15.0.0",
  11. "beautifulsoup4==4.12.3",
  12. "slack-sdk==3.21.3",
  13. "huggingface_hub==0.23.0",
  14. "gitpython==3.1.38",
  15. "yt_dlp==2023.11.14",
  16. "PyGithub==1.59.1",
  17. "feedparser==6.0.10",
  18. "newspaper3k==0.2.8",
  19. "listparser==0.19",
  20. )
  21. stub = Stub(
  22. name="embedchain-app",
  23. image=image,
  24. secrets=[Secret.from_dotenv(".env")],
  25. )
  26. web_app = FastAPI()
  27. embedchain_app = App(name="embedchain-modal-app")
  28. @web_app.post("/add")
  29. async def add(
  30. source: str = Body(..., description="Source to be added"),
  31. data_type: str | None = Body(None, description="Type of the data source"),
  32. ):
  33. """
  34. Adds a new source to the EmbedChain app.
  35. Expects a JSON with a "source" and "data_type" key.
  36. "data_type" is optional.
  37. """
  38. if source and data_type:
  39. embedchain_app.add(source, data_type)
  40. elif source:
  41. embedchain_app.add(source)
  42. else:
  43. return {"message": "No source provided."}
  44. return {"message": f"Source '{source}' added successfully."}
  45. @web_app.post("/query")
  46. async def query(question: str = Body(..., description="Question to be answered")):
  47. """
  48. Handles a query to the EmbedChain app.
  49. Expects a JSON with a "question" key.
  50. """
  51. if not question:
  52. return {"message": "No question provided."}
  53. answer = embedchain_app.query(question)
  54. return {"answer": answer}
  55. @web_app.get("/chat")
  56. async def chat(question: str = Body(..., description="Question to be answered")):
  57. """
  58. Handles a chat request to the EmbedChain app.
  59. Expects a JSON with a "question" key.
  60. """
  61. if not question:
  62. return {"message": "No question provided."}
  63. response = embedchain_app.chat(question)
  64. return {"response": response}
  65. @web_app.get("/")
  66. async def root():
  67. return responses.RedirectResponse(url="/docs")
  68. @stub.function(image=image)
  69. @asgi_app()
  70. def fastapi_app():
  71. return web_app