2024-10-15 11:28:33 +03:00
2024-10-19 20:21:14 +03:00
# G4F Client API Guide
## Table of Contents
- [Introduction ](#introduction )
- [Getting Started ](#getting-started )
- [Switching to G4F Client ](#switching-to-g4f-client )
- [Initializing the Client ](#initializing-the-client )
2024-10-25 20:29:03 +03:00
- [Creating Chat Completions ](#creating-chat-completions )
2024-10-19 20:21:14 +03:00
- [Configuration ](#configuration )
- [Usage Examples ](#usage-examples )
- [Text Completions ](#text-completions )
- [Streaming Completions ](#streaming-completions )
- [Image Generation ](#image-generation )
- [Creating Image Variations ](#creating-image-variations )
- [Advanced Usage ](#advanced-usage )
- [Using a List of Providers with RetryProvider ](#using-a-list-of-providers-with-retryprovider )
- [Using a Vision Model ](#using-a-vision-model )
- [Command-line Chat Program ](#command-line-chat-program )
## Introduction
2024-10-29 23:03:05 +03:00
Welcome to the G4F Client API, a cutting-edge tool for seamlessly integrating advanced AI capabilities into your Python applications. This guide is designed to facilitate your transition from using the OpenAI client to the G4F Client, offering enhanced features while maintaining compatibility with the existing OpenAI API.
2024-02-13 12:45:06 +03:00
2024-10-19 20:21:14 +03:00
## Getting Started
### Switching to G4F Client
**To begin using the G4F Client, simply update your import statement in your Python code:**
2024-02-12 13:41:27 +03:00
2024-10-19 20:21:14 +03:00
**Old Import:**
2024-02-12 13:41:27 +03:00
```python
2024-02-13 12:45:06 +03:00
from openai import OpenAI
2024-02-12 13:41:27 +03:00
```
2024-10-19 20:21:14 +03:00
**New Import:**
2024-02-12 13:41:27 +03:00
```python
2024-02-13 13:29:41 +03:00
from g4f.client import Client as OpenAI
2024-02-12 13:41:27 +03:00
```
2024-10-29 23:03:05 +03:00
The G4F Client preserves the same familiar API interface as OpenAI, ensuring a smooth transition process.
2024-02-12 13:41:27 +03:00
2024-10-19 20:21:14 +03:00
## Initializing the Client
To utilize the G4F Client, create a new instance. **Below is an example showcasing custom providers:**
2024-02-12 13:41:27 +03:00
```python
from g4f.client import Client
2024-02-13 13:29:41 +03:00
from g4f.Provider import BingCreateImages, OpenaiChat, Gemini
2024-02-12 13:41:27 +03:00
client = Client(
2024-02-19 21:34:28 +03:00
provider=OpenaiChat,
2024-02-12 13:41:27 +03:00
image_provider=Gemini,
2024-10-15 11:28:33 +03:00
# Add any other necessary parameters
2024-02-22 06:35:11 +03:00
)
```
2024-10-25 20:29:03 +03:00
## Creating Chat Completions
**Here’ s an improved example of creating chat completions:**
```python
response = client.chat.completions.create(
2024-11-12 09:44:48 +03:00
model="gpt-4o-mini",
2024-10-25 20:29:03 +03:00
messages=[
{
"role": "user",
"content": "Say this is a test"
}
]
# Add any other necessary parameters
)
```
**This example:**
- Asks a specific question `Say this is a test`
- Configures various parameters like temperature and max_tokens for more control over the output
- Disables streaming for a complete response
You can adjust these parameters based on your specific needs.
2024-02-22 06:35:11 +03:00
2024-02-23 13:33:38 +03:00
## Configuration
2024-10-19 20:21:14 +03:00
**You can set an `api_key` for your provider in the client and define a proxy for all outgoing requests:**
2024-02-22 06:35:11 +03:00
```python
from g4f.client import Client
client = Client(
2024-10-19 20:21:14 +03:00
api_key="your_api_key_here",
2024-02-22 06:35:11 +03:00
proxies="http://user:pass@host",
2024-10-15 11:28:33 +03:00
# Add any other necessary parameters
2024-02-12 13:41:27 +03:00
)
```
2024-10-19 20:21:14 +03:00
## Usage Examples
### Text Completions
**Generate text completions using the `ChatCompletions` endpoint:**
2024-02-21 19:02:54 +03:00
```python
2024-10-15 11:28:33 +03:00
from g4f.client import Client
2024-10-15 13:58:09 +03:00
client = Client()
2024-10-19 20:21:14 +03:00
2024-02-21 19:02:54 +03:00
response = client.chat.completions.create(
2024-11-12 09:44:48 +03:00
model="gpt-4o-mini",
2024-10-19 20:21:14 +03:00
messages=[
{
"role": "user",
"content": "Say this is a test"
}
]
2024-10-15 11:28:33 +03:00
# Add any other necessary parameters
2024-02-21 19:02:54 +03:00
)
2024-10-19 20:21:14 +03:00
2024-02-21 19:02:54 +03:00
print(response.choices[0].message.content)
```
2024-10-19 20:21:14 +03:00
### Streaming Completions
**Process responses incrementally as they are generated:**
2024-02-12 13:41:27 +03:00
```python
2024-10-15 11:28:33 +03:00
from g4f.client import Client
client = Client()
2024-10-19 20:21:14 +03:00
2024-02-12 13:41:27 +03:00
stream = client.chat.completions.create(
model="gpt-4",
2024-10-19 20:21:14 +03:00
messages=[
{
"role": "user",
"content": "Say this is a test"
}
],
2024-02-12 13:41:27 +03:00
stream=True,
)
2024-10-15 11:28:33 +03:00
2024-02-12 13:41:27 +03:00
for chunk in stream:
2024-02-13 12:45:06 +03:00
if chunk.choices[0].delta.content:
2024-02-23 13:33:38 +03:00
print(chunk.choices[0].delta.content or "", end="")
2024-02-12 13:41:27 +03:00
```
2024-10-19 20:21:14 +03:00
### Image Generation
**Generate images using a specified prompt:**
2024-02-12 13:41:27 +03:00
```python
2024-10-15 11:28:33 +03:00
from g4f.client import Client
client = Client()
2024-10-19 20:21:14 +03:00
2024-02-12 13:41:27 +03:00
response = client.images.generate(
2024-10-28 11:36:45 +03:00
model="flux",
2024-10-19 20:21:14 +03:00
prompt="a white siamese cat"
2024-10-15 11:28:33 +03:00
# Add any other necessary parameters
2024-02-12 13:41:27 +03:00
)
image_url = response.data[0].url
2024-10-19 20:21:14 +03:00
2024-10-15 11:28:33 +03:00
print(f"Generated image URL: {image_url}")
2024-02-12 13:41:27 +03:00
```
2024-10-28 11:36:45 +03:00
#### Base64 Response Format
```python
from g4f.client import Client
client = Client()
response = client.images.generate(
model="flux",
prompt="a white siamese cat",
response_format="b64_json"
)
base64_text = response.data[0].b64_json
print(base64_text)
```
2024-10-19 20:21:14 +03:00
### Creating Image Variations
**Create variations of an existing image:**
2024-02-12 13:41:27 +03:00
```python
2024-10-15 11:28:33 +03:00
from g4f.client import Client
2024-12-01 00:11:18 +03:00
from g4f.Provider import OpenaiChat
2024-10-15 11:28:33 +03:00
2024-12-01 00:11:18 +03:00
client = Client(
image_provider=OpenaiChat
)
2024-10-19 20:21:14 +03:00
2024-02-12 13:41:27 +03:00
response = client.images.create_variation(
2024-02-13 12:45:06 +03:00
image=open("cat.jpg", "rb"),
2024-12-01 00:11:18 +03:00
model="dall-e-3",
2024-10-15 11:28:33 +03:00
# Add any other necessary parameters
2024-02-12 13:41:27 +03:00
)
image_url = response.data[0].url
2024-10-19 20:21:14 +03:00
2024-10-15 11:28:33 +03:00
print(f"Generated image URL: {image_url}")
2024-02-12 13:41:27 +03:00
```
2024-02-12 14:08:08 +03:00
2024-10-19 20:21:14 +03:00
## Advanced Usage
2024-02-23 19:21:10 +03:00
2024-10-19 20:21:14 +03:00
### Using a List of Providers with RetryProvider
2024-02-23 19:21:10 +03:00
```python
from g4f.client import Client
from g4f.Provider import RetryProvider, Phind, FreeChatgpt, Liaobots
import g4f.debug
2024-10-19 20:21:14 +03:00
2024-02-23 19:21:10 +03:00
g4f.debug.logging = True
2024-10-15 11:28:33 +03:00
g4f.debug.version_check = False
2024-02-23 19:21:10 +03:00
client = Client(
provider=RetryProvider([Phind, FreeChatgpt, Liaobots], shuffle=False)
)
2024-10-19 20:21:14 +03:00
2024-02-23 19:21:10 +03:00
response = client.chat.completions.create(
model="",
2024-10-19 20:21:14 +03:00
messages=[
{
"role": "user",
"content": "Hello"
}
]
2024-02-23 19:21:10 +03:00
)
2024-10-19 20:21:14 +03:00
print(response.choices[0].message.content)
2024-02-23 19:21:10 +03:00
```
2024-10-19 20:21:14 +03:00
2024-12-01 19:31:05 +03:00
### Using a Vision Model
**Analyze an image and generate a description:**
2024-02-23 13:33:38 +03:00
```python
2024-12-01 19:31:05 +03:00
import g4f
import requests
2024-02-23 13:33:38 +03:00
from g4f.client import Client
from g4f.Provider.GeminiPro import GeminiPro
2024-12-01 19:31:05 +03:00
# Initialize the GPT client with the desired provider and api key
2024-02-23 13:33:38 +03:00
client = Client(
2024-10-19 20:21:14 +03:00
api_key="your_api_key_here",
2024-02-23 13:33:38 +03:00
provider=GeminiPro
)
2024-10-19 20:21:14 +03:00
2024-10-15 11:28:33 +03:00
image = requests.get("https://raw.githubusercontent.com/xtekky/gpt4free/refs/heads/main/docs/cat.jpeg", stream=True).raw
# Or: image = open("docs/cat.jpeg", "rb")
response = client.chat.completions.create(
model=g4f.models.default,
2024-10-19 20:21:14 +03:00
messages=[
{
"role": "user",
"content": "What are on this image?"
}
],
image=image
2024-10-15 11:28:33 +03:00
# Add any other necessary parameters
)
2024-10-19 20:21:14 +03:00
2024-10-15 11:28:33 +03:00
print(response.choices[0].message.content)
```
2024-10-19 20:21:14 +03:00
## Command-line Chat Program
**Here's an example of a simple command-line chat program using the G4F Client:**
2024-04-06 04:15:04 +03:00
```python
import g4f
from g4f.client import Client
# Initialize the GPT client with the desired provider
2024-10-15 11:28:33 +03:00
client = Client()
2024-04-06 04:15:04 +03:00
# Initialize an empty conversation history
messages = []
while True:
# Get user input
user_input = input("You: ")
2024-10-19 20:21:14 +03:00
2024-04-06 04:15:04 +03:00
# Check if the user wants to exit the chat
if user_input.lower() == "exit":
print("Exiting chat...")
break # Exit the loop to end the conversation
# Update the conversation history with the user's message
messages.append({"role": "user", "content": user_input})
try:
# Get GPT's response
response = client.chat.completions.create(
messages=messages,
model=g4f.models.default,
)
# Extract the GPT response and print it
gpt_response = response.choices[0].message.content
print(f"Bot: {gpt_response}")
# Update the conversation history with GPT's response
messages.append({"role": "assistant", "content": gpt_response})
2024-10-19 20:21:14 +03:00
2024-04-06 04:15:04 +03:00
except Exception as e:
print(f"An error occurred: {e}")
```
2024-10-19 20:21:14 +03:00
This guide provides a comprehensive overview of the G4F Client API, demonstrating its versatility in handling various AI tasks, from text generation to image analysis and creation. By leveraging these features, you can build powerful and responsive applications that harness the capabilities of advanced AI models.
2024-04-06 04:15:04 +03:00
2024-10-19 20:21:14 +03:00
---
2024-10-15 11:28:33 +03:00
[Return to Home ](/ )