mirror of
https://github.com/xtekky/gpt4free.git
synced 2024-12-22 18:41:41 +03:00
Add Authentication Setup Guide
This commit is contained in:
parent
78c20c08a0
commit
fc4fe21199
10
README.md
10
README.md
@ -107,7 +107,7 @@ docker run \
|
||||
hlohaus789/g4f:latest-slim \
|
||||
rm -r -f /app/g4f/ \
|
||||
&& pip install -U g4f[slim] \
|
||||
&& python -m g4f.cli api --gui --debug
|
||||
&& python -m g4f --debug
|
||||
```
|
||||
It also updates the `g4f` package at startup and installs any new required dependencies.
|
||||
|
||||
@ -134,7 +134,7 @@ By following these steps, you should be able to successfully install and run the
|
||||
|
||||
Run the **Webview UI** on other Platforms:
|
||||
|
||||
- [/docs/guides/webview](docs/webview.md)
|
||||
- [/docs/webview](docs/webview.md)
|
||||
|
||||
##### Use your smartphone:
|
||||
|
||||
@ -204,7 +204,7 @@ image_url = response.data[0].url
|
||||
print(f"Generated image URL: {image_url}")
|
||||
```
|
||||
|
||||
[![Image with cat](/docs/cat.jpeg)](docs/client.md)
|
||||
[![Image with cat](/docs/images/cat.jpeg)](docs/client.md)
|
||||
|
||||
#### **Full Documentation for Python API**
|
||||
- **New:**
|
||||
@ -241,6 +241,10 @@ This API is designed for straightforward implementation and enhanced compatibili
|
||||
|
||||
### Configuration
|
||||
|
||||
#### Authentication
|
||||
|
||||
Refer to the [G4F Authentication Setup Guide](docs/authentication.md) for detailed instructions on setting up authentication.
|
||||
|
||||
#### Cookies
|
||||
|
||||
Cookies are essential for using Meta AI and Microsoft Designer to create images.
|
||||
|
@ -145,7 +145,7 @@ async def main():
|
||||
provider=g4f.Provider.CopilotAccount
|
||||
)
|
||||
|
||||
image = requests.get("https://raw.githubusercontent.com/xtekky/gpt4free/refs/heads/main/docs/cat.jpeg", stream=True).raw
|
||||
image = requests.get("https://raw.githubusercontent.com/xtekky/gpt4free/refs/heads/main/docs/images/cat.jpeg", stream=True).raw
|
||||
|
||||
response = await client.chat.completions.create(
|
||||
model=g4f.models.default,
|
||||
|
139
docs/authentication.md
Normal file
139
docs/authentication.md
Normal file
@ -0,0 +1,139 @@
|
||||
# G4F Authentication Setup Guide
|
||||
|
||||
This documentation explains how to set up Basic Authentication for the GUI and API key authentication for the API when running the G4F server.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before proceeding, ensure you have the following installed:
|
||||
- Python 3.x
|
||||
- G4F package installed (ensure it is set up and working)
|
||||
- Basic knowledge of using environment variables on your operating system
|
||||
|
||||
## Steps to Set Up Authentication
|
||||
|
||||
### 1. API Key Authentication for Both GUI and API
|
||||
|
||||
To secure both the GUI and the API, you'll authenticate using an API key. The API key should be injected via an environment variable and passed to both the GUI (via Basic Authentication) and the API.
|
||||
|
||||
#### Steps to Inject the API Key Using Environment Variables:
|
||||
|
||||
1. **Set the environment variable** for your API key:
|
||||
|
||||
On Linux/macOS:
|
||||
```bash
|
||||
export G4F_API_KEY="your-api-key-here"
|
||||
```
|
||||
|
||||
On Windows (Command Prompt):
|
||||
```bash
|
||||
set G4F_API_KEY="your-api-key-here"
|
||||
```
|
||||
|
||||
On Windows (PowerShell):
|
||||
```bash
|
||||
$env:G4F_API_KEY="your-api-key-here"
|
||||
```
|
||||
|
||||
Replace `your-api-key-here` with your actual API key.
|
||||
|
||||
2. **Run the G4F server with the API key injected**:
|
||||
|
||||
Use the following command to start the G4F server. The API key will be passed to both the GUI and the API:
|
||||
|
||||
```bash
|
||||
python -m g4f --debug --port 8080 --g4f-api-key $G4F_API_KEY
|
||||
```
|
||||
|
||||
- `--debug` enables debug mode for more verbose logs.
|
||||
- `--port 8080` specifies the port on which the server will run (you can change this if needed).
|
||||
- `--g4f-api-key` specifies the API key for both the GUI and the API.
|
||||
|
||||
#### Example:
|
||||
|
||||
```bash
|
||||
export G4F_API_KEY="my-secret-api-key"
|
||||
python -m g4f --debug --port 8080 --g4f-api-key $G4F_API_KEY
|
||||
```
|
||||
|
||||
Now, both the GUI and API will require the correct API key for access.
|
||||
|
||||
---
|
||||
|
||||
### 2. Accessing the GUI with Basic Authentication
|
||||
|
||||
The GUI uses **Basic Authentication**, where the **username** can be any value, and the **password** is your API key.
|
||||
|
||||
#### Example:
|
||||
|
||||
To access the GUI, open your web browser and navigate to `http://localhost:8080/chat/`. You will be prompted for a username and password.
|
||||
|
||||
- **Username**: You can use any username (e.g., `user` or `admin`).
|
||||
- **Password**: Enter your API key (the same key you set in the `G4F_API_KEY` environment variable).
|
||||
|
||||
---
|
||||
|
||||
### 3. Python Example for Accessing the API
|
||||
|
||||
To interact with the API, you can send requests by including the `g4f-api-key` in the headers. Here's an example of how to do this using the `requests` library in Python.
|
||||
|
||||
#### Example Code to Send a Request:
|
||||
|
||||
```python
|
||||
import requests
|
||||
|
||||
url = "http://localhost:8080/v1/chat/completions"
|
||||
|
||||
# Body of the request
|
||||
body = {
|
||||
"model": "your-model-name", # Replace with your model name
|
||||
"provider": "your-provider", # Replace with the provider name
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Hello"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
# API Key (can be set as an environment variable)
|
||||
api_key = "your-api-key-here" # Replace with your actual API key
|
||||
|
||||
# Send the POST request
|
||||
response = requests.post(url, json=body, headers={"g4f-api-key": api_key})
|
||||
|
||||
# Check the response
|
||||
print(response.status_code)
|
||||
print(response.json())
|
||||
```
|
||||
|
||||
In this example:
|
||||
- Replace `"your-api-key-here"` with your actual API key.
|
||||
- `"model"` and `"provider"` should be replaced with the appropriate model and provider you're using.
|
||||
- The `messages` array contains the conversation you want to send to the API.
|
||||
|
||||
#### Response:
|
||||
|
||||
The response will contain the output of the API request, such as the model's completion or other relevant data, which you can then process in your application.
|
||||
|
||||
---
|
||||
|
||||
### 4. Testing the Setup
|
||||
|
||||
- **Accessing the GUI**: Open a web browser and navigate to `http://localhost:8080/chat/`. The GUI will now prompt you for a username and password. You can enter any username (e.g., `admin`), and for the password, enter the API key you set up in the environment variable.
|
||||
|
||||
- **Accessing the API**: Use the Python code example above to send requests to the API. Ensure the correct API key is included in the `g4f-api-key` header.
|
||||
|
||||
---
|
||||
|
||||
### 5. Troubleshooting
|
||||
|
||||
- **GUI Access Issues**: If you're unable to access the GUI, ensure that you are using the correct API key as the password.
|
||||
- **API Access Issues**: If the API is rejecting requests, verify that the `G4F_API_KEY` environment variable is correctly set and passed to the server. You can also check the server logs for more detailed error messages.
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
By following the steps above, you will have successfully set up Basic Authentication for the G4F GUI (using any username and the API key as the password) and API key authentication for the API. This ensures that only authorized users can access both the interface and make API requests.
|
||||
|
||||
[Return to Home](/)
|
@ -181,7 +181,7 @@ client = Client(
|
||||
)
|
||||
|
||||
response = client.images.create_variation(
|
||||
image=open("cat.jpg", "rb"),
|
||||
image=open("docs/images/cat.jpg", "rb"),
|
||||
model="dall-e-3",
|
||||
# Add any other necessary parameters
|
||||
)
|
||||
@ -235,7 +235,7 @@ client = Client(
|
||||
)
|
||||
|
||||
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")
|
||||
# Or: image = open("docs/images/cat.jpeg", "rb")
|
||||
|
||||
response = client.chat.completions.create(
|
||||
model=g4f.models.default,
|
||||
|
Before Width: | Height: | Size: 8.5 KiB After Width: | Height: | Size: 8.5 KiB |
Before Width: | Height: | Size: 5.7 KiB After Width: | Height: | Size: 5.7 KiB |
Before Width: | Height: | Size: 8.1 KiB After Width: | Height: | Size: 8.1 KiB |
@ -6,6 +6,7 @@ from aiohttp import ClientSession
|
||||
|
||||
from ..typing import AsyncResult, Messages
|
||||
from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
|
||||
from .. import debug
|
||||
|
||||
class Blackbox2(AsyncGeneratorProvider, ProviderModelMixin):
|
||||
url = "https://www.blackbox.ai"
|
||||
@ -13,7 +14,7 @@ class Blackbox2(AsyncGeneratorProvider, ProviderModelMixin):
|
||||
working = True
|
||||
supports_system_message = True
|
||||
supports_message_history = True
|
||||
|
||||
supports_stream = False
|
||||
default_model = 'llama-3.1-70b'
|
||||
models = [default_model]
|
||||
|
||||
@ -62,8 +63,8 @@ class Blackbox2(AsyncGeneratorProvider, ProviderModelMixin):
|
||||
raise KeyError("'prompt' key not found in the response")
|
||||
except Exception as e:
|
||||
if attempt == max_retries - 1:
|
||||
yield f"Error after {max_retries} attempts: {str(e)}"
|
||||
raise RuntimeError(f"Error after {max_retries} attempts: {str(e)}")
|
||||
else:
|
||||
wait_time = delay * (2 ** attempt) + random.uniform(0, 1)
|
||||
print(f"Attempt {attempt + 1} failed. Retrying in {wait_time:.2f} seconds...")
|
||||
debug.log(f"Attempt {attempt + 1} failed. Retrying in {wait_time:.2f} seconds...")
|
||||
await asyncio.sleep(wait_time)
|
||||
|
@ -305,7 +305,7 @@ class OpenaiChat(AsyncGeneratorProvider, ProviderModelMixin):
|
||||
if not cls.needs_auth:
|
||||
cls._create_request_args(cookies)
|
||||
RequestConfig.proof_token = get_config(cls._headers.get("user-agent"))
|
||||
async with session.get(cls.url, headers=INIT_HEADERS) as response:
|
||||
async with session.get(cls.url, headers=cls._headers) as response:
|
||||
cls._update_request_args(session)
|
||||
await raise_for_status(response)
|
||||
try:
|
||||
@ -538,6 +538,7 @@ class OpenaiChat(AsyncGeneratorProvider, ProviderModelMixin):
|
||||
await page.send(nodriver.cdp.network.enable())
|
||||
page.add_handler(nodriver.cdp.network.RequestWillBeSent, on_request)
|
||||
page = await browser.get(cls.url)
|
||||
await asyncio.sleep(1)
|
||||
body = await page.evaluate("JSON.stringify(window.__remixContext)")
|
||||
if body:
|
||||
match = re.search(r'"accessToken":"(.*?)"', body)
|
||||
|
9
g4f/__main__.py
Normal file
9
g4f/__main__.py
Normal file
@ -0,0 +1,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from .cli import get_api_parser, run_api_args
|
||||
|
||||
parser = get_api_parser()
|
||||
args = parser.parse_args()
|
||||
if args.gui is None:
|
||||
args.gui = True
|
||||
run_api_args(args)
|
@ -23,7 +23,7 @@ from starlette.status import (
|
||||
HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
)
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials, HTTPBasic
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from starlette.responses import FileResponse
|
||||
from pydantic import BaseModel, Field
|
||||
@ -50,7 +50,7 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_PORT = 1337
|
||||
|
||||
def create_app(g4f_api_key: str = None):
|
||||
def create_app():
|
||||
app = FastAPI()
|
||||
|
||||
# Add CORS middleware
|
||||
@ -62,7 +62,7 @@ def create_app(g4f_api_key: str = None):
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
api = Api(app, g4f_api_key=g4f_api_key)
|
||||
api = Api(app)
|
||||
|
||||
if AppConfig.gui:
|
||||
@app.get("/")
|
||||
@ -86,9 +86,14 @@ def create_app(g4f_api_key: str = None):
|
||||
|
||||
return app
|
||||
|
||||
def create_app_debug(g4f_api_key: str = None):
|
||||
def create_app_debug():
|
||||
g4f.debug.logging = True
|
||||
return create_app(g4f_api_key)
|
||||
return create_app()
|
||||
|
||||
def create_app_with_gui_and_debug():
|
||||
g4f.debug.logging = True
|
||||
AppConfig.gui = True
|
||||
return create_app()
|
||||
|
||||
class ChatCompletionsConfig(BaseModel):
|
||||
messages: Messages = Field(examples=[[{"role": "system", "content": ""}, {"role": "user", "content": ""}]])
|
||||
@ -156,8 +161,8 @@ class ErrorResponse(Response):
|
||||
return cls(format_exception(exception, config), status_code)
|
||||
|
||||
@classmethod
|
||||
def from_message(cls, message: str, status_code: int = HTTP_500_INTERNAL_SERVER_ERROR):
|
||||
return cls(format_exception(message), status_code)
|
||||
def from_message(cls, message: str, status_code: int = HTTP_500_INTERNAL_SERVER_ERROR, headers: dict = None):
|
||||
return cls(format_exception(message), status_code, headers=headers)
|
||||
|
||||
def render(self, content) -> bytes:
|
||||
return str(content).encode(errors="ignore")
|
||||
@ -184,26 +189,57 @@ def set_list_ignored_providers(ignored: list[str]):
|
||||
list_ignored_providers = ignored
|
||||
|
||||
class Api:
|
||||
def __init__(self, app: FastAPI, g4f_api_key=None) -> None:
|
||||
def __init__(self, app: FastAPI) -> None:
|
||||
self.app = app
|
||||
self.client = AsyncClient()
|
||||
self.g4f_api_key = g4f_api_key
|
||||
self.get_g4f_api_key = APIKeyHeader(name="g4f-api-key")
|
||||
self.conversations: dict[str, dict[str, BaseConversation]] = {}
|
||||
|
||||
security = HTTPBearer(auto_error=False)
|
||||
basic_security = HTTPBasic()
|
||||
|
||||
async def get_username(self, request: Request):
|
||||
credentials = await self.basic_security(request)
|
||||
current_password_bytes = credentials.password.encode()
|
||||
is_correct_password = secrets.compare_digest(
|
||||
current_password_bytes, AppConfig.g4f_api_key.encode()
|
||||
)
|
||||
if not is_correct_password:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_401_UNAUTHORIZED,
|
||||
detail="Incorrect username or password",
|
||||
headers={"WWW-Authenticate": "Basic"},
|
||||
)
|
||||
return credentials.username
|
||||
|
||||
def register_authorization(self):
|
||||
if AppConfig.g4f_api_key:
|
||||
print(f"Register authentication key: {''.join(['*' for _ in range(len(AppConfig.g4f_api_key))])}")
|
||||
@self.app.middleware("http")
|
||||
async def authorization(request: Request, call_next):
|
||||
if self.g4f_api_key and request.url.path not in ("/", "/v1"):
|
||||
if AppConfig.g4f_api_key is not None:
|
||||
try:
|
||||
user_g4f_api_key = await self.get_g4f_api_key(request)
|
||||
except HTTPException as e:
|
||||
if e.status_code == 403:
|
||||
except HTTPException:
|
||||
user_g4f_api_key = None
|
||||
if request.url.path.startswith("/v1"):
|
||||
if user_g4f_api_key is None:
|
||||
return ErrorResponse.from_message("G4F API key required", HTTP_401_UNAUTHORIZED)
|
||||
if not secrets.compare_digest(self.g4f_api_key, user_g4f_api_key):
|
||||
if not secrets.compare_digest(AppConfig.g4f_api_key, user_g4f_api_key):
|
||||
return ErrorResponse.from_message("Invalid G4F API key", HTTP_403_FORBIDDEN)
|
||||
else:
|
||||
path = request.url.path
|
||||
if user_g4f_api_key is not None and path.startswith("/images/"):
|
||||
if not secrets.compare_digest(AppConfig.g4f_api_key, user_g4f_api_key):
|
||||
return ErrorResponse.from_message("Invalid G4F API key", HTTP_403_FORBIDDEN)
|
||||
elif path.startswith("/backend-api/") or path.startswith("/images/") or path.startswith("/chat/") and path != "/chat/":
|
||||
try:
|
||||
username = await self.get_username(request)
|
||||
except HTTPException as e:
|
||||
return ErrorResponse.from_message(e.detail, e.status_code, e.headers)
|
||||
response = await call_next(request)
|
||||
response.headers["X-Username"] = username
|
||||
return response
|
||||
return await call_next(request)
|
||||
|
||||
def register_validation_exception_handler(self):
|
||||
@ -512,8 +548,12 @@ def run_api(
|
||||
host, port = bind.split(":")
|
||||
if port is None:
|
||||
port = DEFAULT_PORT
|
||||
if AppConfig.gui and debug:
|
||||
method = "create_app_with_gui_and_debug"
|
||||
else:
|
||||
method = "create_app_debug" if debug else "create_app"
|
||||
uvicorn.run(
|
||||
f"g4f.api:create_app{'_debug' if debug else ''}",
|
||||
f"g4f.api:{method}",
|
||||
host=host,
|
||||
port=int(port),
|
||||
workers=workers,
|
||||
|
17
g4f/cli.py
17
g4f/cli.py
@ -1,19 +1,18 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from argparse import ArgumentParser
|
||||
|
||||
from g4f import Provider
|
||||
from g4f.gui.run import gui_parser, run_gui_args
|
||||
import g4f.cookies
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Run gpt4free")
|
||||
subparsers = parser.add_subparsers(dest="mode", help="Mode to run the g4f in.")
|
||||
api_parser = subparsers.add_parser("api")
|
||||
def get_api_parser():
|
||||
api_parser = ArgumentParser(description="Run the API and GUI")
|
||||
api_parser.add_argument("--bind", default=None, help="The bind string. (Default: 0.0.0.0:1337)")
|
||||
api_parser.add_argument("--port", default=None, help="Change the port of the server.")
|
||||
api_parser.add_argument("--port", "-p", default=None, help="Change the port of the server.")
|
||||
api_parser.add_argument("--debug", "-d", action="store_true", help="Enable verbose logging.")
|
||||
api_parser.add_argument("--gui", "-g", default=False, action="store_true", help="Add gui to the api.")
|
||||
api_parser.add_argument("--gui", "-g", default=None, action="store_true", help="Add gui to the api.")
|
||||
api_parser.add_argument("--model", default=None, help="Default model for chat completion. (incompatible with --reload and --workers)")
|
||||
api_parser.add_argument("--provider", choices=[provider.__name__ for provider in Provider.__providers__ if provider.working],
|
||||
default=None, help="Default provider for chat completion. (incompatible with --reload and --workers)")
|
||||
@ -29,6 +28,12 @@ def main():
|
||||
api_parser.add_argument("--cookie-browsers", nargs="+", choices=[browser.__name__ for browser in g4f.cookies.browsers],
|
||||
default=[], help="List of browsers to access or retrieve cookies from. (incompatible with --reload and --workers)")
|
||||
api_parser.add_argument("--reload", action="store_true", help="Enable reloading.")
|
||||
return api_parser
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Run gpt4free")
|
||||
subparsers = parser.add_subparsers(dest="mode", help="Mode to run the g4f in.")
|
||||
subparsers.add_parser("api", parents=[get_api_parser()], add_help=False)
|
||||
subparsers.add_parser("gui", parents=[gui_parser()], add_help=False)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
@ -744,7 +744,11 @@ const delete_conversation = async (conversation_id) => {
|
||||
};
|
||||
|
||||
const set_conversation = async (conversation_id) => {
|
||||
try {
|
||||
history.pushState({}, null, `/chat/${conversation_id}`);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
window.conversation_id = conversation_id;
|
||||
|
||||
await clear_conversation();
|
||||
@ -898,7 +902,11 @@ async function add_conversation(conversation_id, content) {
|
||||
items: [],
|
||||
});
|
||||
}
|
||||
try {
|
||||
history.pushState({}, null, `/chat/${conversation_id}`);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function save_system_message() {
|
||||
@ -1287,23 +1295,29 @@ async function on_api() {
|
||||
|
||||
register_settings_storage();
|
||||
|
||||
try {
|
||||
models = await api("models");
|
||||
models.forEach((model) => {
|
||||
let option = document.createElement("option");
|
||||
option.value = option.text = model;
|
||||
modelSelect.appendChild(option);
|
||||
});
|
||||
|
||||
providers = await api("providers")
|
||||
Object.entries(providers).forEach(([provider, label]) => {
|
||||
let option = document.createElement("option");
|
||||
option.value = provider;
|
||||
option.text = label;
|
||||
providerSelect.appendChild(option);
|
||||
})
|
||||
});
|
||||
await load_provider_models(appStorage.getItem("provider"));
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
if (document.location.pathname == "/chat/") {
|
||||
document.location.href = `/chat/error`;
|
||||
}
|
||||
}
|
||||
|
||||
await load_settings_storage()
|
||||
await load_provider_models(appStorage.getItem("provider"));
|
||||
|
||||
const hide_systemPrompt = document.getElementById("hide-systemPrompt")
|
||||
const slide_systemPrompt_icon = document.querySelector(".slide-systemPrompt i");
|
||||
@ -1465,7 +1479,7 @@ async function api(ressource, args=null, file=null, message_id=null) {
|
||||
const url = `/backend-api/v2/${ressource}`;
|
||||
const headers = {};
|
||||
if (api_key) {
|
||||
headers.authorization = `Bearer ${api_key}`;
|
||||
headers.x_api_key = api_key;
|
||||
}
|
||||
if (ressource == "conversation") {
|
||||
let body = JSON.stringify(args);
|
||||
|
@ -153,7 +153,7 @@ class Backend_Api(Api):
|
||||
return response
|
||||
|
||||
def get_provider_models(self, provider: str):
|
||||
api_key = None if request.authorization is None else request.authorization.token
|
||||
api_key = request.headers.get("x_api_key")
|
||||
models = super().get_provider_models(provider, api_key)
|
||||
if models is None:
|
||||
return "Provider not found", 404
|
||||
|
Loading…
Reference in New Issue
Block a user