Skip to main content
Glama

generateImage

Generate images from text prompts using AI models, with options for image mixing, reference images, and custom dimensions.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filePathNo本地图片路径或图片URL(可选,若填写则为图片混合/参考图生成功能)
promptYes生成图像的文本描述
modelNo模型名称,可选值: jimeng-5.0, jimeng-4.6, jimeng-4.5, jimeng-4.1, jimeng-4.0, jimeng-3.1, jimeng-3.0(旧版: jimeng-2.1, jimeng-2.0-pro, jimeng-2.0, jimeng-1.4, jimeng-xl-pro)
widthNo图像宽度,默认值:1024
heightNo图像高度,默认值:1024
sample_strengthNo精细度,默认值:0.5,范围0-1
negative_promptNo反向提示词,告诉模型不要生成什么内容

Implementation Reference

  • The generateImage method within the JimengApiClient class handles the core logic for image generation, including parameter validation, file uploading, API request construction, and polling for the result.
    public async generateImage(params: ImageGenerationParams): Promise<string[]> {
      // 参数验证
      if (!params.prompt || typeof params.prompt !== 'string') {
        throw new Error('prompt必须是非空字符串');
      }
      const hasFilePath = params?.filePath
      let uploadID = null
      if (params?.filePath) {
        uploadID = await this.uploadCoverFile(params.filePath)
      }
      // 获取实际模型
      const modelName = hasFilePath ? DEFAULT_BLEND_MODEL : params.model || DEFAULT_MODEL;
      const actualModel = this.getModel(modelName);
      // 生成组件ID
      const componentId = generateUuid();
      const rqParams = {
        "babi_param": urlEncode(jsonEncode({
          "scenario": "image_video_generation",
          "feature_key": hasFilePath ? "to_image_referenceimage_generate" : "aigc_to_image",
          "feature_entrance": "to_image",
          "feature_entrance_detail": hasFilePath ? "to_image-referenceimage-byte_edit" : `to_image-${actualModel}`,
        })),
        "aid": parseInt(DEFAULT_ASSISTANT_ID),
        "device_platform": "web",
        "region": "CN",
        "web_id": WEB_ID
      }
    
      let abilities: Record<string, any> = {}
      if (hasFilePath) {
        abilities = {
          "blend": {
            "type": "",
            "id": generateUuid(),
            "min_features": [],
            "core_param": {
              "type": "",
              "id": generateUuid(),
              "model": actualModel,
              "prompt": params.prompt + '##',
              "sample_strength": params.sample_strength || 0.5,
              "image_ratio": 1,
              "large_image_info": {
                "type": "",
                "id": generateUuid(),
                "height": 1360,
                "width": 1360,
                "resolution_type": '1k'
              }
            },
            "ability_list": [
              {
                "type": "",
                "id": generateUuid(),
                "name": "byte_edit",
                "image_uri_list": [
                  uploadID
                ],
                "image_list": [
                  {
                    "type": "image",
                    "id": generateUuid(),
                    "source_from": "upload",
                    "platform_type": 1,
                    "name": "",
                    "image_uri": uploadID,
                    "width": 0,
                    "height": 0,
                    "format": "",
                    "uri": uploadID
                  }
                ],
                "strength": 0.5
              }
            ],
            "history_option": {
              "type": "",
              "id": generateUuid(),
            },
            "prompt_placeholder_info_list": [
              {
                "type": "",
                "id": generateUuid(),
                "ability_index": 0
              }
            ],
            "postedit_param": {
              "type": "",
              "id": generateUuid(),
              "generate_type": 0
            }
          }
        }
      } else {
        abilities = {
          "generate": {
            "type": "",
            "id": generateUuid(),
            "core_param": {
              "type": "",
              "id": generateUuid(),
              "model": actualModel,
              "prompt": params.prompt,
              "negative_prompt": params.negative_prompt || "",
              "seed": Math.floor(Math.random() * 100000000) + 2500000000,
              "sample_strength": params.sample_strength || 0.5,
              "image_ratio": 1,
              "large_image_info": {
                "type": "",
                "id": generateUuid(),
                "height": params.height || 1024,
                "width": params.width || 1024,
                "resolution_type": '1k'
              }
            },
            "history_option": {
              "type": "",
              "id": generateUuid(),
            }
          }
        }
      }
      let submitId = generateUuid()
      const rqData = {
        "extend": {
          "root_model": actualModel,
          "template_id": "",
        },
        "submit_id": submitId,
        "metrics_extra": hasFilePath ? undefined : jsonEncode({
          "templateId": "",
          "generateCount": 1,
          "promptSource": "custom",
          "templateSource": "",
          "lastRequestId": "",
          "originRequestId": "",
          "enterFrom": "click",
          "position": "page_bottom_box"
        }),
        "draft_content": jsonEncode({
          "type": "draft",
          "id": generateUuid(),
          "min_version": DRAFT_VERSION,
          "is_from_tsn": true,
          "version": "3.2.2",
          "main_component_id": componentId,
          "component_list": [{
            "type": "image_base_component",
            "id": componentId,
            "min_version": DRAFT_VERSION,
            "metadata": {
              "type": "",
              "id": generateUuid(),
              "created_platform": 3,
              "created_platform_version": "",
              "created_time_in_ms": Date.now(),
              "created_did": ""
            },
            "generate_type": hasFilePath ? "blend" : "generate",
            "aigc_mode": "workbench",
            "abilities": {
              "type": "",
              "id": generateUuid(),
              ...abilities
            }
          }]
        }),
      }
    
      // 发送生成请求(积分不足时自动切换Token重试)
      let generateResult: any;
      while (this.tokens.length > 0) {
        const creditInfo = await this.getCredit();
        if (creditInfo.totalCredit <= 0) {
          await this.receiveCredit();
        }
        generateResult = await this.request(
          'POST',
          '/mweb/v1/aigc_draft/generate',
          rqData,
          rqParams
        );
        // console.log('生成请求结果:', generateResult);
        if (generateResult?.ret === '1006') {
          console.log(`Token [${this.tokenIndex + 1}/${this.tokens.length}] 积分不足,移除并切换下一个Token重试`);
          this.nextToken();
          if (this.tokens.length === 0) break;
          submitId = generateUuid();
          rqData.submit_id = submitId;
          continue;
        }
        break;
      }
      if (!generateResult || generateResult?.ret === '1006') {
        throw new Error('所有Token积分不足或没有相关权益');
      }
      const itemList = await this.pollResultWithHistory(generateResult, submitId);
    
      // 提取图片URL
      const resultList = (itemList || []).map(item => {
        const imageUrl = item?.image?.large_images?.[0]?.image_url || item?.common_attr?.cover_url;
        return imageUrl;
      }).filter(Boolean)
      console.log('生成图片结果:', resultList)
      return resultList
    }
  • src/api.ts:1094-1096 (registration)
    The generateImage function is exported as a wrapper around the JimengApiClient instance's generateImage method.
    export const generateImage = (params: ImageGenerationParams): Promise<string[]> => {
      return apiClient.generateImage(params);
    };
  • The ImageGenerationParams interface defines the input parameters for the generateImage function.
    interface ImageGenerationParams {
      filePath?: string; // 图片路径
      model?: string; // 模型名称,默认使用 DEFAULT_MODEL
      prompt: string; // 提示词
      width?: number; // 图像宽度,默认1024
      height?: number; // 图像高度,默认1024
      sample_strength?: number; // 精细度,默认0.5
      negative_prompt?: string; // 反向提示词,默认空
      refresh_token?: string; // 刷新令牌,必需
      req_key?: string; // 自定义参数,兼容旧接口
    }
Behavior1/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Tool has no description.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness1/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Tool has no description.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness1/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Tool has no description.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Tool has no description.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose1/5

Does the description clearly state what the tool does and how it differs from similar tools?

Tool has no description.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines1/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Tool has no description.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/c-rick/jimeng-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server