免费使用github提供的大模型

效果

image-20250805112238486

代码

import os
from openai import OpenAI

# 安全起见,建议将 token 存在环境变量里,例如 os.environ["OPENAI_API_KEY"]
# https://github.com/settings/tokens
# 添加copilot的权限就可以了
token = "ghxxxxxxxxxxxxxxxU6jU"  # 换成自己的
endpoint = "https://models.github.ai/inference"
model_name = "openai/gpt-4o"

# 初始化客户端
client = OpenAI(
    base_url=endpoint,
    api_key=token,
)

# 提问助手主程序
def chat_with_gpt(user_input, history=None):
    if history is None:
        history = []

    # 添加当前用户提问
    history.append({"role": "user", "content": user_input})

    try:
        response = client.chat.completions.create(
            messages=[{"role": "system", "content": "你是一个乐于助人的中文助手。"}] + history,
            temperature=0.7,
            top_p=1.0,
            max_tokens=1000,
            model=model_name
        )
        answer = response.choices[0].message.content
        history.append({"role": "assistant", "content": answer})
        return answer, history
    except Exception as e:
        return f"出错了:{e}", history

# 示例用法
if __name__ == "__main__":
    history = []
    print("你好,我是中文问答助手。请输入你的问题(输入 '退出' 结束):")
    while True:
        user_input = input("你:")
        if user_input.strip().lower() in ["退出", "exit", "q"]:
            print("再见!")
            break
        reply, history = chat_with_gpt(user_input, history)
        print("助手:", reply)

posted @ 2025-08-05 11:23  海浪博客  阅读(48)  评论(0)    收藏  举报