如何从聊天 gpt 响应中仅提取代码内容?

问题描述 投票:0回答:4

我使用

chatGpt
使用
openai
api(
/v1/chat/completions
) 和
gpt-3.5-turbo
作为模型来生成 SQL 查询。

但是我在从响应中提取 SQL 查询时遇到困难。因为有时 chatGpt 会为查询提供一些解释,有时则不会。我尝试过使用正则表达式,但它不可靠。

regex = r"SELECT .*?;"
match = re.search(regex, result)
if match:
   sql_query = match.group()
   print(sql_query)

还有其他方法可以从响应中仅提取代码部分吗?

sql code-generation openai-api gpt-3 chatgpt-api
4个回答
2
投票

我添加了“不要在您的回复中包含任何解释”,并且只得到了代码作为输出。


2
投票

我添加了“不要在回复中包含问题”,并且只得到了代码作为输出。


1
投票

尝试写一个好的提示;如果它仍然没有给你所需格式的输出,请尝试提供示例来尝试几次提示。

请参阅下面的请求正文,

{
    "model": "gpt-3.5-turbo",
    "messages": [
        {
            "role": "system",
            "content": "You are a SQL query generation assistant. You will be given a description of the table and a text description on what needs to be extracted or updated. Respond with only the query without explanation"
        },
        {
            "role": "user",
            "content": "There is a MySQL database table 'person' with four columns 'id', 'first_name', 'last_name' and 'address'. Write a query to return all entries of the table"
        },
        {
            "role": "assistant",
            "content": "SELECT * FROM person;"
        },
        {
            "role": "user",
            "content": "Write a query to update the address of the user with the id 103"
        }
    ],
    "temperature": 0.8
}

在这里,我给出了模型的一个简单响应示例,作为我实际提示的上下文。如果所需的输出格式很复杂,您可能需要举几个例子。

以下是我收到的上述请求的回复。

{
    "id": "chatcmpl-7698KLZnVNmPUHMXx7R4",
    "object": "chat.completion",
    "created": 1687816228,
    "model": "gpt-3.5-turbo-0301",
    "choices": [
        {
            "index": 0,
            "message": {
                "role": "assistant",
                "content": "UPDATE person SET address = 'New Address' WHERE id = 103;"
            },
            "finish_reason": "stop"
        }
    ],
    "usage": {
        "prompt_tokens": 117,
        "completion_tokens": 15,
        "total_tokens": 132
    }
}

0
投票

我不知道你是否还在寻找这个问题的答案,但我最近在 ChatGPT 中尝试了这个提示(不是使用 API,而是使用网络应用程序......无论如何,它应该也可以工作)并且似乎可以工作:

Imagine that you are not a conversational bot, but only a code copilot, so you will provide me only code

看起来 ChatGPT 有一种内部状态,所以如果你希望它以某种方式表现,你必须告诉它是哪一个。

© www.soinside.com 2019 - 2024. All rights reserved.