XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet
公开
关注 0 Fork 0 Star 1
返回提交历史

XFEstudio/gpt4free

Add example demonstrating image usage metadata feature

Co-authored-by: hlohaus <983577+hlohaus@users.noreply.github.com>

5c2e3e43
copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
提交于

代码差异

1 个文件 +130 -0
Added etc/examples/image_usage_metadata.py +130 -0
@@ -0,0 +1,130 @@
1 """
2 Example: Image Generation with Usage Metadata
3
4 This example demonstrates the new image metadata feature in usage statistics.
5 When generating images, the API now returns image dimensions and file size
6 instead of word/token counts.
7
8 Usage:
9 python -m etc.examples.image_usage_metadata
10 """
11
12 import asyncio
13 from g4f.client import AsyncClient
14
15
16 async def generate_image_with_metadata():
17 """
18 Generate an image and display usage statistics with metadata.
19
20 The usage statistics for image generation will include:
21 - images: Number of generated images
22 - width: Width of the primary image in pixels
23 - height: Height of the primary image in pixels
24 - file_size: Total file size of all generated images in bytes
25 """
26 client = AsyncClient()
27
28 print("Generating image...")
29 print("-" * 60)
30
31 try:
32 response = await client.images.generate(
33 model="flux",
34 prompt="A serene mountain landscape at sunset",
35 response_format="url"
36 )
37
38 if response and response.data:
39 image = response.data[0]
40 print(f"✓ Image generated successfully!")
41 print(f" URL: {image.url}")
42
43 # Note: Usage metadata is available in the streaming API
44 # When using the streaming backend API, you'll receive a usage event like:
45 # {
46 # "type": "usage",
47 # "usage": {
48 # "images": 1,
49 # "width": 1024,
50 # "height": 1024,
51 # "file_size": 524288
52 # }
53 # }
54
55 print("\nUsage metadata (available in streaming API):")
56 print(" - Shows image count, dimensions, and file size")
57 print(" - No word/token counts for image generation")
58
59 else:
60 print("✗ Failed to generate image")
61
62 except Exception as e:
63 print(f"✗ Error: {e}")
64
65
66 async def generate_text_for_comparison():
67 """
68 Generate text for comparison to show traditional token-based usage.
69
70 The usage statistics for text generation will include:
71 - prompt_tokens: Number of tokens in the prompt
72 - completion_tokens: Number of tokens in the completion
73 - total_tokens: Total number of tokens used
74 """
75 client = AsyncClient()
76
77 print("\nGenerating text for comparison...")
78 print("-" * 60)
79
80 try:
81 response = await client.chat.completions.create(
82 model="gpt-4o-mini",
83 messages=[{"role": "user", "content": "Hello, how are you?"}]
84 )
85
86 if response:
87 print(f"✓ Text generated successfully!")
88 print(f" Content: {response.choices[0].message.content[:100]}...")
89
90 # Token-based usage for text generation
91 if hasattr(response, 'usage'):
92 usage = response.usage
93 print("\nUsage metadata:")
94 print(f" - Prompt tokens: {usage.prompt_tokens}")
95 print(f" - Completion tokens: {usage.completion_tokens}")
96 print(f" - Total tokens: {usage.total_tokens}")
97
98 else:
99 print("✗ Failed to generate text")
100
101 except Exception as e:
102 print(f"✗ Error: {e}")
103
104
105 async def main():
106 """Run both examples to demonstrate the difference."""
107 print("=" * 60)
108 print("IMAGE GENERATION WITH USAGE METADATA - EXAMPLE")
109 print("=" * 60)
110
111 await generate_image_with_metadata()
112 await generate_text_for_comparison()
113
114 print("\n" + "=" * 60)
115 print("SUMMARY")
116 print("=" * 60)
117 print("""
118 The implementation provides context-appropriate usage statistics:
119
120 • Image Generation: Shows images, width, height, file_size
121 • Text Generation: Shows prompt_tokens, completion_tokens, total_tokens
122
123 This makes it easy to display meaningful statistics in the UI:
124 - For images: "1 image, 1024×1024 pixels, 512 KB"
125 - For text: "150 prompt tokens, 450 completion tokens"
126 """)
127
128
129 if __name__ == "__main__":
130 asyncio.run(main())