Skip to content

AI模组 #590

Backlog
Backlog

Description

@dianke123

我利用deepseek的云端API和ollama的本地AI模型基于python的库写了一个无论是否联网都能够使用的AI模组,以下是项目的代码

```python

import os
import requests
from openai import OpenAI
#这里用来判断是否联网,如果联网就用云端ai,如果没联网就用本地ai
def is_online():
    try:
        response = requests.get("https://www.baidu.com", timeout=3)
        return response.status_code < 500
    except requests.RequestException:
        return False


if is_online():
    ##这些是云端ai的url和API key(我用的是deepseek)具体你可以在官网的文件中查看
    client = OpenAI(
        api_key=os.environ.get('DEEPSEEK_API_KEY'),
        base_url="https://api.deepseek.com",
    )
    response = client.chat.completions.create(
        ##这里要填写你的模型的名字,具体要在deepseek的官网中查看,文件中有说明
        model="deepseek-flash",
        #这里的'rule'是角色'system'后面的内容是你要ai扮演的角色,'user'是你逗号后面的content是你对它说的话,'assistant'是ai向你回答的话
        #每次会话结束后都需要将它的回答按照assistant这行的格式来填写它回答的语句来创建记忆
        #你可以直接复制粘贴这段('role': 'assistant','conteat':'这里填它回答的语句',)
        #你可以直接复制粘贴这段('role': 'user', 'content': '这里填你想要对它说的话',)
    
        messages=[
            {"role": "system", "content": "你是我的人工智能助手贾维斯,你需要帮助我学习和完成项目"},
            {"role": "user", "content": "如果你有12个苹果,现在有四个人你会咋分"},
            {"role": "assistant", "content": "如果有12个苹果和4个人,我会将每个人分配3个苹果。"},
        ],
        #stream是流式输出(一个字一个字的出),reasoning_effort是推理努力程度,extra_body是额外的请求体参数,这些参数可以根据需要进行调整
        stream=False,
        reasoning_effort="high",
        extra_body={"thinking": {"type": "enabled"}},
    )
    #这里是ai回答的语句,具体你可以用apifox来发起请求然后看它回答的代码中的位置
    print(response.choices[0].message.content)
else:
#这些是ollama的本地ai的url和API key
    client = OpenAI(
        base_url='http://localhost:11434/v1/',
        api_key='ollama',  # required but ignored
    `)`
    chat_completion = client.chat.completions.create(
    #这里的rule是角色'user'是你逗号后面的content是你对它说的话,'assistant'是ai向你回答的话
    #每次会话结束后都需要将它的回答按照assistant这行的格式来填写它回答的语句来创建记忆
    #你可以直接复制粘贴这段('role': 'assistant','conteat':'这里填它回答的语句',)
    #你可以直接复制粘贴这段('role': 'user', 'content': '这里填你想要对它说的话',)注意如果在最后段落中添加了这段代码记得不要在后面加逗号,要不然会报错
        messages=[
            {
                'role': 'user', 'content': '你好,请帮我写一个关于if函数的代码',
                'role': 'assistant','conteat':''
            }
        ],
        #这里要填写你的模型的名字,ollama上面怎么写的这里怎么写
        model='gemma4:e4b',
    )
    #这里是ai回答的语句,具体你可以用apifox来发起请求然后看它回答的代码中的位置
    print(chat_completion.choices[0].message.content)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions