readme_table.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. import re
  2. from urllib.parse import urlparse
  3. import asyncio
  4. from g4f import models, ChatCompletion
  5. from g4f.providers.types import BaseRetryProvider, ProviderType
  6. from g4f.providers.base_provider import ProviderModelMixin
  7. from g4f.Provider import __providers__
  8. from g4f.models import _all_models
  9. from g4f import debug
  10. debug.logging = True
  11. async def test_async(provider: ProviderType):
  12. if not provider.working:
  13. return False
  14. messages = [{"role": "user", "content": "Hello Assistant!"}]
  15. try:
  16. if "webdriver" in provider.get_parameters():
  17. return False
  18. response = await asyncio.wait_for(ChatCompletion.create_async(
  19. model=models.default,
  20. messages=messages,
  21. provider=provider
  22. ), 30)
  23. return bool(response)
  24. except Exception as e:
  25. if debug.logging:
  26. print(f"{provider.__name__}: {e.__class__.__name__}: {e}")
  27. return False
  28. def test_async_list(providers: list[ProviderType]):
  29. responses: list = [
  30. asyncio.run(test_async(_provider))
  31. for _provider in providers
  32. ]
  33. return responses
  34. def print_providers():
  35. providers = [provider for provider in __providers__ if provider.working]
  36. responses = test_async_list(providers)
  37. lines = []
  38. for type in ("Free", "Auth"):
  39. lines += [
  40. "",
  41. f"## {type}",
  42. "",
  43. ]
  44. for idx, _provider in enumerate(providers):
  45. do_continue = False
  46. if type == "Auth" and _provider.needs_auth:
  47. do_continue = True
  48. elif type == "Free" and not _provider.needs_auth:
  49. do_continue = True
  50. if not do_continue:
  51. continue
  52. lines.append(
  53. f"### {getattr(_provider, 'label', _provider.__name__)}",
  54. )
  55. provider_name = f"`g4f.Provider.{_provider.__name__}`"
  56. lines.append(f"| Provider | {provider_name} |")
  57. lines.append("| -------- | ---- |")
  58. if _provider.url:
  59. netloc = urlparse(_provider.url).netloc.replace("www.", "")
  60. website = f"[{netloc}]({_provider.url})"
  61. else:
  62. website = "❌"
  63. message_history = "✔️" if _provider.supports_message_history else "❌"
  64. system = "✔️" if _provider.supports_system_message else "❌"
  65. stream = "✔️" if _provider.supports_stream else "❌"
  66. if _provider.working:
  67. status = '![Active](https://img.shields.io/badge/Active-brightgreen)'
  68. if responses[idx]:
  69. status = '![Active](https://img.shields.io/badge/Active-brightgreen)'
  70. else:
  71. status = '![Unknown](https://img.shields.io/badge/Unknown-grey)'
  72. else:
  73. status = '![Inactive](https://img.shields.io/badge/Inactive-red)'
  74. auth = "✔️" if _provider.needs_auth else "❌"
  75. lines.append(f"| **Website** | {website} | \n| **Status** | {status} |")
  76. if issubclass(_provider, ProviderModelMixin):
  77. try:
  78. all_models = _provider.get_models()
  79. models = [model for model in _all_models if model in all_models or model in _provider.model_aliases]
  80. image_models = _provider.image_models
  81. if image_models:
  82. for alias, name in _provider.model_aliases.items():
  83. if alias in _all_models and name in image_models:
  84. image_models.append(alias)
  85. image_models = [model for model in image_models if model in _all_models]
  86. if image_models:
  87. models = [model for model in models if model not in image_models]
  88. if models:
  89. lines.append(f"| **Models** | {', '.join(models)} ({len(all_models)})|")
  90. if image_models:
  91. lines.append(f"| **Image Models (Image Generation)** | {', '.join(image_models)} |")
  92. if hasattr(_provider, "vision_models"):
  93. lines.append(f"| **Vision (Image Upload)** | ✔️ |")
  94. except:
  95. pass
  96. lines.append(f"| **Authentication** | {auth} | \n| **Streaming** | {stream} |")
  97. lines.append(f"| **System message** | {system} | \n| **Message history** | {message_history} |")
  98. return lines
  99. def print_models():
  100. base_provider_names = {
  101. "google": "Google",
  102. "openai": "OpenAI",
  103. "huggingface": "Huggingface",
  104. "anthropic": "Anthropic",
  105. "inflection": "Inflection",
  106. "meta": "Meta",
  107. }
  108. provider_urls = {
  109. "google": "https://gemini.google.com/",
  110. "openai": "https://openai.com/",
  111. "huggingface": "https://huggingface.co/",
  112. "anthropic": "https://www.anthropic.com/",
  113. "inflection": "https://inflection.ai/",
  114. "meta": "https://llama.meta.com/",
  115. }
  116. lines = [
  117. "| Model | Base Provider | Provider | Website |",
  118. "| ----- | ------------- | -------- | ------- |",
  119. ]
  120. for name, model in models.ModelUtils.convert.items():
  121. if name.startswith("gpt-3.5") or name.startswith("gpt-4"):
  122. if name not in ("gpt-3.5-turbo", "gpt-4", "gpt-4-turbo"):
  123. continue
  124. name = re.split(r":|/", model.name)[-1]
  125. if model.base_provider not in base_provider_names:
  126. continue
  127. base_provider = base_provider_names[model.base_provider]
  128. if not isinstance(model.best_provider, BaseRetryProvider):
  129. provider_name = f"g4f.Provider.{model.best_provider.__name__}"
  130. else:
  131. provider_name = f"{len(model.best_provider.providers)}+ Providers"
  132. provider_url = provider_urls[model.base_provider]
  133. netloc = urlparse(provider_url).netloc.replace("www.", "")
  134. website = f"[{netloc}]({provider_url})"
  135. lines.append(f"| {name} | {base_provider} | {provider_name} | {website} |")
  136. return lines
  137. def print_image_models():
  138. lines = [
  139. "| Label | Provider | Image Model | Vision Model | Website |",
  140. "| ----- | -------- | ----------- | ------------ | ------- |",
  141. ]
  142. for provider in [provider for provider in __providers__ if provider.working and getattr(provider, "image_models", None) or getattr(provider, "vision_models", None)]:
  143. provider_url = provider.url if provider.url else "❌"
  144. netloc = urlparse(provider_url).netloc.replace("www.", "")
  145. website = f"[{netloc}]({provider_url})"
  146. label = getattr(provider, "label", provider.__name__)
  147. if provider.image_models:
  148. image_models = ", ".join([model for model in provider.image_models if model in _all_models])
  149. else:
  150. image_models = "❌"
  151. if hasattr(provider, "vision_models"):
  152. vision_models = "✔️"
  153. else:
  154. vision_models = "❌"
  155. lines.append(f'| {label} | `g4f.Provider.{provider.__name__}` | {image_models}| {vision_models} | {website} |')
  156. return lines
  157. if __name__ == "__main__":
  158. with open("docs/providers.md", "w") as f:
  159. f.write("\n".join(print_providers()))
  160. f.write(f"\n{'-' * 50} \n")
  161. #f.write("\n".join(print_models()))
  162. #f.write(f"\n{'-' * 50} \n")
  163. f.write("\n".join(print_image_models()))