Learn Prompt-ChatGPT 精选案例:代码助理

这篇具有很好参考价值的文章主要介绍了Learn Prompt-ChatGPT 精选案例:代码助理。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

你可以使用 ChatGPT 进行代码生成、生成测试用例、注释、审查和漏洞检测。

代码生成​

我们可以让 ChatGPT 自动生成一个排序算法中的快速排序的Python代码。

简单的代码生成对于 ChatGPT 来说小事一桩。

测试用例​

用例来源出自StuGRua

在待测函数函数定义清晰的情况下,单元测试可以通过 ChatGPT 来生成。

写下列代码中CompressPicture函数的单测,要求覆盖全部逻辑。
断言使用require包。
测试用例以testCases的形式输出。

// CompressPicture the picture by resizing it to the specified width.
func CompressPicture(picData []byte, width uint) ([]byte, error) {
   // Decode the input image.
   oldBuffer := bytes.NewBuffer(picData)
   inputImg, _, err := image.Decode(oldBuffer)
   if err != nil {
      return nil, err
   }
   // Resize the image to the specified width.
   outputImg := resize.Resize(width, 0, inputImg, resize.Lanczos3)
   // Encode the output image as PNG and write it to a buffer.
   newBuffer := new(bytes.Buffer)
   err = png.Encode(newBuffer, outputImg)
   if err != nil {
      return nil, err
   }
   // Return the compressed image as a byte slice.
   return newBuffer.Bytes(), nil
}


# ChatGPT生成代码块如下:

func TestCompressPicture(t *testing.T) {
   // Setup test data
   imgData, err := os.ReadFile("test-image.png")
   if err != nil {
      t.Fatalf("failed to read test image file: %v", err)
   }
   testCases := []struct {
      name  string
      width uint
   }{
      {"compress with a valid width", 500},
      {"compress with an invalid width", 0},
   }
   for _, tc := range testCases {
      t.Run(tc.name, func(t *testing.T) {
         // Invoke the function being tested.
         compressedData, err := CompressPicture(imgData, tc.width)

         // Check the result.
         if err != nil {
            t.Fatalf("unexpected error: %v", err)
         }
         if len(compressedData) == 0 {
            t.Fatalf("compressed data is empty")
         }
         create, err := os.Create("test-image-compressed.png")
         if err != nil {
            return
         }
         defer create.Close()
         _, err = create.Write(compressedData)
      })

   }
}

ChatGP T单次对话有长度限制,所以一次尽量只进行一个函数的单元测试生成。

代码注释 & 格式优化​

ChatGPT 可以通过阅读代码,理解函数的输入、输出、功能以及用途,然后生成相应的 API 文档和注释。

Please add line comments to this Python code and reformat it to make it easier to read:

import openai
openai.api_key = "YOUR_API_KEY"

def generate_response(prompt):
    response = openai.Completion.create(engine="davinci",prompt=prompt,temperature=0.5,max_tokens=1024,n=1,stop=None)
    return response.choices[0].text.strip()

while True:
    prompt = input("请输入你的问题:")
    response = generate_response(prompt)
    print("答案:", response)

ChatGPT给每一句话都加上了解释,并且将过长的语句转化成更加易读的格式。

import openai  # Import the openai module

# Set the API key for the openai module
openai.api_key = "YOUR_API_KEY"  # Replace with your actual OpenAI API key

# Define a function for generating a response from OpenAI's language model given a prompt
def generate_response(prompt):
    # Create an OpenAI completion with the specified parameters
    response = openai.Completion.create(
        engine="davinci",  # Use the 'davinci' language model
        prompt=prompt,  # Use the provided prompt
        temperature=0.5,  # Use a temperature of 0.5, which means the model will generate diverse responses
        max_tokens=1024,  # Generate up to 1024 tokens of output
        n=1,  # Generate a single response
        stop=None  # Do not use a stop sequence to end the generated text
    )
    # Extract the generated text from the response and return it
    return response.choices[0].text.strip()

# Continuously prompt the user for questions and generate responses using the generate_response function
while True:
    prompt = input("Please enter your question: ")  # Prompt the user for a question
    response = generate_response(prompt)  # Generate a response to the question using the generate_response function
    print("Answer:", response)  # Print the generated response

代码调试​

通过之前的几个步骤,你已经了解了如何编写正确且具有测试用例的代码。

在日常开发中,除了编写代码之外,我们还会遇到两个比较棘手的开发步骤。一个是解决运行现有的代码后出现的错误;另一个是如何在当前编程语言中复现其他编程语言已经支持的处理逻辑呢?

我们先解决第一个问题。一般来说,写完代码后运行,如果代码中有错误,解释器会提示错误信息,按照提示信息,通常可以很快找出错误并进行修改。但有时候错误提示信息不是那么明确,当你检查了几遍仍然无法找出问题,就会比较困扰。ChatGPT 可以结合已有的错误信息,帮助我们分析代码中潜在的问题。

这里我选择了一个stack overflow上python跟SQL数据库连接错误的例子:Error while trying to connect to sql server with python using pyodbc

ChatGPT扮演成了一个python专家:

You are a python expert who can pinpoint errors in your code through error messages and provide easy-to-understand solutions.

error```
Traceback (most recent call last):
File "[test.py](http://test.py/)", line 7, in <module>
conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL
Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
pyodbc.InterfaceError: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL
Server]Login failed for user 'SA'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC
Driver 17 for SQL Server][SQL Server]Login failed for user 'SA'. (18456)")

code```

import pyodbc

server = 'SERVER'

database = 'DBNAME'

username = 'SA'

password = 'SQLPWD'

conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)

Please analyse "code" for possible causes, solutions and the correct code depending on the "error”.  


The error message indicates that the login for the SQL Server failed for the user 'SA'. There could be several reasons for this error, but one possible reason is that the provided password is incorrect or the 'SA' account is disabled. Here are some steps to troubleshoot and fix the error:

Verify the username and password: Double-check that the provided username and password are correct. You can try logging in to the SQL Server using these credentials to ensure that they are valid.

Check if the 'SA' account is disabled: If the 'SA' account is disabled, you will not be able to log in to the SQL Server using this account. You can check the account status in SQL Server Management Studio or by running a query on the server:

SELECT name, is_disabled
FROM sys.sql_logins
WHERE name = 'SA'
If the 'is_disabled' column value is 1, then the account is disabled. To enable the account, you can run the following query:
ALTER LOGIN SA WITH PASSWORD = '<new_password>', CHECK_POLICY = OFF, CHECK_EXPIRATION = OFF;
Note that it's not recommended to use the 'SA' account for regular database operations as it has elevated privileges.

Check the SQL Server authentication mode: If the SQL Server authentication mode is set to 'Windows Authentication mode only', you will not be able to log in using SQL Server authentication. You can check the authentication mode in SQL Server Management Studio by right-clicking on the server instance, selecting Properties, and navigating to the Security tab.

ChatGPT 给出的解决方法是:

  • 验证用户名和密码
  • 检查 "SA "账户是否被禁用
  • 检查SQL Server的认证模式

而网页中最受欢迎的回复是:

  • SA被禁止访问
  • 服务器认证选择错误
  • SQL服务器没有开放远程访问

通过比较,我们很容易得到ChatGPT在代码调试方面的可行性。

代码互翻​

ChatGPT 提供的另一个非常有用的功能是能够将程序从一种语言移植到另一种语言。

这里我在 Leetcode 找了一道常见算法题最长回文子串的 C++ 实现,转化成 Python 语言。

备注

最长回文子串题目:

给你一个字符串 s,找到 s 中最长的回文子串。 如果字符串的反序与原始字符串相同,则该字符串称为回文字符串。

You are an expert program developer with extensive experience in writing C++ and Python. Please convert this C++ program to Python:

code```
class Solution {
public:
    string longestPalindrome(string s) {
        int len=s.size();
        if(len==0||len==1)
            return s;
        int start=0;
        int max=1;
        vector<vector<int>>  dp(len,vector<int>(len));
        for(int i=0;i<len;i++)
        {
            dp[i][i]=1;
            if(i<len-1&&s[i]==s[i+1])
            {
                dp[i][i+1]=1;
                max=2;
                start=i;
            }
        }
        for(int l=3;l<=len;l++)
        {
            for(int i=0;i+l-1<len;i++)
            {
                int j=l+i-1;
                if(s[i]==s[j]&&dp[i+1][j-1]==1)
                {
                    dp[i][j]=1;
                    start=i;
                    max=l;
                }
            }
        }
        return s.substr(start,max);
    }
};

ChatGPT输出的代码部份如下:

class Solution:
    def longestPalindrome(self, s: str) -> str:
        n = len(s)
        if n == 0 or n == 1:
            return s
        start = 0
        max_len = 1
        dp = [[0] * n for _ in range(n)]
        for i in range(n):
            dp[i][i] = 1
            if i < n - 1 and s[i] == s[i+1]:
                dp[i][i+1] = 1
                start = i
                max_len = 2
        for l in range(3, n+1):
            for i in range(n-l+1):
                j = i + l - 1
                if s[i] == s[j] and dp[i+1][j-1] == 1:
                    dp[i][j] = 1
                    start = i
                    max_len = l
        return s[start:start+max_len]

代码顺利通过测试:

Learn Prompt-ChatGPT 精选案例:代码助理,ChatGPT,prompt,chatgpt

IDE 推荐​

这里我推荐的是Cursor.so,它本身是一个集成了 GPT-4, 国内直接可以访问的,优秀而强大的免费代码生成器,可以帮助你快速编写、编辑和讨论代码。它支持多种编程语言,如 Python, Java, C#, JavaScript 等,并且可以根据你的输入和需求自动生成代码片段。文章来源地址https://www.toymoban.com/news/detail-732334.html

到了这里,关于Learn Prompt-ChatGPT 精选案例:代码助理的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Learn Prompt-人工智能基础

    什么是人工智能?很多人能举出很多例子说这就是人工智能,但是让我们给它定义一个概念大家又觉得很难描述的清楚。实际上,人工智能并不是计算机科学领域专属的概念,在其他学科包括神经科学、心理学、哲学等也有人工智能的概念以及相关的研究。在笔者的观点里,

    2024年02月07日
    浏览(27)
  • ChatGpt与AndroidStudio合体变身教程,从此ChatGPT成为你的私人助理

    chatGpt火了这么长时间了,大家肯定都有所了解,今天我就给大家分享一下,如何让chatgpt与AndroidStudio成功合体,变身成为我们的私人助理!(记得给鄙人点点关注哦) 首先,我们打开AndroidStudio的Setting-Plugins-Marketplace,输入bito,进行下载(如下gif) 重启后,请注意AndroidStudio最右

    2024年02月05日
    浏览(33)
  • ChatGPT在智能虚拟助理和个人助手中的应用如何?

    ChatGPT在智能虚拟助理和个人助手中的应用正日益深入人心,成为人们日常生活和工作中的重要帮手。作为一种先进的自然语言处理技术,ChatGPT能够模拟人类对话、理解用户需求并提供有益信息,从而在智能虚拟助理和个人助手领域发挥着重要作用。本文将详细探讨ChatGPT在这

    2024年02月11日
    浏览(31)
  • 如何调教一个定制化的ChatGPT私人助理,接入自家知识库

    大家好,欢迎来到 Crossin的编程教室 ! 我在之前的文章里介绍过,如何利用 OpenAI 开放的 API,将 ChatGPT 接入自己开发的程序: 把 ChatGPT 加到你自己的程序里 当时开放的模型还是 text-davinci-003。 文章发布后没多久,gpt-3.5 的模型,也就是大家熟知的 ChatGPT,就在 API 中开放了,

    2024年02月10日
    浏览(26)
  • WorkPlus AI助理,基于ChatGPT的企业级知识问答机器人

    随着人工智能技术的发展,WorkPlus AI助理以ChatGPT对话能力为基础,将企业数据与人工智能相结合,推出了面向企业的知识问答机器人。这一创新性的解决方案帮助企业高效管理和利用自身的知识资产,助力企业级人工智能的构建。与传统的基于文本数据的ChatGPT不同,WorkPlus

    2024年02月09日
    浏览(43)
  • 软考案例分析题精选

    试题一:阅读下列说明,回答问题1至问题4,将解答填入答题纸的对应栏内。 某公司中标了一个软件开发项目,项目经理根据以往的经验估算了开发过程中各项任务需要的工期及预算成本,如下表所示: 任务 紧前任务 工期 PV AC 乐观 可能 悲观 A / 2 5 8 500 400 B A 3 5 13 600 650 C

    2024年01月20日
    浏览(28)
  • html5学习精选5篇案例

      html5学习心得1 一:了解HTML5前端开发技术 HTML 指的是超文本标记语言 (Hyper Text Markup Language),标记语言是一套标记标签 (markup tag),HTML 使用标记标签来描述网页。HTML5区别于HTML的标准,基于全新的规则手册,提供了一些新的元素和属性,在web技术发展的过程中成为新的里程

    2024年02月12日
    浏览(28)
  • java集成chatGpt完整案例代码(效果和官网一样逐字输出)

    背景 要集成chatGpt参考我上一篇文章即可。但是,如果要实现官网一样的效果,逐字输出,难度就提升了不少了。经过在官网的研究发现它应该是采用了SSE技术,这是一种最新的HTTP交互技术。SSE(Server-Sent Events):通俗解释起来就是一种基于HTTP的,以流的形式由服务端持续向客户

    2024年02月08日
    浏览(37)
  • 利用群晖部署ChatGPT-web服务,不需要代理,直接起飞,搭建你的私人AI助理

    🌟自建chatgpt-web是一个非常实用的AI服务,它可以帮助我们完成很多任务,而且,OpenAI的收费也非常实惠,自用一个月也就一两美刀,真的不贵!💸 🤖需要注册一个账号,获取API的key,就可以开始使用了。而且,OpenAI还有很多实用的功能,比如可以分享给朋友用,保存聊天

    2024年02月13日
    浏览(29)
  • Python案例|使用Scikit-learn进行房屋租金回归分析

    回归分析是一种预测性的建模技术,研究的是因变量(目标)和自变量(预测器)之间的关系。回归分析是建模和分析数据的重要工具。比如预测股票价格走势、预测居民收入、预测微博互动量等等。常用的有线性回归、逻辑回归、岭回归等。本文主要使用线性回归。 本文使

    2024年02月15日
    浏览(41)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包