You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

answer.py 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import random
  17. from abc import ABC
  18. from functools import partial
  19. import pandas as pd
  20. from agent.component.base import ComponentBase, ComponentParamBase
  21. class AnswerParam(ComponentParamBase):
  22. """
  23. Define the Answer component parameters.
  24. """
  25. def __init__(self):
  26. super().__init__()
  27. self.post_answers = []
  28. def check(self):
  29. return True
  30. class Answer(ComponentBase, ABC):
  31. component_name = "Answer"
  32. def _run(self, history, **kwargs):
  33. if kwargs.get("stream"):
  34. return partial(self.stream_output)
  35. ans = self.get_input()
  36. if self._param.post_answers:
  37. ans = pd.concat([ans, pd.DataFrame([{"content": random.choice(self._param.post_answers)}])], ignore_index=False)
  38. return ans
  39. def stream_output(self):
  40. res = None
  41. if hasattr(self, "exception") and self.exception:
  42. res = {"content": str(self.exception)}
  43. self.exception = None
  44. yield res
  45. self.set_output(res)
  46. return
  47. stream = self.get_stream_input()
  48. if isinstance(stream, pd.DataFrame):
  49. res = stream
  50. answer = ""
  51. for ii, row in stream.iterrows():
  52. answer += row.to_dict()["content"]
  53. yield {"content": answer}
  54. else:
  55. for st in stream():
  56. res = st
  57. yield st
  58. if self._param.post_answers:
  59. res["content"] += random.choice(self._param.post_answers)
  60. yield res
  61. self.set_output(res)
  62. def set_exception(self, e):
  63. self.exception = e