lobehub / chat-plugin-template

🧩 / 🚀 PluginTemplate - This is the plugin template for LobeChat plugin development.
MIT License
45 stars 32 forks source link

[Question] 开发了一个插件业务方法没有被调用 #34

Open jhezjkp opened 1 month ago

jhezjkp commented 1 month ago

🧐 问题描述 | Proposed Solution

开发的是一个text to image的插件,初版相关url和api key参数写死的,调用一切正常:

image

接着进一步迭代,把url和api key提取可以配置的参数,调用就出现问题了:

image

日志:

>>> call in gateway... {
  cookies: RequestCookies {},
  geo: {},
  ip: undefined,
  nextUrl: {
  href: 'http://localhost:3400/api/gateway',
  origin: 'http://localhost:3400',
  protocol: 'http:',
  username: '',
  password: '',
  host: 'localhost:3400',
  hostname: 'localhost',
  port: '3400',
  pathname: '/api/gateway',
  search: '',
  searchParams: URLSearchParams {  },
  hash: ''
},
  url: 'http://localhost:3400/api/gateway',
  bodyUsed: false,
  cache: 'default',
  credentials: 'same-origin',
  destination: '',
  headers: {
  cache-control: '',
  connection: 'keep-alive',
  content-type: 'application/json; charset=utf-8',
  host: 'localhost:3400',
  transfer-encoding: 'chunked',
  user-agent: 'RapidAPI/4.2.5 (Macintosh; OS X/14.5.0) GCDHTTPRequest',
  x-forwarded-for: '::ffff:127.0.0.1',
  x-forwarded-host: 'localhost:3400',
  x-forwarded-port: '3400',
  x-forwarded-proto: 'http',
  x-invoke-path: '/api/gateway',
  x-invoke-query: '%7B%7D',
  x-lobe-plugin-settings: '{"SERVICE_BASE_URL":"https://api.ai.xxxx.com/v1/images/generations","SERVICE_API_KEY":"sk-xxxxxxx"}',
  x-middleware-invoke: ''
},
  integrity: '',
  keepalive: false,
  method: 'POST',
  mode: 'cors',
  redirect: 'follow',
  referrer: 'about:client',
  referrerPolicy: '',
  signal: AbortSignal {
  [Symbol(kAborted)]: false,
  [Symbol(kReason)]: undefined,
  [Symbol(kOnabort)]: undefined,
  [Symbol(realm)]: {
  settingsObject: {
  baseUrl: undefined,
  origin: [Getter],
  policyContainer: { referrerPolicy: 'strict-origin-when-cross-origin' }
}
}
}
}
>>> call in gateway... {
  cookies: RequestCookies {},
  geo: {},
  ip: undefined,
  nextUrl: {
  href: 'http://localhost:3400/api/gateway',
  origin: 'http://localhost:3400',
  protocol: 'http:',
  username: '',
  password: '',
  host: 'localhost:3400',
  hostname: 'localhost',
  port: '3400',
  pathname: '/api/gateway',
  search: '',
  searchParams: URLSearchParams {  },
  hash: ''
},
  url: 'http://localhost:3400/api/gateway',
  bodyUsed: false,
  cache: 'default',
  credentials: 'same-origin',
  destination: '',
  headers: {
  cache-control: '',
  connection: 'keep-alive',
  content-type: 'application/json; charset=utf-8',
  host: 'localhost:3400',
  transfer-encoding: 'chunked',
  user-agent: 'RapidAPI/4.2.5 (Macintosh; OS X/14.5.0) GCDHTTPRequest',
  x-forwarded-for: '::ffff:127.0.0.1',
  x-forwarded-host: 'localhost:3400',
  x-forwarded-port: '3400',
  x-forwarded-proto: 'http',
  x-invoke-path: '/api/gateway',
  x-invoke-query: '%7B%7D',
  x-lobe-plugin-settings: '{"SERVICE_BASE_URL":"https://api.ai.xxxx.com/v1/images/generations","SERVICE_API_KEY":"sk-xxxxxxx"}',
  x-middleware-invoke: ''
},
  integrity: '',
  keepalive: false,
  method: 'POST',
  mode: 'cors',
  redirect: 'follow',
  referrer: 'about:client',
  referrerPolicy: '',
  signal: AbortSignal {
  [Symbol(kAborted)]: false,
  [Symbol(kReason)]: undefined,
  [Symbol(kOnabort)]: undefined,
  [Symbol(realm)]: {
  settingsObject: {
  baseUrl: undefined,
  origin: [Getter],
  policyContainer: { referrerPolicy: 'strict-origin-when-cross-origin' }
}
}
}
}

gateway.ts

export const config = {
  runtime: 'edge',
};

export default async (req: Request) => {
  console.log(">>> call in gateway...", req)
  if (process.env.NODE_ENV === 'development') {
    const { createGatewayOnEdgeRuntime } = await import('@lobehub/chat-plugins-gateway');

    return createGatewayOnEdgeRuntime()(req);
  }

  return new Response('gateway');
};

text2image.ts

import { PluginErrorType, createErrorResponse, getPluginSettingsFromRequest } from '@lobehub/chat-plugin-sdk';

import {Settings, Text2ImageRequest, Text2ImageResponse} from '@/type';

export const config = {
  runtime: 'edge',
};

export default async (req: Request) => {
  console.log("000000")
  if (req.method !== 'POST') return createErrorResponse(PluginErrorType.MethodNotAllowed);

  console.log("11111")
  // 获取 settings 信息
  const settings = getPluginSettingsFromRequest<Settings>(req);
  console.log("11111222")

  if (!settings) {
    console.log("no service config provided!")
    // 如果获取失败,可以通过发送 PluginErrorType.PluginSettingsInvalid 唤起插件配置界面
    return createErrorResponse(PluginErrorType.PluginSettingsInvalid, {
      message: 'Plugin settings not found.',
    });
  }
  console.log("service config:", settings)

  const { size, prompt } = (await req.json()) as Text2ImageRequest;

  console.log("prepare to generate image:", size, prompt)

  const res = await fetch('https://api.ai.xxx.com/v1/images/generations', {
    headers:  {
      Authorization: `Bearer sk-xxxxxx`,
      'Content-Type': 'text/plain; charset=utf-8',
    },
    body: JSON.stringify({
      prompt: prompt,
      n: 1,
      model: 'FLUX.1-schnell',
      size: size,
    }),
    method: 'POST',
  });

  const responseData = await res.json();
  console.log(">>>", responseData);

  const result: Text2ImageResponse = {
    success: true,
    url: responseData.data[0].url,
    revised_prompt: responseData.data[0].revised_prompt
  };

  return new Response(JSON.stringify(result));
};

📝 补充信息 | Additional Information

No response

lobehubbot commented 1 month ago

👀 @jhezjkp Thank you for raising an issue. We will investigate into the matter and get back to you as soon as possible. Please make sure you have given us as much context as possible.\ 非常感谢您提交 issue。我们会尽快调查此事,并尽快回复您。 请确保您已经提供了尽可能多的背景信息。

jhezjkp commented 1 month ago

直接curl测试是成功的:

curl -X "POST" "http://localhost:3400/api/text2image" \
     -H 'x-lobe-plugin-settings: {"SERVICE_BASE_URL":"https://api.ai.xxx.com/v1/images/generations","SERVICE_API_KEY":"sk-xxxx"}' \
     -H 'Content-Type: application/json; charset=utf-8' \
     -d $'{
  "size": "1080x1080",
  "prompt": "a girl with a red hat"
}'

{"success":true,"url":"https://sf-maas-uat-prod.oss-cn-shanghai.aliyuncs.com/outputs/33159cf8-1a13-49b8-82d6-e3528c3f1804_0.png","revised_prompt":"a girl with a red hat"}
image
arvinxx commented 1 month ago

我晚点看看