简介

在本案例中,我们将展示如何创建一个可用于文本摘要的自定义智能体。

安装

通过下述命令安装需要的依赖包

  1. pip install "dbgpt[agent]>=0.5.9rc1" -U
  2. pip install openai

创建自定义智能体

初始化智能体

绝大多数情况下,你只需要继承基础Agent并重写相应的方法即可。

  1. from dbgpt.agent import ConversableAgent
  2. class MySummarizerAgent(ConversableAgent):
  3. def __init__(self, **kwargs):
  4. super().__init__(**kwargs)

定义Profile

在设计每个智能体之前,需要定义它的角色、身份和功能角色。具体定义如下

  1. from dbgpt.agent import ConversableAgent, ProfileConfig
  2. class MySummarizerAgent(ConversableAgent):
  3. profile: ProfileConfig = ProfileConfig(
  4. # The name of the agent
  5. name="Aristotle",
  6. # The role of the agent
  7. role="Summarizer",
  8. # The core functional goals of the agent tell LLM what it can do with it.
  9. goal=(
  10. "Summarize answer summaries based on user questions from provided "
  11. "resource information or from historical conversation memories."
  12. ),
  13. # Introduction and description of the agent, used for task assignment and display.
  14. # If it is empty, the goal content will be used.
  15. desc=(
  16. "You can summarize provided text content according to user's questions"
  17. " and output the summarization."
  18. ),
  19. )
  20. def __init__(self, **kwargs):
  21. super().__init__(**kwargs)

提供Prompt约束

智能体的Prompt默认使用固定的模版组装(如有特殊需求,可绑定外部模版)。其中主要包括

  • 角色认定(自动生成)
  • 资源信息(自动生成)
  • 约束逻辑
  • 参考案例
  • 输出格式模版和限制

所以我们定义的智能体提示词如下:

  1. from dbgpt.agent import ConversableAgent, ProfileConfig
  2. class MySummarizerAgent(ConversableAgent):
  3. profile: ProfileConfig = ProfileConfig(
  4. # The name of the agent
  5. name="Aristotle",
  6. # The role of the agent
  7. role="Summarizer",
  8. # The core functional goals of the agent tell LLM what it can do with it.
  9. goal=(
  10. "Summarize answer summaries based on user questions from provided "
  11. "resource information or from historical conversation memories."
  12. ),
  13. # Introduction and description of the agent, used for task assignment and display.
  14. # If it is empty, the goal content will be used.
  15. desc=(
  16. "You can summarize provided text content according to user's questions"
  17. " and output the summarization."
  18. ),
  19. # Refer to the following. It can contain multiple constraints and reasoning
  20. # restriction logic, and supports the use of parameter template {{ param_name }}.
  21. constraints=[
  22. "Prioritize the summary of answers to user questions from the improved resource"
  23. " text. If no relevant information is found, summarize it from the historical "
  24. "dialogue memory given. It is forbidden to make up your own.",
  25. "You need to first detect user's question that you need to answer with your"
  26. " summarization.",
  27. "Extract the provided text content used for summarization.",
  28. "Then you need to summarize the extracted text content.",
  29. "Output the content of summarization ONLY related to user's question. The "
  30. "output language must be the same to user's question language.",
  31. "If you think the provided text content is not related to user questions at "
  32. "all, ONLY output '{{ not_related_message }}'!!.",
  33. ]
  34. )
  35. def __init__(self, **kwargs):
  36. super().__init__(**kwargs)

Prompt模版格式

如果提示中使用了动态参数,则需要实际的对话过程来组装这些值,需要重载并实现以下接口(_init_reply_message)

  1. from dbgpt.agent import AgentMessage, ConversableAgent, ProfileConfig
  2. NOT_RELATED_MESSAGE = "Did not find the information you want."
  3. class MySummarizerAgent(ConversableAgent):
  4. profile: ProfileConfig = ProfileConfig(
  5. # The name of the agent
  6. name="Aristotle",
  7. # The role of the agent
  8. role="Summarizer",
  9. # The core functional goals of the agent tell LLM what it can do with it.
  10. goal=(
  11. "Summarize answer summaries based on user questions from provided "
  12. "resource information or from historical conversation memories."
  13. ),
  14. # Introduction and description of the agent, used for task assignment and display.
  15. # If it is empty, the goal content will be used.
  16. desc=(
  17. "You can summarize provided text content according to user's questions"
  18. " and output the summarization."
  19. ),
  20. # Refer to the following. It can contain multiple constraints and reasoning
  21. # restriction logic, and supports the use of parameter template {{ param_name }}.
  22. constraints=[
  23. "Prioritize the summary of answers to user questions from the improved resource"
  24. " text. If no relevant information is found, summarize it from the historical "
  25. "dialogue memory given. It is forbidden to make up your own.",
  26. "You need to first detect user's question that you need to answer with your"
  27. " summarization.",
  28. "Extract the provided text content used for summarization.",
  29. "Then you need to summarize the extracted text content.",
  30. "Output the content of summarization ONLY related to user's question. The "
  31. "output language must be the same to user's question language.",
  32. "If you think the provided text content is not related to user questions at "
  33. "all, ONLY output '{{ not_related_message }}'!!.",
  34. ],
  35. )
  36. def __init__(self, **kwargs):
  37. super().__init__(**kwargs)
  38. def _init_reply_message(self, received_message: AgentMessage) -> AgentMessage:
  39. reply_message = super()._init_reply_message(received_message)
  40. # Fill in the dynamic parameters in the prompt template
  41. reply_message.context = {"not_related_message": NOT_RELATED_MESSAGE}
  42. return reply_message

资源预加载(可选)

如果有一些特定的资源,则必须在智能体初始化时提前加载绑定的资源。可以参考下面的实现。根据资源的实际情况确定。在大多数情况下,是没有必要的。

  1. from dbgpt.agent import ConversableAgent, AgentMessage
  2. class MySummarizerAgent(ConversableAgent):
  3. # ... other code
  4. async def preload_resource(self) -> None:
  5. # Load the required resources
  6. for resource in self.resources:
  7. # Load your resource, please write your own code here
  8. pass

结果检查

如果动作执行结果需要严格验证与校验,有两种模式: 代码逻辑验证和LLM验证。当然,验证不是必须的,也没有默认实现。如下使用LLM的例子

  1. from typing import Tuple, Optional
  2. from dbgpt.agent import ConversableAgent, AgentMessage
  3. from dbgpt.core import ModelMessageRoleType
  4. CHECK_RESULT_SYSTEM_MESSAGE = (
  5. "You are an expert in analyzing the results of a summary task."
  6. "Your responsibility is to check whether the summary results can summarize the "
  7. "input provided by the user, and then make a judgment. You need to answer "
  8. "according to the following rules:\n"
  9. " Rule 1: If you think the summary results can summarize the input provided"
  10. " by the user, only return True.\n"
  11. " Rule 2: If you think the summary results can NOT summarize the input "
  12. "provided by the user, return False and the reason, split by | and ended "
  13. "by TERMINATE. For instance: False|Some important concepts in the input are "
  14. "not summarized. TERMINATE"
  15. )
  16. class MySummarizerAgent(ConversableAgent):
  17. # ... other code
  18. async def correctness_check(
  19. self, message: AgentMessage
  20. ) -> Tuple[bool, Optional[str]]:
  21. current_goal = message.current_goal
  22. action_report = message.action_report
  23. task_result = ""
  24. if action_report:
  25. task_result = action_report.get("content", "")
  26. check_result, model = await self.thinking(
  27. messages=[
  28. AgentMessage(
  29. role=ModelMessageRoleType.HUMAN,
  30. content=(
  31. "Please understand the following user input and summary results"
  32. " and give your judgment:\n"
  33. f"User Input: {current_goal}\n"
  34. f"Summary Results: {task_result}"
  35. ),
  36. )
  37. ],
  38. prompt=CHECK_RESULT_SYSTEM_MESSAGE,
  39. )
  40. fail_reason = ""
  41. if check_result and (
  42. "true" in check_result.lower() or "yes" in check_result.lower()
  43. ):
  44. success = True
  45. else:
  46. success = False
  47. try:
  48. _, fail_reason = check_result.split("|")
  49. fail_reason = (
  50. "The summary results cannot summarize the user input due"
  51. f" to: {fail_reason}. Please re-understand and complete the summary"
  52. " task."
  53. )
  54. except Exception:
  55. fail_reason = (
  56. "The summary results cannot summarize the user input. "
  57. "Please re-understand and complete the summary task."
  58. )
  59. return success, fail_reason

创建自定义Action

初始化Action

所有的智能体操作外部环境或者跟真实世界交互都是通过行动(Action)。Action定义了Agent的输出内容结构,并实际执行相应的操作。具体Action实现继承Action基类,如下

  1. from typing import Optional
  2. from pydantic import BaseModel, Field
  3. from dbgpt.vis import Vis
  4. from dbgpt.agent import Action, ActionOutput, AgentResource, ResourceType
  5. from dbgpt.agent.util import cmp_string_equal
  6. NOT_RELATED_MESSAGE = "Did not find the information you want."
  7. # The parameter object that the Action that the current Agent needs to execute needs to output.
  8. class SummaryActionInput(BaseModel):
  9. summary: str = Field(
  10. ...,
  11. description="The summary content",
  12. )
  13. class SummaryAction(Action[SummaryActionInput]):
  14. def __init__(self):
  15. super().__init__()
  16. @property
  17. def resource_need(self) -> Optional[ResourceType]:
  18. # The resource type that the current Agent needs to use
  19. # here we do not need to use resources, just return None
  20. return None
  21. @property
  22. def render_protocol(self) -> Optional[Vis]:
  23. # The visualization rendering protocol that the current Agent needs to use
  24. # here we do not need to use visualization rendering, just return None
  25. return None
  26. @property
  27. def out_model_type(self):
  28. return SummaryActionInput
  29. async def run(
  30. self,
  31. ai_message: str,
  32. resource: Optional[AgentResource] = None,
  33. rely_action_out: Optional[ActionOutput] = None,
  34. need_vis_render: bool = True,
  35. **kwargs,
  36. ) -> ActionOutput:
  37. """Perform the action.
  38. The entry point for actual execution of Action. Action execution will be
  39. automatically initiated after model inference.
  40. """
  41. try:
  42. # Parse the input message
  43. param: SummaryActionInput = self._input_convert(ai_message, SummaryActionInput)
  44. except Exception:
  45. return ActionOutput(
  46. is_exe_success=False,
  47. content="The requested correctly structured answer could not be found, "
  48. f"ai message: {ai_message}",
  49. )
  50. # Check if the summary content is not related to user questions
  51. if param.summary and cmp_string_equal(
  52. param.summary,
  53. NOT_RELATED_MESSAGE,
  54. ignore_case=True,
  55. ignore_punctuation=True,
  56. ignore_whitespace=True,
  57. ):
  58. return ActionOutput(
  59. is_exe_success=False,
  60. content="the provided text content is not related to user questions at all."
  61. f"ai message: {ai_message}",
  62. )
  63. else:
  64. return ActionOutput(
  65. is_exe_success=True,
  66. content=param.summary,
  67. )

绑定Action到智能体

在开发并且定义好Agent和Action之后,将Action绑定到对应的智能体

  1. from pydantic import BaseModel
  2. from dbgpt.agent import Action,ConversableAgent
  3. class SummaryActionInput(BaseModel):
  4. ...
  5. class SummaryAction(Action[SummaryActionInput]):
  6. ...
  7. class MySummarizerAgent(ConversableAgent):
  8. def __init__(self, **kwargs):
  9. super().__init__(**kwargs)
  10. self._init_actions([SummaryAction])

Action扩展参数处理

  1. from typing import Optional, Dict, Any
  2. from pydantic import BaseModel
  3. from dbgpt.agent import Action, ActionOutput, AgentResource, ConversableAgent
  4. class SummaryActionInput(BaseModel):
  5. ...
  6. class SummaryAction(Action[SummaryActionInput]):
  7. ...
  8. async def run(
  9. self,
  10. ai_message: str,
  11. resource: Optional[AgentResource] = None,
  12. rely_action_out: Optional[ActionOutput] = None,
  13. need_vis_render: bool = True,
  14. **kwargs,
  15. ) -> ActionOutput:
  16. # Read the extended parameters passed in by the agent
  17. extra_param = kwargs.get("action_extra_param_key", None)
  18. pass
  19. class MySummarizerAgent(ConversableAgent):
  20. def __init__(self, **kwargs):
  21. super().__init__(**kwargs)
  22. self._init_actions([SummaryAction])
  23. def prepare_act_param(self) -> Dict[str, Any]:
  24. return {"action_extra_param_key": "this is extra param"}

使用自定义智能体

自定义智能体创建好之后,可以通过下面的方式使用对应的智能体。

  1. import asyncio
  2. from dbgpt.agent import AgentContext, ConversableAgent, AgentMemory, LLMConfig, UserProxyAgent
  3. from dbgpt.model.proxy import OpenAILLMClient
  4. class MySummarizerAgent(ConversableAgent):
  5. ...
  6. async def main():
  7. llm_client = OpenAILLMClient(model_alias="gpt-3.5-turbo")
  8. context: AgentContext = AgentContext(conv_id="summarize")
  9. agent_memory: AgentMemory = AgentMemory()
  10. summarizer = (
  11. await MySummarizerAgent()
  12. .bind(context)
  13. .bind(LLMConfig(llm_client=llm_client))
  14. .bind(agent_memory)
  15. .build()
  16. )
  17. user_proxy = await UserProxyAgent().bind(agent_memory).bind(context).build()
  18. await user_proxy.initiate_chat(
  19. recipient=summarizer,
  20. reviewer=user_proxy,
  21. message="""I want to summarize advantages of Nuclear Power according to the following content.
  22. Nuclear power in space is the use of nuclear power in outer space, typically either small fission systems or radioactive decay for electricity or heat. Another use is for scientific observation, as in a Mössbauer spectrometer. The most common type is a radioisotope thermoelectric generator, which has been used on many space probes and on crewed lunar missions. Small fission reactors for Earth observation satellites, such as the TOPAZ nuclear reactor, have also been flown.[1] A radioisotope heater unit is powered by radioactive decay and can keep components from becoming too cold to function, potentially over a span of decades.[2]
  23. The United States tested the SNAP-10A nuclear reactor in space for 43 days in 1965,[3] with the next test of a nuclear reactor power system intended for space use occurring on 13 September 2012 with the Demonstration Using Flattop Fission (DUFF) test of the Kilopower reactor.[4]
  24. After a ground-based test of the experimental 1965 Romashka reactor, which used uranium and direct thermoelectric conversion to electricity,[5] the USSR sent about 40 nuclear-electric satellites into space, mostly powered by the BES-5 reactor. The more powerful TOPAZ-II reactor produced 10 kilowatts of electricity.[3]
  25. Examples of concepts that use nuclear power for space propulsion systems include the nuclear electric rocket (nuclear powered ion thruster(s)), the radioisotope rocket, and radioisotope electric propulsion (REP).[6] One of the more explored concepts is the nuclear thermal rocket, which was ground tested in the NERVA program. Nuclear pulse propulsion was the subject of Project Orion.[7]
  26. Regulation and hazard prevention[edit]
  27. After the ban of nuclear weapons in space by the Outer Space Treaty in 1967, nuclear power has been discussed at least since 1972 as a sensitive issue by states.[8] Particularly its potential hazards to Earth's environment and thus also humans has prompted states to adopt in the U.N. General Assembly the Principles Relevant to the Use of Nuclear Power Sources in Outer Space (1992), particularly introducing safety principles for launches and to manage their traffic.[8]
  28. Benefits
  29. Both the Viking 1 and Viking 2 landers used RTGs for power on the surface of Mars. (Viking launch vehicle pictured)
  30. While solar power is much more commonly used, nuclear power can offer advantages in some areas. Solar cells, although efficient, can only supply energy to spacecraft in orbits where the solar flux is sufficiently high, such as low Earth orbit and interplanetary destinations close enough to the Sun. Unlike solar cells, nuclear power systems function independently of sunlight, which is necessary for deep space exploration. Nuclear-based systems can have less mass than solar cells of equivalent power, allowing more compact spacecraft that are easier to orient and direct in space. In the case of crewed spaceflight, nuclear power concepts that can power both life support and propulsion systems may reduce both cost and flight time.[9]
  31. Selected applications and/or technologies for space include:
  32. Radioisotope thermoelectric generator
  33. Radioisotope heater unit
  34. Radioisotope piezoelectric generator
  35. Radioisotope rocket
  36. Nuclear thermal rocket
  37. Nuclear pulse propulsion
  38. Nuclear electric rocket
  39. """,
  40. )
  41. print(await agent_memory.gpts_memory.one_chat_completions("summarize"))
  42. if __name__ == "__main__":
  43. asyncio.run(main())

全部代码如下

  1. import asyncio
  2. from typing import Any, Dict, Optional, Tuple
  3. from dbgpt.agent import (
  4. Action,
  5. ActionOutput,
  6. AgentContext,
  7. AgentMemory,
  8. AgentMessage,
  9. AgentResource,
  10. ConversableAgent,
  11. LLMConfig,
  12. ProfileConfig,
  13. ResourceType,
  14. UserProxyAgent,
  15. )
  16. from dbgpt.agent.util import cmp_string_equal
  17. from dbgpt.core import ModelMessageRoleType
  18. from dbgpt.model.proxy import OpenAILLMClient
  19. from dbgpt.vis import Vis
  20. from pydantic import BaseModel, Field
  21. NOT_RELATED_MESSAGE = "Did not find the information you want."
  22. CHECK_RESULT_SYSTEM_MESSAGE = (
  23. "You are an expert in analyzing the results of a summary task."
  24. "Your responsibility is to check whether the summary results can summarize the "
  25. "input provided by the user, and then make a judgment. You need to answer "
  26. "according to the following rules:\n"
  27. " Rule 1: If you think the summary results can summarize the input provided"
  28. " by the user, only return True.\n"
  29. " Rule 2: If you think the summary results can NOT summarize the input "
  30. "provided by the user, return False and the reason, split by | and ended "
  31. "by TERMINATE. For instance: False|Some important concepts in the input are "
  32. "not summarized. TERMINATE"
  33. )
  34. class MySummarizerAgent(ConversableAgent):
  35. profile: ProfileConfig = ProfileConfig(
  36. # The name of the agent
  37. name="Aristotle",
  38. # The role of the agent
  39. role="Summarizer",
  40. # The core functional goals of the agent tell LLM what it can do with it.
  41. goal=(
  42. "Summarize answer summaries based on user questions from provided "
  43. "resource information or from historical conversation memories."
  44. ),
  45. # Introduction and description of the agent, used for task assignment and display.
  46. # If it is empty, the goal content will be used.
  47. desc=(
  48. "You can summarize provided text content according to user's questions"
  49. " and output the summarization."
  50. ),
  51. # Refer to the following. It can contain multiple constraints and reasoning
  52. # restriction logic, and supports the use of parameter template {{ param_name }}.
  53. constraints=[
  54. "Prioritize the summary of answers to user questions from the improved resource"
  55. " text. If no relevant information is found, summarize it from the historical "
  56. "dialogue memory given. It is forbidden to make up your own.",
  57. "You need to first detect user's question that you need to answer with your"
  58. " summarization.",
  59. "Extract the provided text content used for summarization.",
  60. "Then you need to summarize the extracted text content.",
  61. "Output the content of summarization ONLY related to user's question. The "
  62. "output language must be the same to user's question language.",
  63. "If you think the provided text content is not related to user questions at "
  64. "all, ONLY output '{{ not_related_message }}'!!.",
  65. ],
  66. )
  67. def __init__(self, **kwargs):
  68. super().__init__(**kwargs)
  69. self._init_actions([SummaryAction])
  70. def _init_reply_message(self, received_message: AgentMessage) -> AgentMessage:
  71. reply_message = super()._init_reply_message(received_message)
  72. # Fill in the dynamic parameters in the prompt template
  73. reply_message.context = {"not_related_message": NOT_RELATED_MESSAGE}
  74. return reply_message
  75. def prepare_act_param(self) -> Dict[str, Any]:
  76. return {"action_extra_param_key": "this is extra param"}
  77. async def correctness_check(
  78. self, message: AgentMessage
  79. ) -> Tuple[bool, Optional[str]]:
  80. current_goal = message.current_goal
  81. action_report = message.action_report
  82. task_result = ""
  83. if action_report:
  84. task_result = action_report.get("content", "")
  85. check_result, model = await self.thinking(
  86. messages=[
  87. AgentMessage(
  88. role=ModelMessageRoleType.HUMAN,
  89. content=(
  90. "Please understand the following user input and summary results"
  91. " and give your judgment:\n"
  92. f"User Input: {current_goal}\n"
  93. f"Summary Results: {task_result}"
  94. ),
  95. )
  96. ],
  97. prompt=CHECK_RESULT_SYSTEM_MESSAGE,
  98. )
  99. fail_reason = ""
  100. if check_result and (
  101. "true" in check_result.lower() or "yes" in check_result.lower()
  102. ):
  103. success = True
  104. else:
  105. success = False
  106. try:
  107. _, fail_reason = check_result.split("|")
  108. fail_reason = (
  109. "The summary results cannot summarize the user input due"
  110. f" to: {fail_reason}. Please re-understand and complete the summary"
  111. " task."
  112. )
  113. except Exception:
  114. fail_reason = (
  115. "The summary results cannot summarize the user input. "
  116. "Please re-understand and complete the summary task."
  117. )
  118. return success, fail_reason
  119. # The parameter object that the Action that the current Agent needs to execute needs to output.
  120. class SummaryActionInput(BaseModel):
  121. summary: str = Field(
  122. ...,
  123. description="The summary content",
  124. )
  125. class SummaryAction(Action[SummaryActionInput]):
  126. def __init__(self):
  127. super().__init__()
  128. @property
  129. def resource_need(self) -> Optional[ResourceType]:
  130. # The resource type that the current Agent needs to use
  131. # here we do not need to use resources, just return None
  132. return None
  133. @property
  134. def render_protocol(self) -> Optional[Vis]:
  135. # The visualization rendering protocol that the current Agent needs to use
  136. # here we do not need to use visualization rendering, just return None
  137. return None
  138. @property
  139. def out_model_type(self):
  140. return SummaryActionInput
  141. async def run(
  142. self,
  143. ai_message: str,
  144. resource: Optional[AgentResource] = None,
  145. rely_action_out: Optional[ActionOutput] = None,
  146. need_vis_render: bool = True,
  147. **kwargs,
  148. ) -> ActionOutput:
  149. """Perform the action.
  150. The entry point for actual execution of Action. Action execution will be
  151. automatically initiated after model inference.
  152. """
  153. extra_param = kwargs.get("action_extra_param_key", None)
  154. try:
  155. # Parse the input message
  156. param: SummaryActionInput = self._input_convert(
  157. ai_message, SummaryActionInput
  158. )
  159. except Exception:
  160. return ActionOutput(
  161. is_exe_success=False,
  162. content="The requested correctly structured answer could not be found, "
  163. f"ai message: {ai_message}",
  164. )
  165. # Check if the summary content is not related to user questions
  166. if param.summary and cmp_string_equal(
  167. param.summary,
  168. NOT_RELATED_MESSAGE,
  169. ignore_case=True,
  170. ignore_punctuation=True,
  171. ignore_whitespace=True,
  172. ):
  173. return ActionOutput(
  174. is_exe_success=False,
  175. content="the provided text content is not related to user questions at all."
  176. f"ai message: {ai_message}",
  177. )
  178. else:
  179. return ActionOutput(
  180. is_exe_success=True,
  181. content=param.summary,
  182. )
  183. async def main():
  184. llm_client = OpenAILLMClient(model_alias="gpt-3.5-turbo")
  185. context: AgentContext = AgentContext(conv_id="summarize")
  186. agent_memory: AgentMemory = AgentMemory()
  187. summarizer = (
  188. await MySummarizerAgent()
  189. .bind(context)
  190. .bind(LLMConfig(llm_client=llm_client))
  191. .bind(agent_memory)
  192. .build()
  193. )
  194. user_proxy = await UserProxyAgent().bind(agent_memory).bind(context).build()
  195. await user_proxy.initiate_chat(
  196. recipient=summarizer,
  197. reviewer=user_proxy,
  198. message="""I want to summarize advantages of Nuclear Power according to the following content.
  199. Nuclear power in space is the use of nuclear power in outer space, typically either small fission systems or radioactive decay for electricity or heat. Another use is for scientific observation, as in a Mössbauer spectrometer. The most common type is a radioisotope thermoelectric generator, which has been used on many space probes and on crewed lunar missions. Small fission reactors for Earth observation satellites, such as the TOPAZ nuclear reactor, have also been flown.[1] A radioisotope heater unit is powered by radioactive decay and can keep components from becoming too cold to function, potentially over a span of decades.[2]
  200. The United States tested the SNAP-10A nuclear reactor in space for 43 days in 1965,[3] with the next test of a nuclear reactor power system intended for space use occurring on 13 September 2012 with the Demonstration Using Flattop Fission (DUFF) test of the Kilopower reactor.[4]
  201. After a ground-based test of the experimental 1965 Romashka reactor, which used uranium and direct thermoelectric conversion to electricity,[5] the USSR sent about 40 nuclear-electric satellites into space, mostly powered by the BES-5 reactor. The more powerful TOPAZ-II reactor produced 10 kilowatts of electricity.[3]
  202. Examples of concepts that use nuclear power for space propulsion systems include the nuclear electric rocket (nuclear powered ion thruster(s)), the radioisotope rocket, and radioisotope electric propulsion (REP).[6] One of the more explored concepts is the nuclear thermal rocket, which was ground tested in the NERVA program. Nuclear pulse propulsion was the subject of Project Orion.[7]
  203. Regulation and hazard prevention[edit]
  204. After the ban of nuclear weapons in space by the Outer Space Treaty in 1967, nuclear power has been discussed at least since 1972 as a sensitive issue by states.[8] Particularly its potential hazards to Earth's environment and thus also humans has prompted states to adopt in the U.N. General Assembly the Principles Relevant to the Use of Nuclear Power Sources in Outer Space (1992), particularly introducing safety principles for launches and to manage their traffic.[8]
  205. Benefits
  206. Both the Viking 1 and Viking 2 landers used RTGs for power on the surface of Mars. (Viking launch vehicle pictured)
  207. While solar power is much more commonly used, nuclear power can offer advantages in some areas. Solar cells, although efficient, can only supply energy to spacecraft in orbits where the solar flux is sufficiently high, such as low Earth orbit and interplanetary destinations close enough to the Sun. Unlike solar cells, nuclear power systems function independently of sunlight, which is necessary for deep space exploration. Nuclear-based systems can have less mass than solar cells of equivalent power, allowing more compact spacecraft that are easier to orient and direct in space. In the case of crewed spaceflight, nuclear power concepts that can power both life support and propulsion systems may reduce both cost and flight time.[9]
  208. Selected applications and/or technologies for space include:
  209. Radioisotope thermoelectric generator
  210. Radioisotope heater unit
  211. Radioisotope piezoelectric generator
  212. Radioisotope rocket
  213. Nuclear thermal rocket
  214. Nuclear pulse propulsion
  215. Nuclear electric rocket
  216. """,
  217. )
  218. print(await agent_memory.gpts_memory.one_chat_completions("summarize"))
  219. if __name__ == "__main__":
  220. asyncio.run(main())

附录