本文正在参加 人工智能创作者扶持方案

众所周知,ChatGPT能够帮助研制人员编写或许Debug程序代码,可是在执行过程中,ChatGPT会将程序代码的一些相关文字解说和代码段混合着回来,如此,研制人员还需要自己进行编辑和张贴操作,功率上差强人意,本次咱们企图将ChatGPT直接嵌入到代码事务中,让ChatGPT生成能够直接运转的代码。

ChatGPT的片面答复问题

首要,咱们向ChatGPT提出一个简单的代码需求:

顺应潮流,解放双手,让ChatGPT直接编写可融入业务可运行的程序代码(Python3.10实现)

能够看到,就像上文所描绘的那样,ChatGPT会将文字描绘和代码片段混合着回来,其实对于真实的需求者来说,文字描绘自身是不用要的,由于假如发问者不知道什么是布隆过滤器,也就不会提出布隆过滤器相关的代码需求。

再看ChatGPT回来的布隆过滤器代码:

import hashlib
class BloomFilter:  
    def __init__(self, size, hash_count):  
        self.size = size  
        self.hash_count = hash_count  
        self.bit_array = [False] * size  
    def add(self, string):  
        for seed in range(self.hash_count):  
            result = hashlib.sha256((string + str(seed)).encode()).hexdigest()  
            index = int(result, 16) % self.size  
            self.bit_array[index] = True  
    def __contains__(self, string):  
        for seed in range(self.hash_count):  
            result = hashlib.sha256((string + str(seed)).encode()).hexdigest()  
            index = int(result, 16) % self.size  
            if not self.bit_array[index]:  
                return False  
        return True

大体上,没有毛病。可是片面性太强,什么是片面性?便是ChatGPT其实不是站在需求者的视角来编写代码,而是站在自己的角度上,它没有考虑事务的上下文联系,也便是类和办法命名、办法参数、以及参数类型或许回来值以及类型,这些东西是否符合需求者当时的代码事务。

当然,这并不是ChatGPT的错,主要是输入的问题描绘不行清晰和详细,但假如每次都需要将代码事务逻辑转化为文字告诉ChatGPT,又有些画蛇添足,狗尾续貂之感。

根据事务配置ChatGPT

那么怎样将ChatGPT融入事务代码?首要创立Openai接入函数:

import openai
openai.api_key = "apikey"  
def generate_code(func, docstring):  
    init_prompt = "You are a Python expert who can implement the given function."  
    definition = f"def {func}"  
    prompt = f"Read this incomplete Python code:\n```python\n{definition}\n```"  
    prompt += "\n"  
    prompt += f"Complete the Python code that follows this instruction: '{docstring}'. Your response must start with code block '```python'."  
    response = openai.ChatCompletion.create(  
        model="gpt-3.5-turbo",  
        temperature=0,  
        max_tokens=1024,  
        top_p=1,  
        messages=[  
            {  
                "role": "system",  
                "content": init_prompt,  
            },  
            {  
                "role": "user",  
                "content": prompt,  
            },  
        ],  
    )  
    codeblock = response.choices[0].message.content  
    code = next(filter(None, codeblock.split("```python"))).rsplit("```", 1)[0]  
    code = code.strip()  
    return code

诀窍便是提前设置好引导词:

init_prompt = "You are a Python expert who can implement the given function."
    definition = f"def {func}"  
    prompt = f"Read this incomplete Python code:\n```python\n{definition}\n```"  
    prompt += "\n"  
    prompt += f"Complete the Python code that follows this instruction: '{docstring}'. Your response must start with code block '```python'."

这儿咱们提前设置两个参数func和docstring,也便是函数名和功用描绘,要求ChatGPT严厉按照参数的输入来回来代码,现在运转函数:

if __name__ == '__main__':
    print(generate_code("test","Sum two numbers"))

程序回来:

➜  chatgpt_write_code /opt/homebrew/bin/python3.10 "/Users/liuyue/wodfan/work/chatgpt_write_code/chatgpt_write_code.p
y"  
def test(a, b):  
    return a + b

如此一来,ChatGPT就不会回来废话,而是直接交给咱们能够运转的代码。

装修器调用ChatGPT

事实上,函数调用环节也能够省掉,咱们能够使用Python装修器的闭包原理,直接将所界说函数的参数和描绘传递给ChatGPT,随后再直接运转被装修的函数,提高功率:

import inspect
from functools import wraps  
def chatgpt_code(func):  
    @wraps(func)  
    def wrapper(*args, **kwargs):  
        signature = f'{func.__name__}({", ".join(inspect.signature(func).parameters)}):'  
        docstring = func.__doc__.strip()  
        code = generate_code(signature, docstring)  
        print(f"generated code:\n```python\n{code}\n```")  
        exec(code)  
        return locals()[func.__name__](*args, **kwargs)  
    return wrapper

将办法界说好之后,使用根据ChatGPT的装修器:

if __name__ == '__main__':
    @chatgpt_code  
    def sum_two(num1,num2):  
        """  
        Sum two numbers.  
        """  
    print(sum_two(1,2))

程序回来:

➜  chatgpt_write_code /opt/homebrew/bin/python3.10 "/Users/liuyue/wodfan/work/chatgpt_write_code/chatgpt_write_code.p
y"  
sum_two(num1, num2):  
generated code:  
def sum_two(num1, num2):  
    """  
    Sum two numbers.  
    """  
    return num1 + num2  
3

直接将事务逻辑和运转成果悉数回来。

那么现在,回到开篇的关于布隆过滤器的问题:

if __name__ == '__main__':
    @chatgpt_code  
    def bloom(target:str,storage:list):  
        """  
        Use a Bloom filter to check if the target is in storage , Just use this func , no more class  
        """  
    print(bloom("你好",["你好","Helloworld"]))

程序回来:

➜  chatgpt_write_code /opt/homebrew/bin/python3.10 "/Users/liuyue/wodfan/work/chatgpt_write_code/chatgpt_write_code.p
y"  
generated code:  
def bloom(target, storage):  
    # Initialize the Bloom filter with all zeros  
    bloom_filter = [0] * len(storage)  
    # Hash the target and set the corresponding bit in the Bloom filter to 1  
    for i in range(len(storage)):  
        if target in storage[i]:  
            bloom_filter[i] = 1  
    # Check if all the bits corresponding to the target are set to 1 in the Bloom filter  
    for i in range(len(storage)):  
        if target in storage[i] and bloom_filter[i] == 0:  
            return False  
    return True  
True  
➜  chatgpt_write_code

丝滑流通,和事务衔接得天衣无缝,拉链般重合,不需要挑挑拣拣,也不用复制张贴。

结语

毫无疑问,ChatGPT确然是神兵利器,吹毛可断,无坚不摧。但东西虽好,也需要看在谁的手里,所谓东西无高低,功力有高深,类比的话,假如倚天剑握在三岁孩童手中,不只毫无增益,还可能伤其自身,可是握在峨眉掌门灭绝师太手里,那就能够横扫千军如卷席了,那才能体现大宗匠的手法。最终,奉上项目代码,与众乡亲同飨:github.com/zcxey2911/chatgptapi_write_code