subtask_decompose.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. # -*- codong: utf-8 -*-
  2. """问题分解与分步处理工具
  3. 此脚本用于将复杂问题分解为多个步骤,并对每个步骤进行单独处理,最终汇总成完整答案。
  4. 主要通过调用DeepSeek API实现问题分解和分步解答功能。
  5. 功能流程:
  6. 1. 配置DeepSeek API参数
  7. 2. 定义API调用函数
  8. 3. 接收原始问题并构建系统提示
  9. 4. 调用API分解问题为多个步骤
  10. 5. 逐一处理每个步骤并获取回答
  11. 6. 汇总所有信息生成完整结果
  12. """
  13. from openai import OpenAI
  14. from typing import List, Dict, Any, Optional
  15. from cosine_similarity_example import cosine_similarity, cosine_similarity_numpy
  16. # 导入各种可能需要的库(部分未在当前版本使用,但为扩展预留)ilarity_numpy
  17. # 配置信息
  18. # DeepSeek 配置
  19. DEEPSEEK_API_KEY = "sk-cfd2df92c8864ab999d66a615ee812c5"
  20. DEEPSEEK_MODEL = {
  21. "DeepSeek-R1": "deepseek-reasoner",
  22. "DeepSeek-V3": "deepseek-chat",
  23. }
  24. def get_deepseek_completion(
  25. model: str,
  26. prompt: str,
  27. output_type: str = "text",
  28. tool_calls: bool = False,
  29. tools: List[Dict] = None
  30. ) -> Optional[Dict | List | str]:
  31. """调用DeepSeek API获取回答"""
  32. messages = [{"role": "user", "content": prompt}]
  33. kwargs = {
  34. "model": DEEPSEEK_MODEL.get(model, "deepseek-chat"),
  35. "messages": messages,
  36. }
  37. # 添加工具调用参数
  38. if tool_calls and tools:
  39. kwargs["tools"] = tools
  40. kwargs["tool_choice"] = "auto"
  41. # 创建OpenAI客户端连接DeepSeek API
  42. client = OpenAI(api_key=DEEPSEEK_API_KEY, base_url="https://api.deepseek.com")
  43. # 设置JSON输出格式
  44. if output_type == "json":
  45. kwargs["response_format"] = {"type": "json_object"}
  46. try:
  47. response = client.chat.completions.create(**kwargs)
  48. choice = response.choices[0]
  49. if output_type == "text":
  50. return choice.message.content # 只返回文本
  51. elif output_type == "json":
  52. import json
  53. return json.loads(choice.message.content)
  54. else:
  55. raise ValueError(f"Invalid output_type: {output_type}")
  56. except Exception as e:
  57. print(f"[ERROR] DeepSeek API调用失败: {e}")
  58. return None
  59. def main():
  60. bias_prompt ="请尽量简洁准确地回答:"
  61. orig_query = "如何养一只金刚鹦鹉"
  62. system_prompt = f"""你是一个智能助手,负责判断问题的复杂度并给出相应处理。
  63. 如果是简单问题,直接组织为json格式的回答返回该回答,例如:
  64. {{"steps": ["简单问题的回答"]}}。
  65. 如果是复杂问题,将这个问题分解为多个步骤,步骤的组织为json格式,格式为{{
  66. "steps": [
  67. "步骤1",
  68. "步骤2",
  69. ...
  70. ]
  71. }}
  72. 例如:如何写一篇好的博文
  73. 1.确定博文主题和目标受众;
  74. 2.进金刚鹦鹉集和研究;
  75. 3.制定博文大纲;
  76. ...
  77. 现在问题如下:{orig_query}
  78. """
  79. query = system_prompt
  80. print(f"\n调用DeepSeek回答: {query}")
  81. answer = get_deepseek_completion(
  82. model="DeepSeek-V3", # 使用DeepSeek V3模型
  83. prompt=query, # 使用query_text_1作为prompt
  84. output_type="json" # 返回文本格式
  85. )
  86. ############# ####解析步骤
  87. if answer:
  88. print(f"\nDeepSeek回答 分解子问题为:\n{answer}")
  89. else:
  90. print("未获取到DeepSeek的回答")
  91. steps = answer.get('steps', [])
  92. print(f"\n解析出的步骤数量: {len(steps)}")
  93. for i, step in enumerate(steps, 1):
  94. print(f"步骤{i}: {step}")
  95. ##################处理每个步骤
  96. context = orig_query
  97. for i, step in enumerate(steps, 1):
  98. print(f"\n处理步骤{i}: {step}")
  99. context += f"\n步骤{i}: {step}"
  100. # 调用DeepSeek处理每个步骤
  101. '''
  102. 这个步骤过程有选择:
  103. 1.调用使用RAG模型,调用知识库,获取步骤的回答
  104. 2.将context信息作为上下文一并投入prompt,获取步骤的回答
  105. '''
  106. step_answer = get_deepseek_completion(
  107. model="DeepSeek-V3", # 使用DeepSeek V3模型
  108. prompt=bias_prompt + step,
  109. output_type="text" # 返回文本格式
  110. )
  111. '''
  112. 这个步骤过程有选择:
  113. 1.调用使用RAG模型,调用知识库,获取步骤的回答
  114. 2.将context信息作为上下文一并投入prompt,获取步骤的回答
  115. '''
  116. if step_answer:
  117. print(f"步骤{i}的回答: {step_answer}")
  118. context += f"\n步骤{i}的回答: {step_answer}"
  119. else:
  120. print(f"步骤{i}未获取到回答")
  121. print("结果:", context)
  122. if __name__ == "__main__":
  123. main()