huhan3000/ai-tools/scripts/moonshot_codegen.py

120 lines
3.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
月之暗面代码生成示例
展示如何使用 Kimi 进行各种代码生成任务
"""
from moonshot_config import get_moonshot_client
def generate_function(description, language="Python"):
"""生成函数代码"""
client = get_moonshot_client()
prompt = f"""
请用 {language} 编写一个函数:{description}
要求:
1. 包含完整的函数定义
2. 添加适当的注释和文档字符串
3. 包含错误处理(如果需要)
4. 提供使用示例
请只返回代码,不要额外的解释。
"""
try:
response = client.chat.completions.create(
model="moonshot-v1-8k",
messages=[
{
"role": "system",
"content": "你是一个专业的程序员,擅长编写高质量、可维护的代码。"
},
{
"role": "user",
"content": prompt
}
],
max_tokens=800,
temperature=0.1
)
return response.choices[0].message.content
except Exception as e:
return f"生成失败: {e}"
def explain_code(code):
"""解释代码功能"""
client = get_moonshot_client()
prompt = f"""
请详细解释以下代码的功能、逻辑和关键点:
```
{code}
```
请用中文回答,包括:
1. 代码的主要功能
2. 关键算法或逻辑
3. 可能的改进建议
"""
try:
response = client.chat.completions.create(
model="moonshot-v1-8k",
messages=[
{
"role": "system",
"content": "你是一个代码审查专家,擅长分析和解释代码。"
},
{
"role": "user",
"content": prompt
}
],
max_tokens=600,
temperature=0.2
)
return response.choices[0].message.content
except Exception as e:
return f"解释失败: {e}"
def main():
print("=== 月之暗面代码生成示例 ===\n")
# 示例1生成排序函数
print("1. 生成快速排序函数:")
print("-" * 40)
code1 = generate_function("实现快速排序算法,对整数列表进行排序")
print(code1)
print("\n" + "=" * 60 + "\n")
# 示例2生成数据处理函数
print("2. 生成数据处理函数:")
print("-" * 40)
code2 = generate_function("读取CSV文件并计算数值列的统计信息均值、中位数、标准差")
print(code2)
print("\n" + "=" * 60 + "\n")
# 示例3解释代码
sample_code = """
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
"""
print("3. 代码解释示例:")
print("-" * 40)
print("原代码:")
print(sample_code)
print("\n解释:")
explanation = explain_code(sample_code)
print(explanation)
if __name__ == "__main__":
main()