GPT Code Interpreter

前几天,找了一些开源项目阅读学习,主要了解现在执行GPT生成的代码一般的做法是什么样的。

unsetunset使用Ipython执行代码unsetunset

我们Google一搜,很容易就搜到:https://e2b.dev/,可以使用它提供的api在e2b的沙箱中执行生成的Python或JavaScript代码,一开始以为是开源的,仓库为:https://github.com/e2b-dev/code-interpreter.git

浏览源码后,开源的只是一个sdk,即你需要提供api key,然后使用e2b cloud sandbox去执行代码,项目关键代码如下:

try:
    with self._client.stream(
        "POST",
        f"{self._jupyter_url}/execute",
        json={
            "code": code,
            "context_id": context_id,
            "language": language,
            "env_vars": envs,
        },
        timeout=(request_timeout, timeout, request_timeout, request_timeout),
    ) as response:
        err = extract_exception(response)
        if err:
            raise err

            execution = Execution()

        for line in response.iter_lines():
            parse_output(
                execution,
                line,
                on_stdout=on_stdout,
                on_stderr=on_stderr,
                on_result=on_result,
                on_error=on_error,
            )

            return execution
except httpx.ReadTimeout:
    raise format_execution_timeout_error()
except httpx.TimeoutException:
    raise format_request_timeout_error()

其中jupyter_url这个变量名引起我的注意,Python仔都知道,Jupyter我们常用来写写数据分析和算法相关的notebook,是可以执行代码的,直接ChatGPT调研,就可以发现,我们可以使用ipython来执行代码。

然后我们发现了这个项目:https://github.com/chapyter/chapyter.git

Jupyter Notebook是基于Ipython的,可以使用Ipython包中的InteractiveShell来执行代码,用法如下:

from IPython.core.interactiveshell import InteractiveShell

# 创建一个 InteractiveShell 实例
shell = InteractiveShell.instance()

# 要执行的代码
code = """
def greet(name):
    return f"Hello, {name}!"

result = greet("Lindee")
print(result)
"""

# 执行代码
shell.run_cell(code)

不负责猜测,e2b可能也用了这种方式来执行。

当然,单纯这样,应该是不行的,因为用户可能会提交恶意代码,即GPT可能会生成自毁代码,所以需要限制执行。

因为e2b这里没有更多信息,所以我们换其他开源项目。

unsetunset使用subprocess.Popenunsetunset

又找到一个code-interpreter:https://github.com/haseeb-heaven/code-interpreter.git

阅读代码,可以找到关键代码如下:

# libs/code_interpreter.py

def execute_code(self, code, language):
        try:
            language = language.lower()
            self.logger.info(f"Running code: {code[:100]} in language: {language}")

            # Check for code and language validity
            ifnot code or len(code.strip()) == 0:
                return"Code is empty. Cannot execute an empty code."
            
            # Check for compilers on the system
            compilers_status = self._check_compilers(language)
            ifnot compilers_status:
                raise Exception("Compilers not found. Please install compilers on your system.")
            
            if language == "python":
                process = subprocess.Popen(["python", "-c", code], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                stdout, stderr = process.communicate()
                stdout_output = stdout.decode("utf-8")
                stderr_output = stderr.decode("utf-8")
                self.logger.info(f"Python Output execution: {stdout_output}, Errors: {stderr_output}")
                return stdout_output, stderr_output
            
            elif language == "javascript":
                process = subprocess.Popen(["node", "-e", code], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                stdout, stderr = process.communicate()
                stdout_output = stdout.decode("utf-8")
                stderr_output = stderr.decode("utf-8")
                self.logger.info(f"JavaScript Output execution: {stdout_output}, Errors: {stderr_output}")
                return stdout_output, stderr_output
            
            else:
                self.logger.info("Unsupported language.")
                raise Exception("Unsupported language.")
                
        except Exception as exception:
            self.logger.error(f"Exception in running code: {str(exception)}")
            raise exception

通过subprocess.Popen来执行Python或JavaScript代码,但跟Ipython一样,依旧会有安全性问题。

这些让cursor基于代码上下文,给我一下解决方案:

  • Sandbo沙箱执行

    • Docker

    • firejail(也是一个沙箱)

  • RestrictedPython执行受限的python代码(定义了Python语法的子集),即有风险的,都不给执行了

  • 对代码进行白名单审察(比如有os.remove的,直接删掉相关代码)

嗯,思路有了,但我想抄代码,不想基于思路直接写,而用cursor生成,我感觉信任度问题,因为自己研究不深入,如果用他生成的代码,可能也会出现意想不到的问题。

unsetunsetautogen的方案unsetunset

autogen是微软的multi-ai-agent相关的项目:

6d133ace24bdb4fba19d09beeff61915.png

它提供了3种执行代码的方式

  • azure就是用azure提供的python容器去执行,限制比较多,只支持有限的python库

  • 使用docker容器执行,默认使用的 python:3-slim 镜像

  • 使用subprocess执行,只是会在前面做一层过来,避免自毁代码

autogen的代码就可以复制来用了。

unsetunset总结unsetunset

比较标准的解决方法,就是使用docker,然后构建容器去执行,容器启动速度是很快的,但也会有点时间损耗,如果你想省点时间,就用subprocess的方案,毕竟autogen代码写好了,前面也有一层代码过滤的逻辑。

### Dify平台中的自定义代码编程指南 在Dify平台上编写自定义代码来实现特定工作流主要涉及利用该平台所提供的API接口以及内置工具集。对于希望构建复杂逻辑或集成第三方服务的应用场景而言,掌握这部分技能至关重要。 #### 利用Code Interpreter ChatBot应用作为起点 为了简化开发流程并加速原型设计阶段,在启动新项目时可以选择从预设模板入手。例如,通过使用`gpt-3.5-turbo`模型初始化一个Code Interpreter ChatBot实例[^3]: ```python from dify import create_chatbot chatbot = create_chatbot(model="gpt-3.5-turbo") ``` 此段代码展示了如何调用Dify API创建一个新的聊天机器人对象,并指定所使用的自然语言处理模型版本。这一步骤为后续定制化操作奠定了基础。 #### 实现具体业务逻辑 当基本环境配置完成后,可以根据实际需求向应用程序添加更多功能模块。假设存在这样一个场景——需要定期抓取某网站上的最新文章列表并将它们保存到本地数据库中;此时可以考虑采用如下方式完成任务: 1. **网络请求**:运用Python标准库或其他第三方库发起HTTP GET请求获取目标网页HTML源码; 2. **解析页面结构**:借助BeautifulSoup等工具提取所需信息片段; 3. **存储数据记录**:将收集到的信息按照既定格式存入关系型数据库表内。 下面给出了一段示范性质的伪代码示例,说明上述思路的具体实施方法: ```python import requests from bs4 import BeautifulSoup import sqlite3 def fetch_latest_articles(): url = "https://example.com/articles" response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') articles = [] for article in soup.find_all('div', class_='article'): title = article.h2.a.string.strip() link = f"https://example.com{article.h2.a['href']}" articles.append((title, link)) conn = sqlite3.connect('./articles.db') cursor = conn.cursor() insert_query = """ INSERT INTO Articles (Title, Link) VALUES (?, ?); """ cursor.executemany(insert_query, articles) fetch_latest_articles() ``` 值得注意的是,这段脚本仅为示意目的而写就,并未经过严格测试验证其正确性和稳定性。实际生产环境中应当更加注重异常情况处理机制的设计,确保程序能够稳定可靠运行。 #### 集成与优化 随着项目的推进发展,可能会遇到性能瓶颈或者维护困难等问题。这时就需要引入一些先进的软件工程实践和技术手段加以改进,比如但不限于: - 将重复性的I/O密集型任务异步化执行以提高效率; - 使用ORM框架代替原始SQL语句增强可读性的同时降低错误率; - 对敏感数据采取加密措施保障安全性。 综上所述,虽然官方文档已经提供了较为详尽的操作手册指导用户入门学习,但在面对个性化较强的需求时仍然离不开深入理解底层原理并灵活运用各种技术资源解决问题的能力[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

懒编程-二两

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值