@ 边界ml/ nextjs
Next.js 为BAML集成,为服务器组件,服务器动作和流回响应提供无缝支持.
安装
npm install @boundaryml/baml @boundaryml/nextjs
设置
- 更新您的 Next.js 配置 :
// next.config.ts
import { withBaml } from '@boundaryml/nextjs';
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
// ... your existing config
};
export default withBaml()(nextConfig);
- 在您的服务器动作中使用 BAML 函数 :
// app/actions/story.ts
'use server'
import { b } from "@/baml_client";
export async function writeMeAStoryAction(prompt: string) {
return b.WriteMeAStory.stream(prompt).toStreamable();
}
- 使用您反应组件中生成的钩子 :
// app/components/story.tsx
'use client'
import { useWriteMeAStoryAction } from "@/baml_client/nextjs";
export function StoryForm() {
const {
data: finalStory,
partialData: streamingStory,
isLoading,
isError,
error,
mutate
} = useWriteMeAStoryAction();
const story = isLoading ? streamingStory : finalStory;
return (
<div>
<button onClick={() => mutate("Once upon a time...")}>
Generate Story
</button>
{isLoading && <p>Generating story...</p>}
{story && (
<div>
<h2>{story.title}</h2>
<p>{story.content}</p>
</div>
)}
</div>
);
}
特征
- QQ 安全: 在服务器上运行 BAML 函数以保持 API 密钥的安全
- QQ 流: 内置支持流响应
- QQ 类型安全: 所有 BAML 函数的完整类型脚本支持
- QQ快:优化了Next.js App路由器和回放服务器组件
- 简单:零配置设置
withBaml
API 参考
withBaml(config?: BamlNextConfig)
将您的 Next.js 配置与 BAML 集成 .
interface BamlNextConfig {
webpack?: NextConfig['webpack']; // Custom webpack configuration
}
生成的钩子
对于每个BAML函数,生成一个相应的反应钩,其界面如下:
interface BamlStreamHookResult<T> {
data?: T; // Final result
partialData?: T; // Streaming result
isLoading: boolean; // Loading state
error?: Error; // Error state
mutate: (input: any) => Promise<void>; // Function to call the BAML function
}
许可证
麻省理工学院