开源项目教程:基于Gemini的Live API Web Console
1. 项目介绍
本项目是基于React的开源项目,旨在提供一个使用Gemini Live API的Web Console。Gemini Live API是Google开发的一种多模态API,可以通过WebSocket进行通信,支持音频播放、用户媒体录制以及统一日志视图等功能,以辅助开发者构建自己的应用程序。
2. 项目快速启动
首先,确保您的开发环境中已经安装了Node.js。
-
克隆项目到本地:
git clone https://github.com/google-gemini/multimodal-live-api-web-console.git cd multimodal-live-api-web-console
-
创建一个免费的Gemini API密钥,并将其添加到项目根目录下的
.env
文件中。 -
安装项目依赖并启动开发服务器:
npm install npm start
运行后,在浏览器中打开
http://localhost:3000
查看应用。 -
项目构建: 当开发完成后,构建项目以用于生产环境:
npm run build
3. 应用案例和最佳实践
以下是一个使用Live API调用并渲染图表的简单示例:
import { useEffect, useRef, useState } from 'react';
import vegaEmbed from 'vega-embed';
import { useLiveAPIContext } from '../../contexts/LiveAPIContext';
const declaration = {
name: 'render_altair',
description: '显示一个Altair图表,以JSON格式传递。',
parameters: {
type: 'object',
properties: {
json_graph: {
type: 'string',
description: '图表的JSON字符串表示。必须是字符串,而不是JSON对象'
}
},
required: ['json_graph']
}
};
export function Altair() {
const [jsonString, setJSONString] = useState('');
const { client, setConfig } = useLiveAPIContext();
useEffect(() => {
setConfig({
model: 'models/gemini-2.0-flash-exp',
systemInstruction: {
parts: [
{
text: '你是我的助手。每次我要求你绘制图表时,调用我提供的"render_altair"函数。不要询问更多信息,只需根据你的最佳判断。'
}
]
},
tools: [
{
googleSearch: {}
},
{
functionDeclarations: [declaration]
}
]
});
}, [setConfig]);
useEffect(() => {
const onToolCall = (toolCall) => {
console.log('收到工具调用', toolCall);
const fc = toolCall.functionCalls.find((fc) => fc.name === declaration.name);
if (fc) {
const str = fc.args.json_graph;
setJSONString(str);
}
};
client.on('toolcall', onToolCall);
return () => {
client.off('toolcall', onToolCall);
};
}, [client]);
const embedRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (embedRef.current && jsonString) {
vegaEmbed(embedRef.current, JSON.parse(jsonString));
}
}, [embedRef, jsonString]);
return <div className="vega-embed" ref={embedRef} />;
}
4. 典型生态项目
目前,本项目生态中的一些典型案例包括:
- GenExplainer:使用Live API进行解释生成的示例。
- GenWeather:使用Live API生成天气信息的示例。
- GenList:使用Live API生成列表的示例。
开发者可以参考这些示例,结合自己的需求,构建更加复杂的应用程序。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考