如何在 Jupyter Notebook 中运行 GPT API shell 命令,而不必将多行字符串参数放在一行中?

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

我有一个 API 密钥,可以从命令行、Jupyter Notebook 或其他界面询问 GPT 机器人。我按照Open AI - 入门 - 提出请求 中的指南进行操作。 该代码在命令行界面中运行:

curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
     "model": "gpt-3.5-turbo",
     "messages": [{"role": "user", "content": "Say this is a test!"}],
     "temperature": 0.7
   }'

输出:

(base) user@admin:~$ curl https://api.openai.com/v1/chat/completions \
>   -H "Content-Type: application/json" \
>   -H "Authorization: Bearer sk-xyzxyzxyz............................" \
>   -d '{
>      "model": "gpt-3.5-turbo",
>      "messages": [{"role": "user", "content": "Say this is a test!"}],
>      "temperature": 0.7
>    }'
{
  "id": "chatcmpl-1a............................",
  "object": "chat.completion",
  "created": 1706212345,
  "model": "gpt-3.5-turbo-0613",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "This is a test!"
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 13,
    "completion_tokens": 5,
    "total_tokens": 18
  },
  "system_fingerprint": null
}

在 Jupyter Notebook 单元中,命令需要以“!curl ...”开头,因此“!”在前。这很清楚。

但是超过一行的字符串会引发错误:

  File <tokenize>:5
    }'
    ^
IndentationError: unindent does not match any outer indentation level

显然,多行字符串不起作用,因为我可以运行:

!curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-xyzxyzxyz............................" \
  -d '{"model": "gpt-3.5-turbo", "messages": [{"role": "user", "content": "Say this is a test!"}], "temperature": 0.7}'

我在一些线程中看到所有内容都写在一行中,例如:https://community.openai.com/t/how-can-i-get-a-gpt4-api-key/379141/12。这可能是最佳实践,也可能不是最佳实践,但这么长的行读起来很尴尬。

如何在 Jupyter Notebook 中运行 GPT API shell 命令,而不必将多行字符串参数放在一行中?

shell jupyter-notebook command-line multiline multilinestring
1个回答
0
投票

这是工作代码,您只需在每一行添加“”或“”即可。正如您从

在 Jupyter 笔记本中运行命令行命令
中猜测的那样,将 """ 放在开头和结尾是行不通的。

我认为这行不通,因为第一行已经有“”标志。

curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{ \
     "model": "gpt-3.5-turbo", \
     "messages": [{"role": "user", "content": "Say this is a test!"}], \
     "temperature": 0.7 \
   }'

这会产生相同的输出。

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