开发Obsidian插件obsidian-python-runner,运行任意python脚本

用windsurf开发了一个Obsidian插件,可以在编辑器运行任何python脚本并将结果输出到编辑器。调用方式很简单:

    @py function_in_python_scripts()

另外,可以将当前文档的相关信息传递给python脚本,将doc作为参数传如即可,在范例程序example.py中有这个功能的演示:

def docinfos(doc):
    from datetime import datetime
    """Display detailed information about the current document"""
    info = {
        "Available fields": list(doc.keys()),
        "Document title": doc['title'],
        "File path": doc['path'],
        "Creation time": datetime.fromtimestamp(doc['created']/1000),
        "Modification time": datetime.fromtimestamp(doc['modified']/1000),
        "Content length": len(doc['content']),
        "Cursor position": doc['cursor'],
    }

    return info

在Obsidian的编辑器内输入

    @py docinfos(doc)

就可以得到当前文档的基本信息

    {'Available fields': 
    ['title', 'path', 'created', 'modified', 'content', 'frontmatter', 'cursor', 'selection'], 
    'Document title': 'Obsidian插件开发', 
    'File path': '杂七杂八/Obsidian插件开发.md', 
    'Creation time': datetime.datetime(2025, 1, 30, 18, 20, 4, 924000), 'Modification time': datetime.datetime(2025, 2, 9, 19, 31, 2, 909000), 
    'Content length': 1046, 
    'Cursor position': {'line': 36, 'ch': 0}}

通过Deepseek提供的API和其交流的代码:

  

def deepseek_r1(query):
    from openai import OpenAI
    """Use the Reasoner model through the DeepSeek API, which will output its reasoning process and final answer."""
    api_key="your api key"
    base_url="https://api.deepseek.com"
    try:
        ds = OpenAI(api_key=api_key, base_url=base_url)
        response = ds.chat.completions.create(
            model='deepseek-reasoner',
            messages=[
                {"role": "system", "content": "You are an office assistant"},
                {"role": "user", "content": query},
            ],
            max_tokens=8192,
            temperature=0.8,
            stream=False
        )  

        message = response.choices[0].message.content
        reasoning_content = response.choices[0].message.reasoning_content  

        r = f"{reasoning_content}\n\n{message}" 
        return(r)
    except Exception as e:
        return str(e)  

def deepseek_chat(query):

    from openai import OpenAI
    """Use the Chat model through the DeepSeek API, which will output the final answer."""
    api_key="your api key"
    base_url="https://api.deepseek.com"
    try:
        ds = OpenAI(api_key=api_key, base_url=base_url)
        response = ds.chat.completions.create(
            model='deepseek-chat',
            messages=[
                {"role": "system", "content": "You are an office assistant"},
                {"role": "user", "content": query},
            ],
            max_tokens=8192,
            temperature=0.8,
            stream=False
        ) 

        message = response.choices[0].message.content
        return(message)
    except Exception as e:
        return str(e)

在编辑器中输入@py deepseek_r1(“给我讲讲鸡兔同笼”),或者 @py deepseek_chat(“写一首关于春天的七言古诗”) 就可以和Deepseek对话了。

deepseek_r1deepseek_chat两个函数分别使用DeepSeek的R1模型和V3模型,可以按需求选择使用,R1虽然更好,但是价格是V3模型的4倍,只选对的,不选贵的。

开发这个插件的初衷,是想在Obsidian的编辑器内直接跟AI对话,虽然有一个现成的插件Smart composer有类似功能,但离我的要求还差一点点。并且很多人都在鼓吹AI的编程能力,认为程序员这一职业将消失,正好我对Obsidian的插件开发是0基础,借此来测试一下AI的编程能力究竟如何。结果在对typescript和插件开发规范完全不懂的情况下,用windsurf不到一个小时就开发出来了,功能完全符合预期,不得不说人工智能有时还是挺有用的。

插件的Github链接: obsidian-python-runner

Leave a Reply

Your email address will not be published. Required fields are marked *