FURTHER ENHANCE THIS SCRIPT, and make this an automatic real-time auto correction AI system. In a formal style with (nil).
code
import g4f
import re
from flask import Flask, render_template, request, jsonify
from difflib import SequenceMatcher
app = Flask(__name__)
def grammar_correction(text, model="gpt-3.5-turbo", provider=g4f.Provider.DeepInfraChat):
messages = [
{"role": "system", "content": "You are a highly skilled proofreader and grammar expert. Your task is to correct any grammatical errors in the given text while preserving its original meaning and style. Provide only the corrected text without explanations."},
{"role": "user", "content": f"Please correct the grammar in the following text:\n\n{text}"}
]
try:
response = g4f.ChatCompletion.create(
model=model,
provider=provider,
messages=messages,
stream=False
)
return response.strip()
except Exception as e:
print(f"An error occurred: {str(e)}")
return None
def get_diff_indices(text1, text2):
matcher = SequenceMatcher(None, text1, text2)
diff_indices = []
for opcode in matcher.get_opcodes():
if opcode[0] != 'equal':
diff_indices.append((opcode[1], opcode[2], opcode[3], opcode[4]))
return diff_indices
@app.route('/')
def index():
return render_template('index.html')
@app.route('/correct', methods=['POST'])
def correct():
text = request.json['text']
corrected_text = grammar_correction(text)
if corrected_text:
diff_indices = get_diff_indices(text, corrected_text)
return jsonify({
'corrected_text': corrected_text,
'diff_indices': diff_indices
})
else:
return jsonify({'error': 'Failed to get a correction.'}), 400
if __name__ == '__main__':
app.run(debug=True)
Assistant
G4F Docs:
#1:
G4F - Client API
Introduction
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.
Getting Started
Switching to G4F Client:
To begin using the G4F Client, simply update your import statement in your Python code:
Old Import:
python
from openai import OpenAI
New Import:
python
from g4f.client import Client as OpenAI
The G4F Client preserves the same familiar API interface as OpenAI, ensuring a smooth transition process.
Initializing the Client
To utilize the G4F Client, create an new instance. Below is an example showcasing custom providers:
python
from g4f.client import Client
from g4f.Provider import BingCreateImages, OpenaiChat, Gemini
client = Client(
provider=OpenaiChat,
image_provider=Gemini,
...
)
Configuration
You can set an "api_key" for your provider in the client.
And you also have the option to define a proxy for all outgoing requests:
You can use the ChatCompletions endpoint to generate text completions as follows:
python
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:
python
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 or "", end="")
Using RetryProvider provider
Using Phind provider
How can I assist you today?
Advanced example using GeminiProVision
python
from g4f.client import Client
from g4f.Provider.GeminiPro import GeminiPro
client = Client(
api_key="...",
provider=GeminiPro
)
response = client.chat.completions.create(
model="gemini-pro-vision",
messages=[{"role": "user", "content": "What are on this image?"}],
image=open("docs/waterfall.jpeg", "rb")
)
print(response.choices[0].message.content)
code
User: What are on this image?
[image: Waterfall]
code
Bot: There is a waterfall in the middle of a jungle. There is a rainbow over...
Advanced example: A command-line program
python
import g4f
from g4f.client import Client
# Initialize the GPT client with the desired provider
client = Client(provider=g4f.Provider.Bing)
# Initialize an empty conversation history
messages = []
while True:
# Get user input
user_input = input("You: ")
# 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})
except Exception as e:
print(f"An error occurred: {e}")
Return to Home
#2:
Interference openai-proxy API
Run interference API from PyPi package
python
from g4f.api import run_api
run_api()
Run interference API from repo
Run server:
sh
g4f api
or
sh
python -m g4f.api.run
python
from openai import OpenAI
client = OpenAI(
api_key="",
# Change the API base URL to the local interference API
base_url="http://localhost:1337/v1"
)
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "write a poem about a tree"}],
stream=True,
)
if isinstance(response, dict):
# Not streaming
print(response.choices[0].message.content)
else:
# Streaming
for token in response:
content = token.choices[0].delta.content
if content is not None:
print(content, end="", flush=True)
API usage (POST)
Send the POST request to /v1/chat/completions with body containing the model method. This example uses python with requests library:
python
import requests
url = "http://localhost:1337/v1/chat/completions"
body = {
"model": "gpt-3.5-turbo-16k",
"stream": False,
"messages": [
{"role": "assistant", "content": "What can you do?"}
]
}
json_response = requests.post(url, json=body).json().get('choices', [])
for choice in json_response:
print(choice.get('message', {}).get('content', ''))
Return to Home
#3:
G4F - Legacy API
ChatCompletion
python
import g4f
g4f.debug.logging = True # Enable debug logging
g4f.debug.version_check = False # Disable automatic version checking
print(g4f.Provider.Bing.params) # Print supported args for Bing
# Using automatic a provider for the given model
## Streamed completion
response = g4f.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "Hello"}],
stream=True,
)
for message in response:
print(message, flush=True, end='')
## Normal response
response = g4f.ChatCompletion.create(
model=g4f.models.gpt_4,
messages=[{"role": "user", "content": "Hello"}],
) # Alternative model setting
print(response)
Completion
python
import g4f
allowed_models = [
'code-davinci-002',
'text-ada-001',
'text-babbage-001',
'text-curie-001',
'text-davinci-002',
'text-davinci-003'
]
response = g4f.Completion.create(
model='text-davinci-003',
prompt='say this is a test'
)
print(response)
Providers
python
import g4f
# Print all available providers
print([
provider.__name__
for provider in g4f.Provider.__providers__
if provider.working
])
# Execute with a specific provider
response = g4f.ChatCompletion.create(
model="gpt-3.5-turbo",
provider=g4f.Provider.Aichat,
messages=[{"role": "user", "content": "Hello"}],
stream=True,
)
for message in response:
print(message)
Image Upload & Generation
Image upload and generation are supported by three main providers:
Bing & Other GPT-4 Providers: Utilizes Microsoft's Image Creator.
Google Gemini: Available for free accounts with IP addresses outside Europe.
OpenaiChat with GPT-4: Accessible for users with a Plus subscription.
python
import g4f
# Setting up the request for image creation
response = g4f.ChatCompletion.create(
model=g4f.models.default, # Using the default model
provider=g4f.Provider.Gemini, # Specifying the provider as Gemini
messages=[{"role": "user", "content": "Create an image like this"}],
image=open("images/g4f.png", "rb"), # Image input can be a data URI, bytes, PIL Image, or IO object
image_name="g4f.png" # Optional: specifying the filename
)
# Displaying the response
print(response)
from g4f.image import ImageResponse
# Get image links from response
for chunk in g4f.ChatCompletion.create(
model=g4f.models.default, # Using the default model
provider=g4f.Provider.OpenaiChat, # Specifying the provider as OpenaiChat
messages=[{"role": "user", "content": "Create images with dogs"}],
access_token="...", # Need a access token from a plus user
stream=True,
ignore_stream=True
):
if isinstance(chunk, ImageResponse):
print(chunk.images) # Print generated image links
print(chunk.alt) # Print used prompt for image generation
Using Browser
Some providers using a browser to bypass the bot protection. They using the selenium webdriver to control the browser. The browser settings and the login data are saved in a custom directory. If the headless mode is enabled, the browser windows are loaded invisibly. For performance reasons, it is recommended to reuse the browser instances and close them yourself at the end:
python
import g4f
from undetected_chromedriver import Chrome, ChromeOptions
from g4f.Provider import (
Bard,
Poe,
AItianhuSpace,
MyShell,
PerplexityAi,
)
options = ChromeOptions()
options.add_argument("--incognito");
webdriver = Chrome(options=options, headless=True)
for idx in range(10):
response = g4f.ChatCompletion.create(
model=g4f.models.default,
provider=g4f.Provider.MyShell,
messages=[{"role": "user", "content": "Suggest me a name."}],
webdriver=webdriver
)
print(f"{idx}:", response)
webdriver.quit()
Async Support
To enhance speed and overall performance, execute providers asynchronously. The total execution time will be determined by the duration of the slowest provider's execution.
Certainly. Below is the enhanced version of your script, transforming it into an automatic real-time auto-correction AI system using Flask-SocketIO for real-time communication. This implementation ensures a formal style and leverages the RetryProvider for improved reliability.
Server-Side (app.py)
python
import g4f
from g4f.client import Client
from g4f.Provider import RetryProvider, DeepInfraChat, Phind, FreeChatgpt, Liaobots
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
from difflib import SequenceMatcher
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key' # Replace with a secure key
socketio = SocketIO(app, cors_allowed_origins="*")
# Initialize the GPT client with RetryProvider
client = Client(
provider=RetryProvider([DeepInfraChat, Phind, FreeChatgpt, Liaobots], shuffle=True)
)
def grammar_correction(text, model="gpt-3.5-turbo"):
messages = [
{"role": "system", "content": "You are a highly skilled proofreader and grammar expert. Your task is to correct any grammatical errors in the given text while preserving its original meaning and style. Provide only the corrected text without explanations."},
{"role": "user", "content": f"Please correct the grammar in the following text:\n\n{text}"}
]
try:
response = client.chat.completions.create(
model=model,
messages=messages,
stream=False
)
return response.strip()
except Exception as e:
print(f"An error occurred: {str(e)}")
return None
def get_diff_indices(original, corrected):
matcher = SequenceMatcher(None, original, corrected)
diff_indices = []
for opcode in matcher.get_opcodes():
if opcode[0] != 'equal':
diff_indices.append((opcode[1], opcode[2], opcode[3], opcode[4]))
return diff_indices
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('send_text')
def handle_send_text(data):
text = data.get('text', '')
if text:
corrected_text = grammar_correction(text)
if corrected_text:
diff_indices = get_diff_indices(text, corrected_text)
emit('receive_correction', {
'corrected_text': corrected_text,
'diff_indices': diff_indices
})
else:
emit('receive_correction', {'error': 'Failed to get a correction.'})
else:
emit('receive_correction', {'error': 'No text provided.'})
if __name__ == '__main__':
socketio.run(app, debug=False)
Navigate to your project directory and run the Flask application:
sh
python app.py
Access the application by navigating to http://localhost:5000 in your web browser.
Features Implemented
Real-Time Correction: Utilizes Flask-SocketIO to handle real-time communication between the client and server, enabling immediate grammar corrections as the user types.
Debounce Mechanism: Implements a 500ms debounce to prevent excessive requests while typing, enhancing performance and reducing server load.
Diff Highlighting: Highlights the differences between the original and corrected text, providing clear visual feedback to the user.
Robust Provider Selection: Uses RetryProvider with multiple providers (DeepInfraChat, Phind, FreeChatgpt, Liaobots) to ensure reliable grammar corrections by retrying with alternative providers in case of failures.
Error Handling: Gracefully handles errors by informing the user if the correction fails or if no text is provided.
Security Considerations
Secret Key: Replace 'your_secret_key' in app.config['SECRET_KEY'] with a strong, unpredictable secret key to secure your application.
CORS Settings: The cors_allowed_origins="*" setting allows connections from any origin. Adjust this as needed to restrict access to trusted sources.
Final Notes
This enhanced script provides a seamless and efficient real-time grammar correction experience. By leveraging Flask-SocketIO and the robust features of the g4f library, users receive immediate feedback on their text, enhancing their writing quality in a formal and user-friendly interface.