chat.py 968 B

1234567891011121314151617181920212223242526272829303132333435
  1. import json
  2. from backend.apis.api import API
  3. from backend.apis.bing import BingSearchAPI
  4. from backend.models.codegeex import model, tokenizer
  5. from backend.utils.chat import build_model_input, SYS_PROMPT
  6. def chat(query: str, history: list[list[str]] = None):
  7. if not history:
  8. history = []
  9. ans = ""
  10. # Search with bing
  11. api: API = BingSearchAPI()
  12. search_res = api.call(query=query, history=history)
  13. ans += "搜索结果".center(100, "-") + '\n'
  14. ans += "```json\n" + json.dumps(search_res, indent=4, ensure_ascii=False) + "\n```\n"
  15. yield ans
  16. # Build model's input
  17. inputs: str = build_model_input(query, search_res)
  18. # Generate response
  19. ans += "模型回复".center(100, "-") + '\n'
  20. yield ans
  21. response, _ = model.chat(
  22. tokenizer,
  23. query=inputs,
  24. history=[{"role": "system", "content": SYS_PROMPT}],
  25. max_new_tokens=1024,
  26. temperature=0.2
  27. )
  28. yield ans + response