|
| 1 | +# scripts/answer_discussion.py |
| 2 | +import os |
| 3 | +import sys |
| 4 | +import openai |
| 5 | +from github import Github |
| 6 | + |
| 7 | + |
| 8 | +def answer_question(question): |
| 9 | + openai.api_key = os.environ["GH_TOKEN"] |
| 10 | + |
| 11 | + # 构建提示词,包含组件库上下文信息 |
| 12 | + prompt = f""" |
| 13 | + 你是一个精通 Ant Design Charts 组件库的专家。请回答以下问题: |
| 14 | + {question} |
| 15 | +
|
| 16 | + 回答要求: |
| 17 | + - 提供代码示例(如果适用) |
| 18 | + - 引用官方文档(如果有相关内容) |
| 19 | + - 保持简洁明了 |
| 20 | + - 对复杂概念提供类比或解释 |
| 21 | + """ |
| 22 | + |
| 23 | + try: |
| 24 | + response = openai.chat.completions.create( |
| 25 | + model="gpt-4.1", |
| 26 | + messages=[{"role": "user", "content": prompt}], |
| 27 | + temperature=0.1, |
| 28 | + max_tokens=5000 |
| 29 | + ) |
| 30 | + return response.choices[0].message.content.strip() |
| 31 | + except Exception as e: |
| 32 | + print(f"Error generating answer: {e}") |
| 33 | + return "抱歉,回答生成失败。请尝试重新提问或联系维护者。" |
| 34 | + |
| 35 | + |
| 36 | +def get_discussion(gh, repo_name, discussion_id): |
| 37 | + repo = gh.get_repo(repo_name) |
| 38 | + return repo.get_discussion(int(discussion_id)) |
| 39 | + |
| 40 | + |
| 41 | +def post_answer(discussion, answer): |
| 42 | + footer = "\n\n---\n此回答由AI自动生成,仅供参考。如有疑问,请等待维护者回复。" |
| 43 | + discussion.create_reply(answer + footer) |
| 44 | + |
| 45 | + |
| 46 | +def main(): |
| 47 | + if len(sys.argv) != 2: |
| 48 | + print("Usage: python answer_discussion.py <discussion_id>") |
| 49 | + sys.exit(1) |
| 50 | + |
| 51 | + discussion_id = sys.argv[1] |
| 52 | + repo_name = os.environ["GITHUB_REPOSITORY"] # GitHub自动设置的环境变量 |
| 53 | + gh_token = os.environ["GH_TOKEN"] |
| 54 | + if not gh_token: |
| 55 | + print("Please set the GH_TOKEN environment variable") |
| 56 | + sys.exit(1) |
| 57 | + gh = Github(gh_token) |
| 58 | + |
| 59 | + try: |
| 60 | + discussion = get_discussion(gh, repo_name, discussion_id) |
| 61 | + question = discussion.body |
| 62 | + |
| 63 | + answer = answer_question(question) |
| 64 | + |
| 65 | + post_answer(discussion, answer) |
| 66 | + print(f"成功回复讨论 #{discussion_id}") |
| 67 | + except Exception as e: |
| 68 | + print(f"处理讨论时出错: {e}") |
| 69 | + sys.exit(1) |
| 70 | + |
| 71 | + |
| 72 | +if __name__ == "__main__": |
| 73 | + main() |
0 commit comments