The G4F Client API introduces a new way to integrate advanced AI functionalities into your Python applications. This guide will help you transition from using the OpenAI client to the new G4F Client, offering compatibility with the existing OpenAI API alongside additional features.
Switching to G4F Client:
Replace the OpenAI client import statement in your Python code as follows:
Old Import:
from openai import OpenAI
New Import:
from g4f.client import Client as OpenAI
The G4F Client maintains the same API interface as OpenAI, ensuring a seamless transition.
To use the G4F Client, create an instance with customized providers:
from g4f.client import Client
from g4f.Provider import BingCreateImages, OpenaiChat, Gemini
client = Client(
provider=OpenaiChat,
image_provider=Gemini,
proxies=None
)
Text Completions:
You can use the ChatCompletions
endpoint to generate text completions as follows:
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "Say this is a test"}],
...
)
print(response.choices[0].message.content)
Also streaming are supported:
stream = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": "Say this is a test"}],
stream=True,
...
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
Image Generation:
Generate images using a specified prompt:
response = client.images.generate(
model="dall-e-3",
prompt="a white siamese cat",
...
)
image_url = response.data[0].url
Creating Image Variations:
Create variations of an existing image:
response = client.images.create_variation(
image=open("cat.jpg", "rb"),
model="bing",
...
)
image_url = response.data[0].url
Original / Variant:
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。