Migrate OpenAI SDK Has Fix
Description
OpenAI has introduced some breaking changes in their API, such as using Client
to initialize the service and renaming the Completion
method to completions
. This example shows how to use ast-grep to automatically update your code to the new API.
API migration requires multiple related rules to work together. The example shows how to write multiple rules in a single YAML file. The rules and patterns in the example are simple and self-explanatory, so we will not explain them further.
YAML
yaml
id: import-openai
language: python
rule:
pattern: import openai
fix: from openai import Client
---
id: rewrite-client
language: python
rule:
pattern: openai.api_key = $KEY
fix: client = Client($KEY)
---
id: rewrite-chat-completion
language: python
rule:
pattern: openai.Completion.create($$$ARGS)
fix: |-
client.completions.create(
$$$ARGS
)
Example
python
import os
import openai
from flask import Flask, jsonify
app = Flask(__name__)
openai.api_key = os.getenv("OPENAI_API_KEY")
@app.route("/chat", methods=("POST"))
def index():
animal = request.form["animal"]
response = openai.Completion.create(
model="text-davinci-003",
prompt=generate_prompt(animal),
temperature=0.6,
)
return jsonify(response.choices)
Diff
python
import os
import openai
from openai import Client
from flask import Flask, jsonify
app = Flask(__name__)
openai.api_key = os.getenv("OPENAI_API_KEY")
client = Client(os.getenv("OPENAI_API_KEY"))
@app.route("/chat", methods=("POST"))
def index():
animal = request.form["animal"]
response = openai.Completion.create(
response = client.completions.create(
model="text-davinci-003",
prompt=generate_prompt(animal),
temperature=0.6,
)
return jsonify(response.choices)
Contributed by
Herrington Darkholme, inspired by Morgante from grit.io