快速开始
警告
⚠️ 本项目仍在开发中。我们正努力尽快发布Flappy的首个版本。敬请期待!文档和代码示例将很快提供。
Flappy是一个用于构建基于大语言模型(LLM)的AI Agent/AI应用程序的开发框架,同时支持多种不同编程语言。请指定您正在使用的语言以开始使用。
安装
- NodeJS (TypeScript)
- Java
- Kotlin
- C#
npm install @plesito/node-flappy@next
# or yarn add @pleisto/node-flappy@next
Plugin
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.7.0</version>
</extension>
</extensions>
</build>
Dependency
<dependency>
<groupId>com.pleisto</groupId>
<artifactId>flappy</artifactId>
<version>0.0.8</version>
</dependency>
<dependency>
<groupId>com.pleisto</groupId>
<artifactId>flappy-java-bindings</artifactId>
<version>0.0.8</version>
</dependency>
<dependency>
<groupId>com.pleisto</groupId>
<artifactId>flappy-java-bindings</artifactId>
<version>0.0.8</version>
<classifier>${os.detected.classifier}</classifier>
</dependency>
// plugins
id("com.google.osdetector") version "1.7.3"
// dependencies
implementation("com.pleisto:flappy:0.0.8")
implementation("com.pleisto:flappy-java-bindings:0.0.8")
implementation("com.pleisto:flappy-java-bindings:0.0.8:${osdetector.classifier}")
<PackageReference Include="Pleisto.Flappy" Version="0.0.0.4-alpha" />
创建LLM适配器
Flappy支持多种LLM实现,例如OpenAI的ChatGPT和hugingface的transformers。您也可以通过实现LLMBase接口来创建自己的LLM适配器。
- NodeJS (TypeScript) & ChatGPT
- NodeJS (TypeScript) & 百川53B大模型API
- Java with ChatGPT
- Kotlin with ChatGPT
- C#
// you need to manually install `openai` package.
import { env } from 'node:process'
import OpenAI from 'openai'
import { ChatGPT } from '@pleisto/node-flappy'
const chatGpt = new ChatGPT(
new OpenAI({
apiKey: env.OPENAI_API_KEY!,
baseURL: env.OPENAI_API_BASE!
})
)
import { env } from 'node:process'
import { Baichuan } from '@pleisto/node-flappy'
const chatGpt = new Baichuan(
{
baichuan_api_key: env.BAICHUAN_API_KEY!,
baichuan_secret_key: env.BAICHUAN_SECRET_KEY!,
}
)
Dotenv dotenv = Dotenv.load();
ChatGPT llm = new ChatGPT(new ChatGPT.ChatGPTConfig(null, dotenv.get("OPENAI_TOKEN"), dotenv.get("OPENAI_API_BASE")));
val dotenv = dotenv()
val llm = ChatGPT(
ChatGPT.ChatGPTConfig(token = dotenv["OPENAI_TOKEN"], host = dotenv["OPENAI_API_BASE"])
)
var gpt35 = new ChatGPT(new OpenAIAPI
{
Auth = new APIAuthentication(apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")),
ApiUrlFormat = Environment.GetEnvironmentVariable("OPENAI_API_URL"),
ApiVersion = "v1",
}, "gpt-3.5-turbo", null, null);
定义你的 Agent
在人工智能中,Agent 是一个计算机程序或系统,其设计目的是感知其环境,做出决定,并采取行动以实现特定的目标或一组目标。Agent 自主运行,意味着它不直接受人类操作员的控制。
在 Flappy 的生态系统中,Agent 作为 LLM 的多功能通道进行操作。它的设计目的是进行各种任务的处理 - 结构化数据,调用外部 API,或者对 LLM 生成的 Python 代码进行沙盒处理 - 根据需要以任何组合进行。它是一个灵活的工具,而不是一个僵化的齿轮,能够适应您对更高效和安全的 LLM 交互的需求。
关键概念
函数
函数作为 Flappy 框架中你的 Agent 的基础。在这个文档中,我们将介绍 InvokeFunction
和 SythesizedFunction
,这两种你可以定义和使用的基础函数类型。
InvokeFunction
使 Agent 能够与环境进行交互,类似于 Langchain 的 Agent 中的工具。它由输入和输出参数定义,这些参数的结构必须清晰,以便语言学习模型(LLM)能够有效地进行交互。理解这些参数以及函数在与用户请求和世界交互中的角色是非常重要的,它对于成本效益的任务计划至关重要。SythesizedFunction
是由 LLM 扮演的一种函数。你只需要定义它的描述和它的输入和输出的结构。然后,LLM 将尝试按照定义的格式处理输入并产生预期格式的输出。这使得 SythesizedFunction 在 LLM 执行结构化数据提取任务,或者预期 LLM 输出结构化数据的场景中尤其有用。
代码解释器
Flappy 中的代码解释器作为 ChatGPT 代码解释器的等效替代品,使语言模型能够通过 Python 代码满足复杂的用户需求。Flappy 的代码解释器与市场上其他开源实现的区别在于其沙盒化的安全特性。这确保了它满足生产环境部署所必需的严格的安全需求。
- NodeJS (TypeScript)
- Java
- Kotlin
- C#
import { createFlappyAgent, createInvokeFunction, createSynthesizedFunction, createCodeInterpreter, z } from '@pleisto/node-flappy'
enum Verdict {
Innocent = 'Innocent',
Guilty = 'Guilty',
Unknown = 'Unknown'
}
const MOCK_LAWSUIT_DATA =
"As Alex Jones continues telling his Infowars audience about his money problems and pleads for them to buy his products, his own documents show life is not all that bad — his net worth is around $14 million and his personal spending topped $93,000 in July alone, including thousands of dollars on meals and entertainment. The conspiracy theorist and his lawyers file monthly financial reports in his personal bankruptcy case, and the latest one has struck a nerve with the families of victims of Sandy Hook Elementary School shooting. They're still seeking the $1.5 billion they won last year in lawsuits against Jones and his media company for repeatedly calling the 2012 massacre a hoax on his shows. “It is disturbing that Alex Jones continues to spend money on excessive household expenditures and his extravagant lifestyle when that money rightfully belongs to the families he spent years tormenting,” said Christopher Mattei, a Connecticut lawyer for the families. “The families are increasingly concerned and will continue to contest these matters in court.” In an Aug. 29 court filing, lawyers for the families said that if Jones doesn’t reduce his personal expenses to a “reasonable” level, they will ask the bankruptcy judge to bar him from “further waste of estate assets,” appoint a trustee to oversee his spending, or dismiss the bankruptcy case. On his Infowars show Tuesday, Jones said he’s not doing anything wrong."
const agent = createFlappyAgent({
llm: chatGpt,
// Define your agent's features.
features: [
createCodeInterpreter(),
createSynthesizedFunction({
name: 'getMeta',
description: 'Extract meta data from a lawsuit full text.',
args: z.object({
lawsuit: z.string().describe('Lawsuit full text.')
}),
returnType: z.object({
verdict: z.nativeEnum(Verdict),
plaintiff: z.string(),
defendant: z.string(),
judgeOptions: z.array(z.string())
})
}),
createInvokeFunction({
name: 'getLatestLawsuitsByPlaintiff',
description: 'Get the latest lawsuits by plaintiff.',
args: z.object({
plaintiff: z.string(),
arg1: z.boolean().describe('For demo purpose. set to False'),
arg2: z.array(z.string()).describe('ignore it').optional()
}),
returnType: z.string(),
resolve: async args => {
// Do something
// e.g. query SQL database
console.debug('getLatestLawsuitsByPlaintiff called', args)
return MOCK_LAWSUIT_DATA
}
})
]
})
public class Law {
public static final String LAW_EXECUTE_PLAN_PROMPT = "Find the latest case with the plaintiff being families of victims and return its metadata.";
static final String MOCK_LAWSUIT_DATA =
"As Alex Jones continues telling his Infowars audience about his money problems and pleads for them to buy his products, his own documents show life is not all that bad — his net worth is around $14 million and his personal spending topped $93,000 in July alone, including thousands of dollars on meals and entertainment. The conspiracy theorist and his lawyers file monthly financial reports in his personal bankruptcy case, and the latest one has struck a nerve with the families of victims of Sandy Hook Elementary School shooting. They're still seeking the $1.5 billion they won last year in lawsuits against Jones and his media company for repeatedly calling the 2012 massacre a hoax on his shows. “It is disturbing that Alex Jones continues to spend money on excessive household expenditures and his extravagant lifestyle when that money rightfully belongs to the families he spent years tormenting,” said Christopher Mattei, a Connecticut lawyer for the families. “The families are increasingly concerned and will continue to contest these matters in court.” In an Aug. 29 court filing, lawyers for the families said that if Jones doesn’t reduce his personal expenses to a “reasonable” level, they will ask the bankruptcy judge to bar him from “further waste of estate assets,” appoint a trustee to oversee his spending, or dismiss the bankruptcy case. On his Infowars show Tuesday, Jones said he’s not doing anything wrong.";
public static FlappyFeatureBase<?, ?> lawGetLatestLawsuitsByPlaintiff = new FlappyInvokeFunction(
"getLatestLawsuitsByPlaintiff",
"Get the latest lawsuits by plaintiff.",
GetLatestLawsuitsArguments.class,
String.class,
(a, agent, $completion) -> MOCK_LAWSUIT_DATA
);
public static FlappyFeatureBase<?, ?> lawGetMeta = new FlappySynthesizedFunction(
"getMeta",
"Extract meta data from a lawsuit full text.",
LawMetaArguments.class,
LawMetaReturn.class
);
public static void main(String[] args) throws ExecutionException, InterruptedException {
Dotenv dotenv = Dotenv.load();
ChatGPT llm = new ChatGPT(new ChatGPT.ChatGPTConfig(null, dotenv.get("OPENAI_TOKEN"), dotenv.get("OPENAI_API_BASE")));
FlappyBaseAgent agent = new FlappyBaseAgent(
llm, Arrays.asList(lawGetMeta, lawGetLatestLawsuitsByPlaintiff)
);
}
public enum Verdict {
Innocent, Guilty, Unknown
}
public static class LawMetaReturn {
@FlappyField
Verdict verdict;
@FlappyField
String plaintiff;
@FlappyField
String defendant;
@FlappyField
List<String> judgeOptions;
public Verdict getVerdict() {
return verdict;
}
public void setVerdict(Verdict verdict) {
this.verdict = verdict;
}
public String getPlaintiff() {
return plaintiff;
}
public void setPlaintiff(String plaintiff) {
this.plaintiff = plaintiff;
}
public String getDefendant() {
return defendant;
}
public void setDefendant(String defendant) {
this.defendant = defendant;
}
public List<String> getJudgeOptions() {
return judgeOptions;
}
public void setJudgeOptions(List<String> judgeOptions) {
this.judgeOptions = judgeOptions;
}
}
static class GetLatestLawsuitsArguments {
@FlappyField
String plaintiff;
@FlappyField(description = "For demo purpose. set to False")
Boolean arg1;
@FlappyField(description = "ignore it", optional = true)
List<String> arg2 = null;
public String getPlaintiff() {
return plaintiff;
}
public void setPlaintiff(String plaintiff) {
this.plaintiff = plaintiff;
}
public Boolean getArg1() {
return arg1;
}
public void setArg1(Boolean arg1) {
this.arg1 = arg1;
}
public List<String> getArg2() {
return arg2;
}
public void setArg2(List<String> arg2) {
this.arg2 = arg2;
}
}
static class LawMetaArguments {
@FlappyField(description = "Lawsuit full text.")
String lawsuit;
public String getLawsuit() {
return lawsuit;
}
public void setLawsuit(String lawsuit) {
this.lawsuit = lawsuit;
}
}
}
import flappy.FlappyBaseAgent
import flappy.annotations.FlappyField
import flappy.features.FlappyInvokeFunction
import flappy.features.FlappySynthesizedFunction
import flappy.llms.ChatGPT
import io.github.cdimascio.dotenv.dotenv
enum class Verdict {
Innocent, Guilty, Unknown
}
const val MOCK_LAWSUIT_DATA =
"""As Alex Jones continues telling his Infowars audience about his money problems and pleads for them to buy his products, his own documents show life is not all that bad — his net worth is around $14 million and his personal spending topped $93,000 in July alone, including thousands of dollars on meals and entertainment. The conspiracy theorist and his lawyers file monthly financial reports in his personal bankruptcy case, and the latest one has struck a nerve with the families of victims of Sandy Hook Elementary School shooting. They're still seeking the $1.5 billion they won last year in lawsuits against Jones and his media company for repeatedly calling the 2012 massacre a hoax on his shows. “It is disturbing that Alex Jones continues to spend money on excessive household expenditures and his extravagant lifestyle when that money rightfully belongs to the families he spent years tormenting,” said Christopher Mattei, a Connecticut lawyer for the families. “The families are increasingly concerned and will continue to contest these matters in court.” In an Aug. 29 court filing, lawyers for the families said that if Jones doesn’t reduce his personal expenses to a “reasonable” level, they will ask the bankruptcy judge to bar him from “further waste of estate assets,” appoint a trustee to oversee his spending, or dismiss the bankruptcy case. On his Infowars show Tuesday, Jones said he’s not doing anything wrong."""
class LawMetaArguments(
@FlappyField(description = "Lawsuit full text.")
val lawsuit: String
)
class LawMetaReturn(
@FlappyField
val verdict: Verdict,
@FlappyField
val plaintiff: String,
@FlappyField
val defendant: String,
@FlappyField
val judgeOptions: List<String>
)
val lawGetMeta = FlappySynthesizedFunction(
name = "getMeta",
description = "Extract meta data from a lawsuit full text.",
args = LawMetaArguments::class.java,
returnType = LawMetaReturn::class.java,
)
class GetLatestLawsuitsArguments(
@FlappyField
val plaintiff: String,
@FlappyField(description = "For demo purpose. set to False")
val arg1: Boolean,
@FlappyField(description = "ignore it", optional = true)
val arg2: List<String>?
)
val lawGetLatestLawsuitsByPlaintiff = FlappyInvokeFunction(
name = "getLatestLawsuitsByPlaintiff",
description = "Get the latest lawsuits by plaintiff.",
args = GetLatestLawsuitsArguments::class.java,
returnType = String::class.java,
invoker = { _, _ -> MOCK_LAWSUIT_DATA }
)
const val LAW_EXECUTE_PLAN_PROMPT =
"Find the latest case with the plaintiff being families of victims and return its metadata."
suspend fun main(args: Array<String>) {
val dotenv = dotenv()
val chatGPT = ChatGPT(
ChatGPT.ChatGPTConfig(token = dotenv["OPENAI_TOKEN"], host = dotenv["OPENAI_API_BASE"])
)
val agent = FlappyBaseAgent(
maxRetry = 2,
inferenceLLM = chatGPT,
features = listOf(lawGetMeta, lawGetLatestLawsuitsByPlaintiff)
)
}
internal class LawCase
{
public static void Main()
{
var gpt35 = new ChatGPT(new OpenAIAPI
{
Auth = new APIAuthentication(apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")),
ApiUrlFormat = Environment.GetEnvironmentVariable("OPENAI_API_URL"),
ApiVersion = "v1",
}, "gpt-3.5-turbo", null, Logger.CreateLogger<ChatGPT>());
var lawAgent = new FlappyAgent(new FlappyAgentConfig
{
LLM = gpt35,
Features = new IFlappyFeature[]
{
new SynthesizedFeature<getMeta_Args,getMeta_Return,FlappyFeatureOption>(new SynthesizedFeatureDefinition<getMeta_Args,getMeta_Return>
{
Name = "getMeta",
Description = "Extract meta data from a lawsuit full text.",
Args = new getMeta_Args(),
ReturnType = new getMeta_Return()
}),
new InvokeFeature<getLatestLawsuits_Args,getMeta_Args,FlappyFeatureOption>(new InvokeFeatureDefinition<getLatestLawsuits_Args, getMeta_Args>
{
Name = "getLatestLawsuitsByPlaintiff",
Description= "Get the latest lawsuits by plaintiff.",
Args = new getLatestLawsuits_Args(),
ReturnType = new getMeta_Args(),
Resolve = (args) =>
{
Console.WriteLine($"====================== getLatestLawsuitsByPlaintiff call =========================");
Console.WriteLine($"getLatestLawsuitsByPlaintiff called");
Console.WriteLine(JObject.FromObject(args).ToString());
Console.WriteLine($"====================== getLatestLawsuitsByPlaintiff call =========================");
return Task.FromResult(new getMeta_Args
{
lawsuit =MOCK_LAWSUIT_DATA
});
}
})
},
}, null, null, Logger.CreateLogger<FlappyAgent>());
}
private const string LAW_EXECUTE_PLAN_PROMPT = "Find the resume of a frontend engineer and return their metadata.";
private const string MOCK_LAWSUIT_DATA =
"As Alex Jones continues telling his Infowars audience about his money problems and pleads for them to buy his products, his own documents show life is not all that bad — his net worth is around $14 million and his personal spending topped $93,000 in July alone, including thousands of dollars on meals and entertainment. The conspiracy theorist and his lawyers file monthly financial reports in his personal bankruptcy case, and the latest one has struck a nerve with the families of victims of Sandy Hook Elementary School shooting. They're still seeking the $1.5 billion they won last year in lawsuits against Jones and his media company for repeatedly calling the 2012 massacre a hoax on his shows. “It is disturbing that Alex Jones continues to spend money on excessive household expenditures and his extravagant lifestyle when that money rightfully belongs to the families he spent years tormenting,” said Christopher Mattei, a Connecticut lawyer for the families. “The families are increasingly concerned and will continue to contest these matters in court.” In an Aug. 29 court filing, lawyers for the families said that if Jones doesn’t reduce his personal expenses to a “reasonable” level, they will ask the bankruptcy judge to bar him from “further waste of estate assets,” appoint a trustee to oversee his spending, or dismiss the bankruptcy case. On his Infowars show Tuesday, Jones said he’s not doing anything wrong.";
}
internal class getLatestLawsuits_Args
{
public string plantiff { get; set; }
[Description("For demo purpose. set to False")]
public bool arg1 { get; set; }
[Description("ignore it")]
public bool arg2 { get; set; }
public override string ToString()
{
return JObject.FromObject(this).ToString();
}
}
internal class getMeta_Args
{
[Description("Lawsuit full text.")]
public string lawsuit { get; set; }
public override string ToString()
{
return JObject.FromObject(this).ToString();
}
}
[JsonObject(ItemRequired = Required.Always)]
public class getMeta_Return
{
[JsonConverter(typeof(StringEnumConverter))]
[DefaultValue(Verdict.Unknow)]
public Verdict verdict { get; set; } = Verdict.Unknow;
public string plaintiff { get; set; } = string.Empty;
public string defendant { get; set; } = string.Empty;
public string[] judgeOptions { get; set; } = Array.Empty<string>();
public override string ToString()
{
return JObject.FromObject(this).ToString();
}
}
public enum Verdict
{
Innocent,
Guilty,
Unknow
}