systex_app.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import datetime
  2. from json import loads
  3. import time
  4. from typing import List
  5. from fastapi import Body, FastAPI
  6. from fastapi.middleware.cors import CORSMiddleware
  7. import pandas as pd
  8. from pydantic import BaseModel
  9. import uvicorn
  10. from dotenv import load_dotenv
  11. import os
  12. from supabase.client import Client, create_client
  13. from langchain.callbacks import get_openai_callback
  14. from ai_agent import main
  15. from semantic_search import semantic_cache
  16. load_dotenv()
  17. URI = os.getenv("SUPABASE_URI")
  18. supabase_url = os.environ.get("SUPABASE_URL")
  19. supabase_key = os.environ.get("SUPABASE_KEY")
  20. supabase: Client = create_client(supabase_url, supabase_key)
  21. app = FastAPI()
  22. app.add_middleware(
  23. CORSMiddleware,
  24. allow_origins=["*"],
  25. allow_credentials=True,
  26. allow_methods=["*"],
  27. allow_headers=["*"],
  28. )
  29. class ChatHistoryItem(BaseModel):
  30. q: str
  31. a: str
  32. @app.post("/agents")
  33. def agent(question: str, chat_history: List[ChatHistoryItem] = Body(...)):
  34. print(question)
  35. start = time.time()
  36. with get_openai_callback() as cb:
  37. # cache_question, cache_answer = semantic_cache(supabase, question)
  38. cache_answer = None
  39. if cache_answer:
  40. answer = cache_answer
  41. else:
  42. answer = main(question)
  43. processing_time = time.time() - start
  44. save_history(question, answer, cb, processing_time)
  45. if "test@systex.com" in answer:
  46. answer = "很抱歉,目前我無法回答您的問題,請將您的詢問發送至 test@systex.com 以便獲得更進一步的幫助,謝謝。"
  47. print(answer)
  48. return {"Answer": answer}
  49. def save_history(question, answer, cb, processing_time):
  50. # reference = [doc.dict() for doc in reference]
  51. record = {
  52. 'Question': question,
  53. 'Answer': answer,
  54. 'Total_Tokens': cb.total_tokens,
  55. 'Total_Cost': cb.total_cost,
  56. 'Processing_time': processing_time,
  57. }
  58. response = (
  59. supabase.table("agent_records")
  60. .insert(record)
  61. .execute()
  62. )
  63. class history_output(BaseModel):
  64. Question: str
  65. Answer: str
  66. Total_Tokens: int
  67. Total_Cost: float
  68. Processing_time: float
  69. Time: datetime.datetime
  70. @app.get('/history', response_model=List[history_output])
  71. async def get_history():
  72. response = supabase.table("agent_records").select("*").execute()
  73. df = pd.DataFrame(response.data)
  74. # engine = create_engine(URI, echo=True)
  75. # df = pd.read_sql_table("systex_records", engine.connect())
  76. # df.fillna('', inplace=True)
  77. result = df.to_json(orient='index', force_ascii=False)
  78. result = loads(result)
  79. return result.values()
  80. if __name__ == "__main__":
  81. uvicorn.run("systex_app:app", host='0.0.0.0', reload=True, port=8080,
  82. ssl_keyfile="/etc/ssl_file/key.pem",
  83. ssl_certfile="/etc/ssl_file/cert.pem")