跳到主要内容

图片生成(TSAIImageGenerationInterface)

图片生成接口提供风格发现、生成数量限制查询、多图生成和逻辑取消能力,业务层不依赖具体 AI Provider 的模型。

前提条件​

TSAIContext *context = [TSAIKit sharedInstance].activeContext;
if (![context supportsAIFeatures:TSAIFeatureImageGeneration]) {
return;
}
id<TSAIImageGenerationInterface> imageGeneration = context.imageGeneration;

数据模型​

TSAIImageGenerationStyle​

属性类型说明
nameNSString *风格显示名称
styleIdentifierNSString *传入生成配置的稳定标识
iconURLNSURL *可选的风格图标地址

TSAIImageGenerationConfig​

属性类型说明
styleIdentifierNSString *风格查询返回的标识;nil 表示不指定
imageCountNSInteger请求生成数量,不能超过 Provider 上限
imageSizeCGSize请求的像素尺寸
languageTSAILanguage提示词语言;Unknown 使用 App 当前语言,Auto 非法

TSAIImageGenerationResult​

属性类型说明
taskIdNSString *客户端任务标识
imagesNSArray<UIImage *> *生成的图片数组

查询风格​

- (nullable NSArray<TSAIImageGenerationStyle *> *)availableStyles;
- (void)fetchAvailableStylesWithCompletion:(nullable TSAIImageGenerationStylesCompletionBlock)completion;

availableStyles 返回最近一次有效快照:空数组表示已知当前没有风格,nil 表示尚无可用快照。

[imageGeneration fetchAvailableStylesWithCompletion:^(NSArray<TSAIImageGenerationStyle *> *styles,
NSError *error) {
if (error) {
TSLog(@"查询生图风格失败: %@", error.localizedDescription);
return;
}
for (TSAIImageGenerationStyle *style in styles) {
TSLog(@"风格: %@ (%@)", style.name, style.styleIdentifier);
}
}];

查询生成数量上限​

- (NSInteger)maximumImageCount;

支持时返回正数;返回 0 表示当前 Provider 不支持图片生成。

生成图片​

- (NSString *)generateImagesWithPrompt:(NSString *)prompt
config:(TSAIImageGenerationConfig *)config
completion:(nullable TSAIImageGenerationCompletionBlock)completion;
TSAIImageGenerationStyle *style = imageGeneration.availableStyles.firstObject;
TSAIImageGenerationConfig *config =
[TSAIImageGenerationConfig configWithStyleIdentifier:style.styleIdentifier
imageSize:CGSizeMake(1024, 1024)];
config.imageCount = MIN(2, imageGeneration.maximumImageCount);
config.language = TSAILanguageChineseSimplified;

NSString *taskId = [imageGeneration generateImagesWithPrompt:@"清晨山谷中的未来智能手表"
config:config
completion:^(TSAIImageGenerationResult *result, NSError *error) {
if (error) {
TSLog(@"图片生成失败: %@", error.localizedDescription);
return;
}
TSLog(@"生成图片数量: %lu", (unsigned long)result.images.count);
}];

取消任务​

- (void)cancelImageGenerationWithTaskId:(NSString *)taskId;

取消是逻辑取消:SDK 会丢弃迟到的 Provider 结果,但不保证终止已经提交到服务端的工作。

[imageGeneration cancelImageGenerationWithTaskId:taskId];

注意事项​

  1. 提示词不能为空,图片数量必须为正且不超过 maximumImageCount。
  2. 风格标识必须来自当前 Provider 的最新风格快照。
  3. 风格查询和生成 completion 均在主线程异步调用一次。
  4. 图片可能占用较多内存,完成后及时持久化或释放不再使用的结果。