app.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. "embedchain[dataloaders]",
  9. )
  10. stub = Stub(
  11. name="embedchain-app",
  12. image=image,
  13. secrets=[Secret.from_dotenv(".env")],
  14. )
  15. web_app = FastAPI()
  16. embedchain_app = App(name="embedchain-modal-app")
  17. @web_app.post("/add")
  18. async def add(
  19. source: str = Body(..., description="Source to be added"),
  20. data_type: str | None = Body(None, description="Type of the data source"),
  21. ):
  22. """
  23. Adds a new source to the EmbedChain app.
  24. Expects a JSON with a "source" and "data_type" key.
  25. "data_type" is optional.
  26. """
  27. if source and data_type:
  28. embedchain_app.add(source, data_type)
  29. elif source:
  30. embedchain_app.add(source)
  31. else:
  32. return {"message": "No source provided."}
  33. return {"message": f"Source '{source}' added successfully."}
  34. @web_app.post("/query")
  35. async def query(question: str = Body(..., description="Question to be answered")):
  36. """
  37. Handles a query to the EmbedChain app.
  38. Expects a JSON with a "question" key.
  39. """
  40. if not question:
  41. return {"message": "No question provided."}
  42. answer = embedchain_app.query(question)
  43. return {"answer": answer}
  44. @web_app.get("/chat")
  45. async def chat(question: str = Body(..., description="Question to be answered")):
  46. """
  47. Handles a chat request to the EmbedChain app.
  48. Expects a JSON with a "question" key.
  49. """
  50. if not question:
  51. return {"message": "No question provided."}
  52. response = embedchain_app.chat(question)
  53. return {"response": response}
  54. @web_app.get("/")
  55. async def root():
  56. return responses.RedirectResponse(url="/docs")
  57. @stub.function(image=image)
  58. @asgi_app()
  59. def fastapi_app():
  60. return web_app