作为前端开发者,我们的日常工作中总是有各种各样的 UI 布局任务。从设计稿到代码实现,往往需要花费大量时间去调整布局、优化细节,这种重复性的工作不仅浪费时间资源,还无形中加重了我们的工作负荷,让人感到疲惫。
前段时间,我在 GitHub 上偶然发现了一个热门的开源项目 Screenshot-to-Code,它能够通过 AI 自动生成前端代码,并且支持生成多种不同技术栈的代码,如 HTML + Tailwind、React + Tailwind 等等。
想到可以借助 AI 来帮助我开发复杂的页面,我立刻决定尝试一下。
环境搭建
首先,我们可以将项目 Clone 到本地并用 IDE 打开,准备本地部署启动。然而,面对冗长的项目 Readme 文档,直接阅读可能会带来很重的视觉负担。
按照它给到的命令执行后,我成功地启动了项目:
使用编程助手增加 Gemini 模型
接着在 backend/.env、backend/config.py 增加 Gemini 的 API KEY:
#.env增加key
GEMINI_API_KEY=xxxxxx
#config.py增加获取key
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY", None)
然后可以在 Llm.py
中增加 Gemini 模型以及调用 Gemini 的代码。这时我发现有一个 stream_claude_response_native 方法,看起来是在调用 Claude,我们让豆包MarsCode 编程助手解释一下:
通过豆包MarsCode 编程助手的解释,确认是在调用 Claude。那我们需要增加调用 Gemini 的代码。编写代码过程中,通过编程助手提供的代码补全功能,效率获得了显著的提升。
class Llm(Enum):
GPT_4_VISION = "gpt-4-vision-preview"
GPT_4_TURBO_2024_04_09 = "gpt-4-turbo-2024-04-09"
GPT_4O_2024_05_13 = "gpt-4o-2024-05-13"
CLAUDE_3_SONNET = "claude-3-sonnet-20240229"
CLAUDE_3_OPUS = "claude-3-opus-20240229"
CLAUDE_3_HAIKU = "claude-3-haiku-20240307"
CLAUDE_3_5_SONNET_2024_06_20 = "claude-3-5-sonnet-20240620"
//新增gemini
GEMINI_1_5_PRO_LATEST = "gemini-1.5-pro-latest"
async def stream_gemini_response(
messages: List[ChatCompletionMessageParam],
api_key: str,
callback: Callable[[str], Awaitable[None]],
) -> str:
genai.configure(api_key=api_key)
generation_config = genai.GenerationConfig(
temperature = 0.0
)
model = genai.GenerativeModel(
model_name = "gemini-1.5-pro-latest",
generation_config = generation_config
)
contents = parse_openai_to_gemini_prompt(messages);
response = model.generate_content(
contents = contents,
#Support streaming
stream = True,
)
for chunk in response:
content = chunk.text or ""
await callback(content)
if not response:
raise Exception("No HTML response found in AI response")
else:
return response.text;
def parse_openai_to_gemini_prompt(prompts):
messages = []
for prompt in prompts:
message = {}
message['role'] = prompt['role']
if prompt['role'] == 'system':
message['role'] = 'user'
if prompt['role'] == 'assistant':
message['role'] = 'model'
message['parts'] = []
content = prompt['content']
if isinstance(content, list):
for content in prompt['content']:
part = {}
if content['type'] == 'image_url':
base64 = content['image_url']['url']
part['inline_data'] = {
'data': base64.split(",")[1],
'mime_type': base64.split(";")[0].split(":")[1]
}
elif content['type'] == 'text':
part['text'] = content['text']
message['parts'].append(part)
else:
message['parts'] = [content]
messages.append(message)
return messages
之后,我们还需要在 generate_code 增加调用前面写的 Gemini 方法:
if validated_input_mode == "video":
if not anthropic_api_key:
await throw_error(
only works with Anthropic models. No Anthropic API key found. Please add the environment variable ANTHROPIC_API_KEY to backend/.env or in the settings dialog"
)
raise Exception("No Anthropic key")
completion = await stream_claude_response_native(
system_prompt=VIDEO_PROMPT,
messages=prompt_messages, # type: ignore
api_key=anthropic_api_key,
callback=lambda x: process_chunk(x),
model=Llm.CLAUDE_3_OPUS,
include_thinking=True,
)
exact_llm_version = Llm.CLAUDE_3_OPUS
elif (
code_generation_model == Llm.CLAUDE_3_SONNET
or code_generation_model == Llm.CLAUDE_3_5_SONNET_2024_06_20
:
if not anthropic_api_key:
await throw_error(
Anthropic API key found. Please add the environment variable ANTHROPIC_API_KEY to backend/.env or in the settings dialog"
)
raise Exception("No Anthropic key")
completion = await stream_claude_response(
# type: ignore
api_key=anthropic_api_key,
callback=lambda x: process_chunk(x),
model=code_generation_model,
)
exact_llm_version = code_generation_model
# 增加调用gemini
elif (
code_generation_model == Llm.GEMINI_1_5_PRO_LATEST
:
if not GEMINI_API_KEY:
await throw_error(
GEMINI API key found. Please add the environment variable ANTHROPIC_API_KEY to backend/.env or in the settings dialog"
)
raise Exception("No GEMINI key")
completion = await stream_gemini_response(
# type: ignore
api_key=GEMINI_API_KEY,
callback=lambda x: process_chunk(x),
)
exact_llm_version = code_generation_model
else:
completion = await stream_openai_response(
# type: ignore
api_key=openai_api_key,
base_url=openai_base_url,
callback=lambda x: process_chunk(x),
model=code_generation_model,
)
exact_llm_version = code_generation_model
最后安装 Gemini SDK:
cd backend
poetry add google-generativeai
效果呈现
点击阅读原文,即刻体验豆包MarsCode~