Overview
Some providers require authentication or cookies to access their API. This guide will show you how to set cookies and authenticate with these providers in the g4f
package.
Setting Cookies
Setting Cookies for a Provider
To set cookies for a specific provider, you can use the set_cookies
function from the g4f.cookies
module:
The set_cookies
function takes two arguments:
The domain name of the provider (e.g. .bing.com
, .google.com
)
A dictionary of cookie names and values
Make sure to set the correct domain and provide the necessary cookie values required by the provider.
Authentication
Authenticating with a Provider
Some providers like OpenAI require an access token for authentication. You can pass the access token when creating a completion:
Use the auth
parameter and provide your access token as a string.
Automatically Reading Cookies
The g4f
package can automatically read cookies from your web browser using the browser_cookie3
library.
Make sure you have logged into the provider’s website on your browser for this to work.
It supports reading cookies from the following browsers:
Google Chrome
Microsoft Edge
Mozilla Firefox
Opera
Brave
No additional configuration is needed. The package will attempt to read the required cookies automatically.
Troubleshooting
If the cookies are not being set properly, make sure:
You are using the correct domain name
The cookie names and values are accurate
You have the necessary permissions to set cookies
If you encounter authentication errors, double check that:
Your access token is valid and not expired
You are passing the token in the auth
parameter
The provider supports authentication via access tokens
Example
Here’s an example of setting cookies and using authentication:
By setting the appropriate cookies and providing authentication, you can successfully use providers that require them.
Conclusion
Adding cookies and authentication is straightforward with the g4f
package. Use the set_cookies
function to manually set cookies or let the package automatically read them from your browser. For providers needing authentication, pass your access token using the auth
parameter.