Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

answer.py 2.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. from typing import Tuple, Union
  20. import pandas as pd
  21. from agent.component.base import ComponentBase, ComponentParamBase
  22. class AnswerParam(ComponentParamBase):
  23. """
  24. Define the Answer component parameters.
  25. """
  26. def __init__(self):
  27. super().__init__()
  28. self.post_answers = []
  29. def check(self):
  30. return True
  31. class Answer(ComponentBase, ABC):
  32. component_name = "Answer"
  33. def _run(self, history, **kwargs):
  34. if kwargs.get("stream"):
  35. return partial(self.stream_output)
  36. ans = self.get_input()
  37. if self._param.post_answers:
  38. ans = pd.concat([ans, pd.DataFrame([{"content": random.choice(self._param.post_answers)}])], ignore_index=False)
  39. return ans
  40. def stream_output(self):
  41. res = None
  42. if hasattr(self, "exception") and self.exception:
  43. res = {"content": str(self.exception)}
  44. self.exception = None
  45. yield res
  46. self.set_output(res)
  47. return
  48. stream = self.get_stream_input()
  49. if isinstance(stream, pd.DataFrame):
  50. res = stream
  51. answer = ""
  52. for ii, row in stream.iterrows():
  53. answer += row.to_dict()["content"]
  54. yield {"content": answer}
  55. elif stream is not None:
  56. for st in stream():
  57. res = st
  58. yield st
  59. if self._param.post_answers and res:
  60. res["content"] += random.choice(self._param.post_answers)
  61. yield res
  62. if res is None:
  63. res = {"content": ""}
  64. self.set_output(res)
  65. def set_exception(self, e):
  66. self.exception = e
  67. def output(self, allow_partial=True) -> Tuple[str, Union[pd.DataFrame, partial]]:
  68. if allow_partial:
  69. return super.output()
  70. for r, c in self._canvas.history[::-1]:
  71. if r == "user":
  72. return self._param.output_var_name, pd.DataFrame([{"content": c}])
  73. self._param.output_var_name, pd.DataFrame([])