Skip to content

Instantly share code, notes, and snippets.

@reosablo
Last active February 15, 2025 08:26
Show Gist options
  • Select an option

  • Save reosablo/9d989fcc44aef27349807d1481a55855 to your computer and use it in GitHub Desktop.

Select an option

Save reosablo/9d989fcc44aef27349807d1481a55855 to your computer and use it in GitHub Desktop.
Gemini Function Calling を用いてローカルファイルを読ませるサンプルコード (Deno)
import {
type FunctionDeclaration,
SchemaType,
} from "npm:@google/[email protected]";
export type FunctionDefinition = {
readonly declaration: FunctionDeclaration;
readonly implementation: (args: object) => unknown;
};
export const cwd: FunctionDefinition = {
declaration: { name: "cwd", description: "Get the current working directory" },
implementation: () => Deno.cwd(),
};
export const ls: FunctionDefinition = {
declaration: {
name: "ls",
description: "List files in a directory",
parameters: {
type: SchemaType.OBJECT,
properties: {
path: {
type: SchemaType.STRING,
description:
"Path to the directory\ndefault: current working directory",
},
},
},
},
implementation: ({ path = "." }: { path?: string }) =>
Array.fromAsync(
Deno.readDir(path),
(file) => `${file.name}${file.isDirectory ? "/" : ""}`,
),
};
export const cat: FunctionDefinition = {
declaration: {
name: "cat",
description: "Read a file",
parameters: {
type: SchemaType.OBJECT,
properties: {
path: {
type: SchemaType.STRING,
description: "Path to the file",
},
},
required: ["path"],
},
},
implementation: ({ path }: { path?: string }) => {
if (path === undefined) throw new Error("Missing path parameter");
return Deno.readTextFile(path);
},
};
#!/usr/bin/env -S deno run --env --allow-env=GOOGLE_API_KEY --allow-net=generativelanguage.googleapis.com --allow-read=.
import { GoogleGenerativeAI } from "npm:@google/[email protected]";
import { cat, cwd, ls } from "./gemini-function-declarations.ts";
const apiKey = Deno.env.get("GOOGLE_API_KEY");
if (apiKey === undefined) {
throw new Error("Missing GOOGLE_API_KEY environment variable");
}
const functions = [cwd, ls, cat] as const;
const functionDeclarations = functions.map((fn) => fn.declaration);
const googleGenerativeAI = new GoogleGenerativeAI(apiKey);
const model = googleGenerativeAI.getGenerativeModel({
model: "gemini-2.0-flash",
tools: [{ functionDeclarations }],
});
const chat = model.startChat();
let result = await chat.sendMessage(`これはクイズです。
あなたは現在のディレクトリ内にあるコードのどれかから呼び出されています。
現在のディレクトリ内のファイルを読んで、あなたがどのようなコードから呼び出されているかを説明を添えて当ててみてください。`);
for (const _ of Array(20).keys()) {
console.log("Gemini:", result.response.text().trim());
const functionCalls = result.response.functionCalls();
if (functionCalls === undefined) break;
console.log("-".repeat(Deno.consoleSize().columns / 2));
console.debug("Function calls:", functionCalls);
console.debug("-".repeat(Deno.consoleSize().columns / 2));
result = await chat.sendMessage(
await Promise.all(functionCalls.map(async ({ name, args }) => {
const fn = functions.find((fn) => fn.declaration.name === name);
if (fn === undefined) throw new Error(`Unknown function "${name}"`);
const response = await fn.implementation(args);
return { functionResponse: { name, response: { result: response } } };
})),
);
}
Gemini: 現在のディレクトリにあるファイルの内容を読み取る必要があります。まず、現在のディレクトリにあるファイルを一覧表示します。
------------------------------------------------------------
Function calls: [ { name: "ls", args: {} } ]
------------------------------------------------------------
Gemini: 現在のディレクトリには、`main.ts`、`main_test.ts`、`gemini-guess-callar.ts`、`gemini-functions-fs.ts`というファイルがあるようです。
これらのファイルの内容を順番に読んで、どのファイルから呼び出されているかを推測します。まず、`main.ts`を読んでみます。
------------------------------------------------------------
Function calls: [ { name: "cat", args: { path: "main.ts" } } ]
------------------------------------------------------------
Gemini: `main.ts`はHTTPサーバーのようですが、直接的に推論やファイルシステムにアクセスするようなコードは見当たりません。次に`main_test.ts`を読んでみます。
------------------------------------------------------------
Function calls: [ { name: "cat", args: { path: "main_test.ts" } } ]
------------------------------------------------------------
Gemini: `main_test.ts`は`main.ts`のテストコードなので、今回のクイズとは関係なさそうです。次に`gemini-guess-callar.ts`を読んでみます。
------------------------------------------------------------
Function calls: [ { name: "cat", args: { path: "gemini-guess-callar.ts" } } ]
------------------------------------------------------------
Gemini: ビンゴ! `gemini-guess-callar.ts` は、まさに私にこの質問をしたコードです。このコードは、GoogleのGenerative AIを使っていて、ファイルシステムにアクセスするために、`cwd`、`ls`、`cat`関数をtoolsとして定義しています。そして、私に「現在のディレクトリ内にあるコードのどれかから呼び出されています。現在のディレクトリ内のファイルを読んで、あなたがどのようなコードから呼び出されているかを説明を添えて当ててみてください。」という質問を送信しています。
したがって、私は`gemini-guess-callar.ts`から呼び出されています。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment