自学内容网 自学内容网

学习最佳实践G4F中的编程技术:获得项目的pypi版本和获得github版本

获得项目的pypi版本

要获得pypi的版本,主要是从pypi网站获取信息,然后再从信息中获得版本信息
获得信息:

import requests
package_name = "g4f"
response = requests.get(f"https://pypi.org/pypi/{package_name}/json").json()


然后返回版本信息:

return response["info"]["version"]


返回json信息,根就是info,然后再拿version即可。

如果直接https://pypi/org/pypi/g4f ,则可浏览g4f的pypi主页,带上json:https://pypi.org/pypi/g4f/json,返回的是json字符串。在python中可以使用.json()转换为json格式,然后使用response["info"]["version"] 获得具体版本。

返回所有字符串为:

{"info":{"author":"Tekky","author_email":"<support@g4f.ai>","bugtrack_url":null,"classifiers":["Development Status :: 2 - Pre-Alpha","Intended Audience :: Developers","Operating System :: MacOS :: MacOS X","Operating System :: Microsoft :: Windows","Operating System :: Unix","Programming Language :: Python :: 3"],"description":"\n![248433934-7886223b-c1d1-4260-82aa-da5741f303bb](https://github.com/xtekky/gpt4free/assets/98614666/ea012c87-76e0-496a-8ac4-e2de090cc6c9)\n\n<a href=\"https://trendshift.io/repositories/1692\" target=\"_blank\"><img src=\"https://trendshift.io/api/badge/repositories/1692\" alt=\"xtekky%2Fgpt4free | Trendshift\" style=\"width: 250px; height: 55px;\" width=\"250\" height=\"55\"/></a>\n\n---\n\nWritten by [@xtekky](https://github.com/xtekky) & maintained by [@hlohaus](https://github.com/hlohaus)\n\n<div id=\"top\"></div>\n\n> By using this repository or any code related to it, you agree to the [legal notice](https://github.com/xtekky/gpt4free/blob/main/LEGAL_NOTICE.md). The author is **not responsible for the usage of this repository nor endorses it**, nor is the author responsible for any copies, forks, re-uploads made by other users, or anything else related to GPT4Free. This is the author's only account and repository. To prevent impersonation or irresponsible actions, please comply with the GNU GPL license this Repository uses.\n\n> [!Warning] > _\"gpt4free\"_ serves as a **PoC** (proof of concept), demonstrating the development of an API package with multi-provider requests, with features like timeouts, load balance and flow control.\n\n> [!Note] > <sup><strong>Lastet version:</strong></sup> [![PyPI version](https://img.shields.io/pypi/v/g4f?color=blue)](https://pypi.org/project/g4f) [![Docker version](https://img.shields.io/docker/v/hlohaus789/g4f?label=docker&color=blue)](https://hub.docker.com/r/hlohaus789/g4f)  \n> <sup><strong>Stats:</strong></sup> [![Downloads](https://static.pepy.tech/badge/g4f)](https://pepy.tech/project/g4f) [![Downloads](https://static.pepy.tech/badge/g4f/month)](https://pepy.tech/project/g4f)\n\n```sh\npip install -U g4f\n```\n\n```sh\ndocker pull hlohaus789/g4f\n```\n\n## 🆕 What's New\n\n- Added `gpt-4o`, simply use `gpt-4o` in `chat.completion.create`.\n- Installation Guide for Windows (.exe): 💻 [#installation-guide-for-windows](#installation-guide-for-windows-exe)\n- Join our Telegram Channel: 📨 [telegram.me/g4f_channel](https://telegram.me/g4f_channel)\n- Join our Discord Group: 💬 [discord.gg/XfybzPXPH5](https://discord.gg/XfybzPXPH5)\n- `g4f` now supports 100% local inference: 🧠 [local-docs](https://g4f.mintlify.app/docs/core/usage/local)\n\n## 🔻 Site Takedown\n\nIs your site on this repository and you want to take it down? Send an email to takedown@g4f.ai with proof it is yours and it will be removed as fast as possible. To prevent reproduction please secure your API. 😉\n\n## 🚀 Feedback and Todo\n\nYou can always leave some feedback here: https://forms.gle/FeWV9RLEedfdkmFN6\n\nAs per the survey, here is a list of improvements to come\n\n- [x] Update the repository to include the new openai library syntax (ex: `Openai()` class) | completed, use `g4f.client.Client`\n- [ ] Golang implementation\n- [ ] 🚧 Improve Documentation (in /docs & Guides, Howtos, & Do video tutorials)\n- [x] Improve the provider status list & updates\n- [ ] Tutorials on how to reverse sites to write your own wrapper (PoC only ofc)\n- [x] Improve the Bing wrapper. (Wait and Retry or reuse conversation)\n- [ ] 🚧 Write a standard provider performance test to improve the stability\n- [ ] Potential support and development of local models\n- [ ] 🚧 Improve compatibility and error handling\n\n## 📚 Table of Contents\n\n- [🆕 What's New](#-whats-new)\n- [📚 Table of Contents](#-table-of-contents)\n- [🛠️ Getting Started](#-getting-started)\n  - [Docker Container Guide](#docker-container-guide)\n  - [Installation Guide for Windows (.exe)](#installation-guide-for-windows-exe)\n  - [Use python](#use-python)\n    - [Prerequisites](#prerequisites)\n    - [Install using PyPI package:](#install-using-pypi-package)\n    - [Install from source:](#install-from-source)\n    - [Install using Docker:](#install-using-docker)\n- [💡 Usage](#-usage)\n  - [Text Generation](#text-generation)\n  - [Image Generation](#image-generation)\n  - [Web UI](#web-ui)\n  - [Interference API](#interference-api)\n  - [Configuration](#configuration)\n- [🚀 Providers and Models](#-providers-and-models)\n  - [GPT-4](#gpt-4)\n  - [GPT-3.5](#gpt-35)\n  - [Other](#other)\n  - [Models](#models)\n- [🔗 Powered by gpt4free](#-powered-by-gpt4free)\n- [🤝 Contribute](#-contribute)\n  - [How do i create a new Provider?](#guide-how-do-i-create-a-new-provider)\n  - [How can AI help me with writing code?](#guide-how-can-ai-help-me-with-writing-code)\n- [🙌 Contributors](#-contributors)\n- [©️ Copyright](#-copyright)\n- [⭐ Star History](#-star-history)\n- [📄 License](#-license)\n\n## 🛠️ Getting Started\n\n#### Docker Container Guide\n\n##### Getting Started Quickly:\n\n1. **Install Docker:** Begin by [downloading and installing Docker](https://docs.docker.com/get-docker/).\n\n2. **Set Up the Container:**\n   Use the following commands to pull the latest image and start the container:\n\n```sh\ndocker pull hlohaus789/g4f\ndocker run \\\n  -p 8080:8080 -p 1337:1337 -p 7900:7900 \\\n  --shm-size=\"2g\" \\\n  -v ${PWD}/har_and_cookies:/app/har_and_cookies \\\n  -v ${PWD}/generated_images:/app/generated_images \\\n  hlohaus789/g4f:latest\n```\n\n3. **Access the Client:**\n\n   - To use the included client, navigate to: [http://localhost:8080/chat/](http://localhost:8080/chat/)\n   - Or set the API base for your client to: [http://localhost:1337/v1](http://localhost:1337/v1)\n\n4. **(Optional) Provider Login:**\n   If required, you can access the container's desktop here: http://localhost:7900/?autoconnect=1&resize=scale&password=secret for provider login purposes.\n\n#### Installation Guide for Windows (.exe)\n\nTo ensure the seamless operation of our application, please follow the instructions below. These steps are designed to guide you through the installation process on Windows operating systems.\n\n### Installation Steps\n\n1. **Download the Application**: Visit our [releases page](https://github.com/xtekky/gpt4free/releases/tag/0.3.1.7) and download the most recent version of the application, named `g4f.exe.zip`.\n2. **File Placement**: After downloading, locate the `.zip` file in your Downloads folder. Unpack it to a directory of your choice on your system, then execute the `g4f.exe` file to run the app.\n3. **Open GUI**: The app starts a web server with the GUI. Open your favorite browser and navigate to `http://localhost:8080/chat/` to access the application interface.\n4. **Firewall Configuration (Hotfix)**: Upon installation, it may be necessary to adjust your Windows Firewall settings to allow the application to operate correctly. To do this, access your Windows Firewall settings and allow the application.\n\nBy following these steps, you should be able to successfully install and run the application on your Windows system. If you encounter any issues during the installation process, please refer to our Issue Tracker or try to get contact over Discord for assistance.\n\nRun the **Webview UI** on other Platfroms:\n\n- [/docs/guides/webview](https://github.com/xtekky/gpt4free/blob/main/docs/webview.md)\n\n##### Use your smartphone:\n\nRun the Web UI on Your Smartphone:\n\n- [/docs/guides/phone](https://github.com/xtekky/gpt4free/blob/main/docs/guides/phone.md)\n\n#### Use python\n\n##### Prerequisites:\n\n1. [Download and install Python](https://www.python.org/downloads/) (Version 3.10+ is recommended).\n2. [Install Google Chrome](https://www.google.com/chrome/) for providers with webdriver\n\n##### Install using PyPI package:\n\n```\npip install -U g4f[all]\n```\n\nHow do I install only parts or do disable parts?\nUse partial requirements: [/docs/requirements](https://github.com/xtekky/gpt4free/blob/main/docs/requirements.md)\n\n##### Install from source:\n\nHow do I load the project using git and installing the project requirements?\nRead this tutorial and follow it step by step: [/docs/git](https://github.com/xtekky/gpt4free/blob/main/docs/git.md)\n\n##### Install using Docker:\n\nHow do I build and run composer image from source?\nUse docker-compose: [/docs/docker](https://github.com/xtekky/gpt4free/blob/main/docs/docker.md)\n\n## 💡 Usage\n\n#### Text Generation\n\n```python\nfrom g4f.client import Client\n\nclient = Client()\nresponse = client.chat.completions.create(\n    model=\"gpt-3.5-turbo\",\n    messages=[{\"role\": \"user\", \"content\": \"Hello\"}],\n    ...\n)\nprint(response.choices[0].message.content)\n```\n\n```\nHello! How can I assist you today?\n```\n\n#### Image Generation\n\n```python\nfrom g4f.client import Client\n\nclient = Client()\nresponse = client.images.generate(\n  model=\"gemini\",\n  prompt=\"a white siamese cat\",\n  ...\n)\nimage_url = response.data[0].url\n```\n\n[![Image with cat](/docs/cat.jpeg)](https://github.com/xtekky/gpt4free/blob/main/docs/client.md)\n\n**Full Documentation for Python API**\n\n- New AsyncClient API from G4F: [/docs/async_client](https://github.com/xtekky/gpt4free/blob/main/docs/async_client.md)\n- Client API like the OpenAI Python library: [/docs/client](https://github.com/xtekky/gpt4free/blob/main/docs/client.md)\n- Legacy API with python modules: [/docs/legacy](https://github.com/xtekky/gpt4free/blob/main/docs/legacy.md)\n\n#### Web UI\n\nTo start the web interface, type the following codes in python:\n\n```python\nfrom g4f.gui import run_gui\nrun_gui()\n```\n\nor execute the following command:\n\n```bash\npython -m g4f.cli gui -port 8080 -debug\n```\n\n#### Interference API\n\nYou can use the Interference API to serve other OpenAI integrations with G4F.\n\nSee docs: [/docs/interference](https://github.com/xtekky/gpt4free/blob/main/docs/interference.md)\n\nAccess with: http://localhost:1337/v1\n\n### Configuration\n\n#### Cookies\n\nCookies are essential for using Meta AI and Microsoft Designer to create images.\nAdditionally, cookies are required for the Google Gemini and WhiteRabbitNeo Provider.\nFrom Bing, ensure you have the \"\\_U\" cookie, and from Google, all cookies starting with \"\\_\\_Secure-1PSID\" are needed.\n\nYou can pass these cookies directly to the create function or set them using the `set_cookies` method before running G4F:\n\n```python\nfrom g4f.cookies import set_cookies\n\nset_cookies(\".bing.com\", {\n  \"_U\": \"cookie value\"\n})\n\nset_cookies(\".google.com\", {\n  \"__Secure-1PSID\": \"cookie value\"\n})\n```\n\n#### Using .har and Cookie Files\n\nYou can place `.har` and cookie files in the default `./har_and_cookies` directory. To export a cookie file, use the [EditThisCookie Extension](https://chromewebstore.google.com/detail/editthiscookie/fngmhnnpilhplaeedifhccceomclgfbg) available on the Chrome Web Store.\n\n#### Creating .har Files to Capture Cookies\n\nTo capture cookies, you can also create `.har` files. For more details, refer to the next section.\n\n#### Changing the Cookies Directory and Loading Cookie Files in Python\n\nYou can change the cookies directory and load cookie files in your Python environment. To set the cookies directory relative to your Python file, use the following code:\n\n```python\nimport os.path\nfrom g4f.cookies import set_cookies_dir, read_cookie_files\n\nimport g4f.debug\ng4f.debug.logging = True\n\ncookies_dir = os.path.join(os.path.dirname(__file__), \"har_and_cookies\")\nset_cookies_dir(cookies_dir)\nread_cookie_files(cookies_dir)\n```\n\n### Debug Mode\n\nIf you enable debug mode, you will see logs similar to the following:\n\n```\nRead .har file: ./har_and_cookies/you.com.har\nCookies added: 10 from .you.com\nRead cookie file: ./har_and_cookies/google.json\nCookies added: 16 from .google.com\n```\n\n#### .HAR File for OpenaiChat Provider\n\n##### Generating a .HAR File\n\nTo utilize the OpenaiChat provider, a .har file is required from https://chatgpt.com/. Follow the steps below to create a valid .har file:\n\n1. Navigate to https://chatgpt.com/ using your preferred web browser and log in with your credentials.\n2. Access the Developer Tools in your browser. This can typically be done by right-clicking the page and selecting \"Inspect,\" or by pressing F12 or Ctrl+Shift+I (Cmd+Option+I on a Mac).\n3. With the Developer Tools open, switch to the \"Network\" tab.\n4. Reload the website to capture the loading process within the Network tab.\n5. Initiate an action in the chat which can be captured in the .har file.\n6. Right-click any of the network activities listed and select \"Save all as HAR with content\" to export the .har file.\n\n##### Storing the .HAR File\n\n- Place the exported .har file in the `./har_and_cookies` directory if you are using Docker. Alternatively, you can store it in any preferred location within your current working directory.\n\nNote: Ensure that your .har file is stored securely, as it may contain sensitive information.\n\n#### Using Proxy\n\nIf you want to hide or change your IP address for the providers, you can set a proxy globally via an environment variable:\n\n- On macOS and Linux:\n\n```bash\nexport G4F_PROXY=\"http://host:port\"\n```\n\n- On Windows:\n\n```bash\nset G4F_PROXY=http://host:port\n```\n\n## 🚀 Providers and Models\n\n### GPT-4\n\n| Website                                | Provider                  | GPT-3.5 | GPT-4 | Stream | Status                                                     | Auth  |\n| -------------------------------------- | ------------------------- | ------- | ----- | ------ | ---------------------------------------------------------- | ----- |\n| [bing.com](https://bing.com/chat)      | `g4f.Provider.Bing`       | ❌      | ✔️    | ✔️     | ![Active](https://img.shields.io/badge/Active-brightgreen) | ❌    |\n| [chatgpt.ai](https://chatgpt.ai)       | `g4f.Provider.ChatgptAi`  | ❌      | ✔️    | ✔️     | ![Unknown](https://img.shields.io/badge/Unknown-grey)      | ❌    |\n| [liaobots.site](https://liaobots.site) | `g4f.Provider.Liaobots`   | ✔️      | ✔️    | ✔️     | ![Unknown](https://img.shields.io/badge/Unknown-grey)      | ❌    |\n| [chatgpt.com](https://chatgpt.com)     | `g4f.Provider.OpenaiChat` | ✔️      | ✔️    | ✔️     | ![Active](https://img.shields.io/badge/Active-brightgreen) | ❌+✔️ |\n| [raycast.com](https://raycast.com)     | `g4f.Provider.Raycast`    | ✔️      | ✔️    | ✔️     | ![Unknown](https://img.shields.io/badge/Unknown-grey)      | ✔️    |\n| [beta.theb.ai](https://beta.theb.ai)   | `g4f.Provider.Theb`       | ✔️      | ✔️    | ✔️     | ![Unknown](https://img.shields.io/badge/Unknown-grey)      | ❌    |\n| [you.com](https://you.com)             | `g4f.Provider.You`        | ✔️      | ✔️    | ✔️     | ![Active](https://img.shields.io/badge/Active-brightgreen) | ❌    |\n\n## Best OpenSource Models\n\nWhile we wait for gpt-5, here is a list of new models that are at least better than gpt-3.5-turbo. **Some are better than gpt-4**. Expect this list to grow.\n\n| Website                                                                                  | Provider                            | parameters        | better than        |\n| ---------------------------------------------------------------------------------------- | ----------------------------------- | ----------------- | ------------------ |\n| [claude-3-opus](https://anthropic.com/)                                                  | `g4f.Provider.You`                  | ?B                | gpt-4-0125-preview |\n| [command-r+](https://txt.cohere.com/command-r-plus-microsoft-azure/)                     | `g4f.Provider.HuggingChat`          | 104B              | gpt-4-0314         |\n| [llama-3-70b](https://meta.ai/)                                                          | `g4f.Provider.Llama` or `DeepInfra` | 70B               | gpt-4-0314         |\n| [claude-3-sonnet](https://anthropic.com/)                                                | `g4f.Provider.You`                  | ?B                | gpt-4-0314         |\n| [reka-core](https://chat.reka.ai/)                                                       | `g4f.Provider.Reka`                 | 21B               | gpt-4-vision       |\n| [dbrx-instruct](https://www.databricks.com/blog/introducing-dbrx-new-state-

获得项目的github版本


获得github版本,主要是用如下两句:

import requests
GITHUB_REPOSITORY = "xtekky/gpt4free"
response = requests.get(f"https://api.github.com/repos/{repo}/releases/latest").json()

然后再从json里取出tag_name即可

return response["tag_name"]

也就是从https://api.github.com/repos/xtekky/gpt4free/releases/latest
获得项目信息,然后用.json()转为json格式,最后使用response["tag_name"]拿到版本信息
比如现在拿到的版本号是0.3.2.7

返回字符串的所有信息:

{
  "url": "https://api.github.com/repos/xtekky/gpt4free/releases/175141934",
  "assets_url": "https://api.github.com/repos/xtekky/gpt4free/releases/175141934/assets",
  "upload_url": "https://uploads.github.com/repos/xtekky/gpt4free/releases/175141934/assets{?name,label}",
  "html_url": "https://github.com/xtekky/gpt4free/releases/tag/0.3.2.7",
  "id": 175141934,
  "author": {
    "login": "xtekky",
    "id": 98614666,
    "node_id": "U_kgDOBeC9ig",
    "avatar_url": "https://avatars.githubusercontent.com/u/98614666?v=4",
    "gravatar_id": "",
    "url": "https://api.github.com/users/xtekky",
    "html_url": "https://github.com/xtekky",
    "followers_url": "https://api.github.com/users/xtekky/followers",
    "following_url": "https://api.github.com/users/xtekky/following{/other_user}",
    "gists_url": "https://api.github.com/users/xtekky/gists{/gist_id}",
    "starred_url": "https://api.github.com/users/xtekky/starred{/owner}{/repo}",
    "subscriptions_url": "https://api.github.com/users/xtekky/subscriptions",
    "organizations_url": "https://api.github.com/users/xtekky/orgs",
    "repos_url": "https://api.github.com/users/xtekky/repos",
    "events_url": "https://api.github.com/users/xtekky/events{/privacy}",
    "received_events_url": "https://api.github.com/users/xtekky/received_events",
    "type": "User",
    "site_admin": false
  },
  "node_id": "RE_kwDOJQK9zM4KcHQu",
  "tag_name": "0.3.2.7",
  "target_commitish": "main",
  "name": "g4f v-0.3.2.7",
  "draft": false,
  "prerelease": false,
  "created_at": "2024-09-15T22:37:30Z",
  "published_at": "2024-09-15T22:40:40Z",
  "assets": [

  ],
  "tarball_url": "https://api.github.com/repos/xtekky/gpt4free/tarball/0.3.2.7",
  "zipball_url": "https://api.github.com/repos/xtekky/gpt4free/zipball/0.3.2.7",
  "body": "Thank you so much for 60k stars !!!\r\n\r\ng4f is fully operative.\r\n<img width=\"867\" alt=\"image\" src=\"https://github.com/user-attachments/assets/9f44b54f-e903-4095-b8d3-b696203fc020\">\r\n\r\n## What's Changed\r\n* Provider updates and optimizations across multiple modules by @kqlio67 in https://github.com/xtekky/gpt4free/pull/2220\r\n\r\n\r\n**Full Changelog**: https://github.com/xtekky/gpt4free/compare/0.3.2.6...0.3.2.7",
  "reactions": {
    "url": "https://api.github.com/repos/xtekky/gpt4free/releases/175141934/reactions",
    "total_count": 25,
    "+1": 13,
    "-1": 0,
    "laugh": 2,
    "hooray": 3,
    "confused": 0,
    "heart": 5,
    "rocket": 2,
    "eyes": 0
  },
  "mentions_count": 1
}

当然在实际项目中,会加入try except来加强错误输出

学习g4f源代码

附上g4f项目的相关源代码:

from __future__ import annotations

from os import environ
import requests
from functools import cached_property
from importlib.metadata import version as get_package_version, PackageNotFoundError
from subprocess import check_output, CalledProcessError, PIPE
from .errors import VersionNotFoundError
from . import debug

PACKAGE_NAME = "g4f"
GITHUB_REPOSITORY = "xtekky/gpt4free"

def get_pypi_version(package_name: str) -> str:
    """
    Retrieves the latest version of a package from PyPI.

    Args:
        package_name (str): The name of the package for which to retrieve the version.

    Returns:
        str: The latest version of the specified package from PyPI.

    Raises:
        VersionNotFoundError: If there is an error in fetching the version from PyPI.
    """
    try:
        response = requests.get(f"https://pypi.org/pypi/{package_name}/json").json()
        return response["info"]["version"]
    except requests.RequestException as e:
        raise VersionNotFoundError(f"Failed to get PyPI version: {e}")

def get_github_version(repo: str) -> str:
    """
    Retrieves the latest release version from a GitHub repository.

    Args:
        repo (str): The name of the GitHub repository.

    Returns:
        str: The latest release version from the specified GitHub repository.

    Raises:
        VersionNotFoundError: If there is an error in fetching the version from GitHub.
    """
    try:
        response = requests.get(f"https://api.github.com/repos/{repo}/releases/latest").json()
        return response["tag_name"]
    except requests.RequestException as e:
        raise VersionNotFoundError(f"Failed to get GitHub release version: {e}")

class VersionUtils:
    """
    Utility class for managing and comparing package versions of 'g4f'.
    """
    @cached_property
    def current_version(self) -> str:
        """
        Retrieves the current version of the 'g4f' package.

        Returns:
            str: The current version of 'g4f'.

        Raises:
            VersionNotFoundError: If the version cannot be determined from the package manager, 
                                  Docker environment, or git repository.
        """
        if debug.version:
            return debug.version

        # Read from package manager
        try:
            return get_package_version(PACKAGE_NAME)
        except PackageNotFoundError:
            pass

        # Read from docker environment
        version = environ.get("G4F_VERSION")
        if version:
            return version

        # Read from git repository
        try:
            command = ["git", "describe", "--tags", "--abbrev=0"]
            return check_output(command, text=True, stderr=PIPE).strip()
        except CalledProcessError:
            pass

        raise VersionNotFoundError("Version not found")

    @cached_property
    def latest_version(self) -> str:
        """
        Retrieves the latest version of the 'g4f' package.

        Returns:
            str: The latest version of 'g4f'.
        """
        # Is installed via package manager?
        try:
            get_package_version(PACKAGE_NAME)
        except PackageNotFoundError:
            return get_github_version(GITHUB_REPOSITORY)
        return get_pypi_version(PACKAGE_NAME)

    def check_version(self) -> None:
        """
        Checks if the current version of 'g4f' is up to date with the latest version.

        Note:
            If a newer version is available, it prints a message with the new version and update instructions.
        """
        try:
            if self.current_version != self.latest_version:
                print(f'New g4f version: {self.latest_version} (current: {self.current_version}) | pip install -U g4f')
        except Exception as e:
            print(f'Failed to check g4f version: {e}')

utils = VersionUtils()

 


原文地址:https://blog.csdn.net/skywalk8163/article/details/142374558

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!