FURTHER ENHANCE THIS SCRIPT, and make this an automatic real-time auto correction AI system. In  a formal style with (nil).

```
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)
```

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:

```python
from g4f.client import Client

client = Client(
    api_key="...",
    proxies="http://user:pass@host",
    ...
)
```

#### Usage Examples

**Text Completions:**

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="")
```

**Image Generation:**

Generate images using a specified prompt:

```python
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:

```python
response = client.images.create_variation(
    image=open("cat.jpg", "rb"),
    model="bing",
    ...
)

image_url = response.data[0].url
```
Original / Variant:

[![Original Image](/docs/cat.jpeg)](/docs/client.md) [![Variant Image](/docs/cat.webp)](/docs/client.md)

#### Use a list of providers with RetryProvider

```python
from g4f.client import Client
from g4f.Provider import RetryProvider, Phind, FreeChatgpt, Liaobots

import g4f.debug
g4f.debug.logging = True

client = Client(
    provider=RetryProvider([Phind, FreeChatgpt, Liaobots], shuffle=False)
)
response = client.chat.completions.create(
    model="",
    messages=[{"role": "user", "content": "Hello"}],
)
print(response.choices[0].message.content)
```

```
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)
```
```
User: What are on this image?
```
![Waterfall](/docs/waterfall.jpeg)

```
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.

```python
import g4f
import asyncio

_providers = [
    g4f.Provider.Aichat,
    g4f.Provider.ChatBase,
    g4f.Provider.Bing,
    g4f.Provider.GptGo,
    g4f.Provider.You,
    g4f.Provider.Yqcloud,
]

async def run_provider(provider: g4f.Provider.BaseProvider):
    try:
        response = await g4f.ChatCompletion.create_async(
            model=g4f.models.default,
            messages=[{"role": "user", "content": "Hello"}],
            provider=provider,
        )
        print(f"{provider.__name__}:", response)
    except Exception as e:
        print(f"{provider.__name__}:", e)
        
async def run_all():
    calls = [
        run_provider(provider) for provider in _providers
    ]
    await asyncio.gather(*calls)

asyncio.run(run_all())
```

##### Proxy and Timeout Support

All providers support specifying a proxy and increasing timeout in the create functions.

```python
import g4f

response = g4f.ChatCompletion.create(
    model=g4f.models.default,
    messages=[{"role": "user", "content": "Hello"}],
    proxy="http://host:port",
    # or socks5://user:pass@host:port
    timeout=120,  # in secs
)

print(f"Result:", response)
```

[Return to Home](/)