运行 ChatGPT、Claude、Gemini 和 Grok 的 Stata 命令

Chuck Huber, 统计推广部总监

我在 2023 年写了一篇题为”运行 ChatGPT 的 Stata 命令”的博客文章,它仍然很受欢迎。不幸的是,OpenAI 更改了 API 代码,那篇文章中的chatgpt 命令不再运行。在这篇文章中,我将向您展示如何更新 API 代码,以及如何编写类似的 Stata 命令来使用 Claude、Gemini 和 Grok,如下所示:

. chatgpt "Write a haiku about Stata."
Data flows with ease,
Stata charts the silent truths,
Insights bloom in code.

. claude "Write a haiku about Stata."
Here is a haiku about Stata:
Stata, my old friend
Analyzing data with ease
Insights ever found

. gemini "Write a haiku about Stata."
Commands flow so fast,
Data shaped, models defined,
Insights now appear.

. grok "Write a haiku about Stata."
Data streams unfold,
Stata weaves the threads of truth,
Insights bloom in code.

与之前的文章一样,本文的重点是演示利用 PyStata 功能连接到 ChatGPT 和其他 AI 工具是多么容易,而不是就如何使用 AI 工具回答 Stata 特定问题提供建议。因此,我展示的示例只是要求写一首关于 Stata 的俳句。但是,您可以传递任何在 Stata 工作流程中认为有帮助的请求。

 

Stata/Python 集成回顾

我将假设您熟悉 Stata/Python 集成以及如何编写原始的chatgpt 命令。如果您不熟悉这些主题,您将需要阅读以下博客文章:

 

更新 ChatGPT 命令

您需要 OpenAI 用户账户和您自己的 OpenAI API 密钥来使用下面的代码。我无法使用我 2023 年的旧 API 密钥,不得不创建一个新密钥。

您还需要在 Stata 命令窗口中键入shell pip install openai来安装 Python 包openai。如果您使用作为平台(如 Anaconda)一部分的 Python,您可能需要使用不同的方法来安装openai包。我不得不键入shell pip uninstall openai来删除旧版本,然后键入shell pip install openai来安装新版本。

接下来,我们需要使用现代 API 语法用更新的代码替换旧的 Python 代码。我在搜索引擎中键入了python function to prompt chatgpt through api,这引导我找到了 OpenAI 网站上的 Developer quickstart 页面。一些阅读后,经过反复试验,得出了下面的 Python 代码。Python 函数query_openai()通过 API 发送提示,使用”gpt-4.1-mini”模型,并接收响应。我没有包含其他模型的选项,但如果您愿意,可以更改模型。

剩余的 Python 代码对响应做三件事。首先,它在 Stata 的 Results 窗口中打印响应。其次,它将响应写入名为chatgpt_output.txt的文件。第三,它使用 Stata 的 SFI 模块将响应从 Python 传递到 Stata 中的局部宏。第三步对于简单响应效果很好,但对于包含非标准字符或许多单引号或双引号的长响应可能会导致错误。您可以在”Macro.setLocal(…”行的开头放置一个#字符来注释掉该行并防止错误。

您可以将下面的代码保存到名为chatgpt.ado的文件中,将文件放在您的个人 ado 文件夹中,并像使用任何其他 Stata 命令一样使用它。您可以键入adopath来定位您的个人 ado 文件夹。

capture program drop chatgpt

program chatgpt, rclass

    version 19.5   // (or version 19 if you do not have StataNow)

    args InputText

    display ""

    python: query_openai("`InputText'", "gpt-4.1-mini")

    return local OutputText = `"`OutputText'"'

end

    

python:

import os

from openai import OpenAI

from sfi import Macro

    

def query_openai(prompt: str, model: str = "gpt-4.1-mini") -> str:

    # Pass the input string from a Stata local macro to Python

    inputtext = Macro.getLocal('InputText')

    # Enter your API key

    client = OpenAI(api_key="PASTE YOUR API KEY HERE")

    # Send the prompt through the API and receive the response

    response = client.chat.completions.create(

        model= model,

        messages=[

            {"role": "user", "content": inputtext}

        ]

    )

    # Print the response in the Results window

    print(response.choices[0].message.content)

    # Write the response to a text file

    f = open("chatgpt_output.txt", "w")

    f.write(response.choices[0].message.content)

    f.close()

    # Pass the response string from Python back to a Stata local macro

    Macro.setLocal("OutputText", response.choices[0].message.content)

end

现在我们可以运行我们的chatgpt命令并在 Results 窗口中查看响应。

. chatgpt "Write a haiku about Stata."
Data flows with ease,
Stata charts the silent truths,
Insights bloom in code.

我们可以键入return list来查看存储在局部宏r(OutputText)中的响应。

. return list
macros:
         r(OutputText) : "Data flows with ease, Stata charts the silent truths, Insights bloom .."

我们可以键入type chatgpt_output.txt来查看保存在文件chatgpt_output.txt中的响应。

. type chatgpt_output.txt
Data flows with ease,
Stata charts the silent truths,
Insights bloom in code.

成功了!让我们看看是否可以使用类似的策略为另一个 AI 模型创建 Stata 命令。

使用 Claude 的 Stata 命令

Claude 是由 Anthropic 开发的流行 AI 模型。Claude 包括 API 接口,您需要在其网站上设置用户账户并获取 API 密钥。获取我的 API 密钥后,我键入了python function to query claude api,这引导我找到了”Get started with Claude”网站。同样,一些阅读和反复试验得出了下面的 Python 代码。您需要在 Stata 的命令窗口中键入shell pip install anthropic来安装anthropic包。

请注意下面的 Python 代码与我们的chatgpt命令中的 Python 代码多么相似。唯一的主要区别是通过 API 发送提示并接收响应的代码。其他所有内容几乎完全相同。

您可以将下面的代码保存到名为claude.ado的文件中,将文件放在您的个人 ado 文件夹中,并像使用任何其他 Stata 命令一样使用它。

capture program drop claude

program claude, rclass

    version 19.5   // (or version 19 if you do not have StataNow)

    args InputText

    display ""

    python: query_claude()

    return local OutputText = `"`OutputText'"'

end

    

python:

import os

from sfi import Macro

from anthropic import Anthropic

    

def query_claude():

    # Pass the input string from a Stata local macro to Python

    inputtext = Macro.getLocal('InputText')

    # Enter your API key

    client = Anthropic(

        api_key='PASTE YOUR API KEY HERE'

    )

    # Send the prompt through the API and receive the response

    response = client.messages.create(

        model="claude-3-haiku-20240307",

        max_tokens=1000,

        messages=[

            {"role": "user", "content": inputtext}

        ]

    )

    # Print the response to the Results window

    print(response.content[0].text)

    # Write the response to a text file

    f = open("claude_output.txt", "w")

    f.write(response.content[0].text)

    f.close()

    # Pass the response string from Python back to a Stata local macro

    Macro.setLocal("OutputText", response.content[0].text)

end

现在我们可以运行我们的claude命令并查看响应。

. claude "Write a haiku about Stata."
Here is a haiku about Stata:
Stata, my old friend
Analyzing data with ease
Insights ever found

我们可以键入return list来查看存储在局部宏r(OutputText)中的响应。

. return list
macros:
         r(OutputText) : "Here is a haiku about Stata: Stata, my old friend Analyzing data with ea.."

我们可以键入type claude_output.txt来查看保存在文件claude_output.txt中的响应。

. type claude_output.txt
Here is a haiku about Stata:
Stata, my old friend
Analyzing data with ease
Insights ever found

您有时可能会看到如下所示的错误。这并不表示您的代码有问题。它告诉您 API 服务或网络已超时或已被中断。只需等待并重试。

  File "C:\Users\ChuckStata\AppData\Local\Programs\Python\Python313\Lib\site-packages\anthropic\
> _base_client.py", line 1065, in request
    raise APITimeoutError(request=request) from err
anthropic.APITimeoutError: Request timed out or interrupted. This could be due to a network timeout, 
> dropped connection, or request cancellation. See https://docs.anthropic.com/en/api/errors#long-requests
> for more details.
r(7102);

 

使用 Gemini 的 Stata 命令

Gemini 是由 Google 开发的流行 AI 模型。Gemini 也包括 API 接口,您需要在其网站上设置用户账户并获取 API 密钥。获取我的 API 密钥后,我键入了python function to query gemini api,这引导我找到了 Gemini API quickstart 网站。同样,一些阅读和反复试验得出了下面的 Python 代码。您需要在 Stata 的命令窗口中键入shell pip install -q -U google-genai来安装google-genai包。

同样,您可以将下面的代码保存到名为gemini.ado的文件中,将文件放在您的个人 ado 文件夹中,并像使用任何其他 Stata 命令一样使用它。

capture program drop gemini

program gemini, rclass

    version 19.5   // (or version 19 if you do not have StataNow)

    args InputText

    display ""

    python: query_gemini()

    return local OutputText = `"`OutputText'"'

end

    

python:

import os

from sfi import Macro

from google import genai

    

def query_gemini():

    # Pass the input string from a Stata local macro to Python

    inputtext = Macro.getLocal('InputText')

    # Enter your API key

    client = genai.Client(api_key="PASTE YOUR API KEY HERE")

    # Send prompt through the claude API key and get response

    response = client.models.generate_content(

        model="gemini-2.5-flash", contents=inputtext

    )

    # Print the response to the Results window

    print(response.text)

    # Write the response to a text file

    f = open("gemini_output.txt", "w")

    f.write(response.text)

    f.close()

    # Pass the response string from Python back to a Stata local macro

    Macro.setLocal("OutputText", response.text)

end

现在我们可以运行我们的gemini命令并查看响应。

. gemini "Write a haiku about Stata."
Commands flow so fast,
Data shaped, models defined,
Insights now appear.

我们可以键入return list来查看存储在局部宏r(OutputText)中的响应。

. return list
macros:
         r(OutputText) : "Commands flow so fast, Data shaped, models defined, Insights now appea.."

我们可以键入type gemini_output.txt来查看保存在文件gemini_output.txt中的响应。

. type gemini_output.txt
Commands flow so fast,
Data shaped, models defined,
Insights now appear.

 

使用 Grok 的 Stata 命令

好的,再添加一个只是为了好玩。Grok 是由 xAI 开发的另一个流行 AI 模型。您需要在其网站上设置用户账户并获取 API 密钥。获取我的 API 密钥后,我键入了python function to query grok api,这引导我找到了”Hitchhiker’s Guide to Grok”网站。同样,一些阅读和反复试验得出了下面的 Python 代码。您需要在 Stata 的命令窗口中键入shell pip install xai_sdk来安装xai_sdk包。

同样,您可以将下面的代码保存到名为grok.ado的文件中,将文件放在您的个人 ado 文件夹中,并像使用任何其他 Stata 命令一样使用它。

capture program drop grok

program grok, rclass

    version 19.5   // (or version 19 if you do not have StataNow)

    args InputText

    display ""

    python: query_grok("`InputText'", "grok-4")

    return local OutputText = `"`OutputText'"'

end

    

python:

import os

from sfi import Macro

from xai_sdk import Client

from xai_sdk.chat import user, system

    

def query_grok(prompt: str, model: str = "grok-4") -> str:

    # Pass the input string from a Stata local macro to Python

    inputtext = Macro.getLocal('InputText')

    # Enter your API key

    client = Client(api_key="PASTE YOUR API KEY HERE")

    # Send prompt through the claude API key and get response

    chat = client.chat.create(model=model)

    chat.append(user(inputtext))

    response = chat.sample()

    # Print the response to the Results window

    print(response.content)

    # Write the response to a text file

    f = open("grok_output.txt", "w")

    f.write(response.content)

    f.close()

    # Pass the response string from Python back to a Stata local macro

    Macro.setLocal("OutputText", response.content)

end

现在我们可以运行我们的grok命令并在 Results 窗口中查看响应。

. grok "Write a haiku about Stata."
Data streams unfold,
Stata weaves the threads of truth,
Insights bloom in code.

我们可以键入return list来查看存储在局部宏r(OutputText)中的响应。

. return list
macros:
         r(OutputText) : "Data streams unfold, Stata weaves the threads of truth,  Insights b.."

我们可以键入type grok_output.txt来查看文件grok_output.txt中的结果。

. type grok_output.txt
Data streams unfold,
Stata weaves the threads of truth,
Insights bloom in code.

 

结论

我希望上面的例子已经让您相信,编写和更新您自己的 Stata 命令来运行 AI 模型相对容易。我的示例故意很简单,仅用于教育目的。但我确信您可以想象许多选项,可以添加这些选项以允许使用其他模型进行其他类型的提示,例如声音或图像。也许你们中的一些人会受到启发,编写自己的命令并将它们发布在网络上。

将来阅读这篇文章的您可能会发现,API 语法再次更改,上面的代码不再工作,这很令人沮丧。这就是使用 API 的本质。它们会发生变化,您需要做一些功课来更新您的代码。但是,互联网上有许多资源可以帮助您更新代码或编写新命令。祝您好运,玩得开心!