Compare commits

..

13 Commits

Author SHA1 Message Date
github-actions[bot] 5478ba88b1 Release 0.9.10 (#1728)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: marcusschiesser <17126+marcusschiesser@users.noreply.github.com>
2025-03-11 13:47:43 +07:00
Marcus Schiesser aea550aff4 feat: Add factory convenience factory for each LLM provider, e.g. you… (#1731) 2025-03-11 13:42:09 +07:00
Marcus Schiesser e66c6e25fb feat: add tool factory method (#1730) 2025-03-11 12:57:13 +07:00
Marcus Schiesser 40ee7610b2 feat: add asQueryTool to index and add factory methods for simplifying agent usage (#1715) 2025-03-11 11:06:21 +07:00
yangqiao c14a21bc0b fix: Add user agent for AzureCosmosDBMongoDBVectorStore (#1729)
Co-authored-by: yangqiao <yangqiao@microsoft.com>
2025-03-10 18:08:28 +07:00
Thomas Vanier 33f98565ab fix: google start chat tools params (#1716)
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2025-03-10 18:07:36 +07:00
Huu Le b5cb35a732 chore: add unit test for agent workflow (#1704) 2025-03-10 16:44:49 +07:00
Thuc Pham c1b5be5182 feat: make AgentWorkflow llm param optional (#1727) 2025-03-10 11:48:51 +07:00
Alex Yang 6f8b68ac5f chore: fix turbo.json (#1724) 2025-03-09 01:45:28 -08:00
Alex Yang e075643b50 chore: bump bunchee (#1725) 2025-03-09 01:33:33 -08:00
Alex Yang f71b143ceb chore: add tailwindcss prettier (#1723) 2025-03-09 01:11:27 -08:00
Alex Yang ead4a80a3a feat(docs): improve misc (#1722) 2025-03-09 00:57:47 -08:00
Alex Yang da78689e24 fix(docs): use docs.toFumadocsSource (#1721) 2025-03-09 00:34:49 -08:00
200 changed files with 2565 additions and 1026 deletions
+16
View File
@@ -1,5 +1,21 @@
# @llamaindex/doc
## 0.1.10
### Patch Changes
- Updated dependencies [aea550a]
- Updated dependencies [c1b5be5]
- Updated dependencies [40ee761]
- Updated dependencies [40ee761]
- @llamaindex/openai@0.1.60
- llamaindex@0.9.10
- @llamaindex/workflow@0.0.16
- @llamaindex/core@0.5.8
- @llamaindex/cloud@3.0.9
- @llamaindex/node-parser@1.0.8
- @llamaindex/readers@2.0.8
## 0.1.9
### Patch Changes
+1 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/doc",
"version": "0.1.9",
"version": "0.1.10",
"private": true,
"scripts": {
"postinstall": "fumadocs-mdx",
@@ -51,7 +51,6 @@
"react-dom": "^19.0.0",
"react-icons": "^5.3.0",
"react-monaco-editor": "^0.56.2",
"react-text-transition": "^3.1.0",
"react-use-measure": "^2.1.1",
"rehype-katex": "^7.0.1",
"remark-math": "^6.0.0",
+5 -1
View File
@@ -4,4 +4,8 @@ import { updateLlamaCloud } from "./update-llamacloud.mjs";
env.loadEnvConfig(process.cwd());
await updateLlamaCloud();
if (process.env.VERCEL_ENV === "production") {
updateLlamaCloud().catch((error) => {
console.error(error);
});
}
+6 -1
View File
@@ -2,6 +2,7 @@ import { rehypeCodeDefaultOptions } from "fumadocs-core/mdx-plugins";
import { fileGenerator, remarkDocGen, remarkInstall } from "fumadocs-docgen";
import { defineConfig, defineDocs } from "fumadocs-mdx/config";
import { transformerTwoslash } from "fumadocs-twoslash";
import { createFileSystemTypesCache } from "fumadocs-twoslash/cache-fs";
import rehypeKatex from "rehype-katex";
import remarkMath from "remark-math";
@@ -20,7 +21,11 @@ export default defineConfig({
},
transformers: [
...(rehypeCodeDefaultOptions.transformers ?? []),
transformerTwoslash(),
transformerTwoslash({
typesCache: createFileSystemTypesCache({
dir: ".next/cache/twoslash",
}),
}),
{
name: "transformers:remove-notation-escape",
code(hast) {
+17 -16
View File
@@ -8,7 +8,7 @@ import {
} from "@/components/infinite-providers";
import { MagicMove } from "@/components/magic-move";
import { NpmInstall } from "@/components/npm-install";
import { TextEffect } from "@/components/text-effect";
import { Supports } from "@/components/supports";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { LEGACY_DOCUMENT_URL } from "@/lib/const";
@@ -24,18 +24,18 @@ import { Suspense } from "react";
export default function HomePage() {
return (
<main className="container mx-auto px-4 py-12">
<h1 className="text-4xl md:text-6xl font-bold text-center mb-4">
<h1 className="mb-4 text-center text-4xl font-bold md:text-6xl">
Build context-augmented web apps using
<br /> <span className="text-blue-500">LlamaIndex.TS</span>
</h1>
<p className="text-xl text-center text-fd-muted-foreground mb-12 ">
<p className="text-fd-muted-foreground mb-12 text-center text-xl">
LlamaIndex.TS is the JS/TS version of{" "}
<a href="https://llamaindex.ai">LlamaIndex</a>, the framework for
building agentic generative AI applications connected to your data.
</p>
<div className="text-center text-lg text-fd-muted-foreground mb-12">
<div className="text-fd-muted-foreground mb-12 text-center text-lg">
<span>Designed for building web applications in </span>
<TextEffect />
<Supports />
</div>
<div className="flex flex-wrap justify-center gap-4">
@@ -125,19 +125,20 @@ const response = await agent.chat({
description="Truly powerful retrieval-augmented generation applications use agentic techniques, and LlamaIndex.TS makes it easy to build them."
>
<CodeBlock
code={`import { FunctionTool } from "llamaindex";
import { OpenAIAgent } from "@llamaindex/openai";
code={`import { agent } from "llamaindex";
import { OpenAI } from "@llamaindex/openai";
const interpreterTool = FunctionTool.from(...);
const systemPrompt = \`...\`;
// using a previously created LlamaIndex index to query information from
const queryTool = index.queryTool();
const agent = new OpenAIAgent({
llm,
tools: [interpreterTool],
systemPrompt,
const agent = agent({
llm: new OpenAI({
model: "gpt-4o",
}),
tools: [queryTool],
});
await agent.chat('...');`}
await agent.run('...');`}
lang="ts"
/>
</Feature>
@@ -149,13 +150,13 @@ await agent.chat('...');`}
>
<div className="mt-8 flex flex-col gap-8">
<div>
<h3 className="text-lg font-semibold text-fd-muted-foreground mb-2">
<h3 className="text-fd-muted-foreground mb-2 text-lg font-semibold">
LLMs
</h3>
<InfiniteLLMProviders />
</div>
<div>
<h3 className="text-lg font-semibold text-fd-muted-foreground mb-2">
<h3 className="text-fd-muted-foreground mb-2 text-lg font-semibold">
Vector Stores
</h3>
<InfiniteVectorStoreProviders />
@@ -13,6 +13,8 @@ import { notFound } from "next/navigation";
const { AutoTypeTable } = createTypeTable();
export const revalidate = false;
export default async function Page(props: {
params: Promise<{ slug?: string[] }>;
}) {
@@ -26,6 +28,7 @@ export default async function Page(props: {
<DocsPage
toc={page.data.toc}
full={page.data.full}
lastUpdate={page.data.lastModified}
editOnGithub={{
owner: "run-llama",
repo: "LlamaIndexTS",
+1 -1
View File
@@ -22,7 +22,7 @@ export default function Layout({ children }: { children: ReactNode }) {
variant: "secondary",
size: "xs",
className:
"md:flex-1 px-2 ms-2 gap-1.5 text-fd-muted-foreground rounded-full",
"text-fd-muted-foreground ms-2 gap-1.5 rounded-full px-2 md:flex-1",
}),
)}
>
+1 -1
View File
@@ -32,7 +32,7 @@ export default function Layout({ children }: { children: ReactNode }) {
href="/favicon-16x16.png"
/>
</head>
<body className="flex flex-col min-h-screen">
<body className="flex min-h-screen flex-col">
<TooltipProvider>
<AIProvider>
<RootProvider>{children}</RootProvider>
+62
View File
@@ -0,0 +1,62 @@
import fg from "fast-glob";
import { fileGenerator, remarkDocGen, remarkInstall } from "fumadocs-docgen";
import { remarkInclude } from "fumadocs-mdx/config";
import { remarkAutoTypeTable } from "fumadocs-typescript";
import matter from "gray-matter";
import * as fs from "node:fs/promises";
import path from "node:path";
import { remark } from "remark";
import remarkGfm from "remark-gfm";
import remarkMdx from "remark-mdx";
import remarkStringify from "remark-stringify";
export const revalidate = false;
export async function GET() {
const files = await fg([
"./src/content/docs/**/*.mdx",
// remove generated openapi files
"!./src/content/docs/cloud/api/**/*",
]);
const scan = files.map(async (file) => {
const fileContent = await fs.readFile(file);
const { content, data } = matter(fileContent.toString());
const dir = path.dirname(file).split(path.sep).at(4);
const category = {
llamaindex: "LlamaIndexTS Framework",
api: "LlamaIndexTS API",
cloud: "LlamaCloud Service",
}[dir ?? ""];
const processed = await processContent(file, content);
return `file: ${file}
# ${category}: ${data.title}
${data.description}
${processed}`;
});
const scanned = await Promise.all(scan);
return new Response(scanned.join("\n\n"));
}
async function processContent(path: string, content: string): Promise<string> {
const file = await remark()
.use(remarkMdx)
.use(remarkInclude)
.use(remarkGfm)
.use(remarkAutoTypeTable)
.use(remarkDocGen, { generators: [fileGenerator()] })
.use(remarkInstall, { persist: { id: "package-manager" } })
.use(remarkStringify)
.process({
path,
value: content,
});
return String(file);
}
+5 -5
View File
@@ -45,13 +45,13 @@ export const AITrigger = (props: AITriggerProps) => {
<Dialog>
<DialogTrigger {...props} />
<DialogPortal>
<DialogOverlay className="fixed inset-0 z-50 bg-fd-background/50 backdrop-blur-sm data-[state=closed]:animate-fd-fade-out data-[state=open]:animate-fd-fade-in" />
<DialogOverlay className="bg-fd-background/50 data-[state=closed]:animate-fd-fade-out data-[state=open]:animate-fd-fade-in fixed inset-0 z-50 backdrop-blur-sm" />
<DialogContent
onOpenAutoFocus={(e) => {
document.getElementById("nd-ai-input")?.focus();
e.preventDefault();
}}
className="fixed left-1/2 z-50 my-[5vh] flex max-h-[90dvh] w-[98vw] max-w-[860px] origin-left -translate-x-1/2 flex-col rounded-lg border bg-fd-popover text-fd-popover-foreground shadow-lg focus-visible:outline-none data-[state=closed]:animate-fd-dialog-out data-[state=open]:animate-fd-dialog-in"
className="bg-fd-popover text-fd-popover-foreground data-[state=closed]:animate-fd-dialog-out data-[state=open]:animate-fd-dialog-in fixed left-1/2 z-50 my-[5vh] flex max-h-[90dvh] w-[98vw] max-w-[860px] origin-left -translate-x-1/2 flex-col rounded-lg border shadow-lg focus-visible:outline-none"
>
<DialogHeader>
<DialogTitle className="sr-only">Search AI</DialogTitle>
@@ -67,11 +67,11 @@ export const AITrigger = (props: AITriggerProps) => {
</AlertDescription>
</Alert>
</DialogHeader>
<div className="overflow-scroll flex-grow mt-4">
<div className="mt-4 flex-grow overflow-scroll">
<ChatList messages={messages} />
</div>
<form
className="px-4 py-2 space-y-4"
className="space-y-4 px-4 py-2"
action={async () => {
const value = inputValue.trim();
setInputValue("");
@@ -102,7 +102,7 @@ export const AITrigger = (props: AITriggerProps) => {
}
}}
>
<div className="flex flex-row w-full items-center gap-2">
<div className="flex w-full flex-row items-center gap-2">
<Textarea
tabIndex={0}
placeholder="Ask AI about documentation."
+1 -1
View File
@@ -10,7 +10,7 @@ export function Contributing(): ReactElement {
<h2 className="mb-4 text-xl font-semibold sm:text-2xl">
Made possible by you <Heart className="inline align-middle" />
</h2>
<p className="mb-4 text-fd-muted-foreground">
<p className="text-fd-muted-foreground mb-4">
LlamaIndex.TS is powered by the open source community.
</p>
<div className="mb-8 flex flex-row items-center gap-2">
@@ -33,7 +33,7 @@ export default async function ContributorCounter({
href={`https://github.com/${contributor.login}`}
rel="noreferrer noopener"
target="_blank"
className="size-10 overflow-hidden rounded-full border-4 border-fd-background bg-fd-background md:-mr-4 md:size-12"
className="border-fd-background bg-fd-background size-10 overflow-hidden rounded-full border-4 md:-mr-4 md:size-12"
style={{
zIndex: topContributors.length - i,
}}
@@ -48,7 +48,7 @@ export default async function ContributorCounter({
</a>
))}
{displayCount < contributors.length ? (
<div className="size-12 content-center rounded-full bg-fd-secondary text-center">
<div className="bg-fd-secondary size-12 content-center rounded-full text-center">
+{contributors.length - displayCount}
</div>
) : null}
@@ -83,7 +83,7 @@ export function CreateAppAnimation(): React.ReactElement {
}}
>
{tick > timeWindowOpen && (
<LaunchAppWindow className="absolute bottom-5 right-4 z-10 animate-in fade-in slide-in-from-top-10" />
<LaunchAppWindow className="animate-in fade-in slide-in-from-top-10 absolute bottom-5 right-4 z-10" />
)}
<pre className="overflow-hidden rounded-xl border text-xs">
<div className="flex flex-row items-center gap-2 border-b px-4 py-2">
@@ -92,7 +92,7 @@ export function CreateAppAnimation(): React.ReactElement {
<div className="grow" />
<div className="size-2 rounded-full bg-red-400" />
</div>
<div className="min-h-[200px] bg-gradient-to-b from-fd-secondary [mask-image:linear-gradient(to_bottom,white,transparent)]">
<div className="from-fd-secondary min-h-[200px] bg-gradient-to-b [mask-image:linear-gradient(to_bottom,white,transparent)]">
<code className="grid p-4">{lines}</code>
</div>
</pre>
@@ -103,7 +103,7 @@ export function CreateAppAnimation(): React.ReactElement {
function UserMessage({ children }: { children: ReactNode }) {
return (
<div className="group relative flex items-start">
<div className="flex h-8 w-8 shrink-0 select-none items-center justify-center rounded-md border shadow-sm bg-background">
<div className="bg-background flex h-8 w-8 shrink-0 select-none items-center justify-center rounded-md border shadow-sm">
<IconUser />
</div>
<div className="ml-4 flex-1 space-y-2 overflow-hidden px-1">
@@ -122,7 +122,7 @@ function BotMessage({
}) {
return (
<div className={cn("group relative flex items-start", className)}>
<div className="flex h-8 w-8 shrink-0 select-none items-center justify-center rounded-md border shadow-sm bg-primary text-primary-foreground">
<div className="bg-primary text-primary-foreground flex h-8 w-8 shrink-0 select-none items-center justify-center rounded-md border shadow-sm">
<IconAI />
</div>
<div className="ml-4 flex-1 space-y-2 overflow-hidden px-1">
@@ -164,7 +164,7 @@ export function ChatExample() {
return (
<div className="max-w-64">
<div className="flex flex-col px-4 gap-2">
<div className="flex flex-col gap-2 px-4">
{userMessageLength === userMessageFull.length && (
<UserMessage>
<span>{userMessageFull}</span>
@@ -204,11 +204,11 @@ function LaunchAppWindow(
<div
{...props}
className={cn(
"overflow-hidden rounded-md border bg-fd-background shadow-xl",
"bg-fd-background overflow-hidden rounded-md border shadow-xl",
props.className,
)}
>
<div className="relative flex h-6 flex-row items-center border-b bg-fd-muted px-4 text-xs text-fd-muted-foreground">
<div className="bg-fd-muted text-fd-muted-foreground relative flex h-6 flex-row items-center border-b px-4 text-xs">
<p className="absolute inset-x-0 text-center">localhost:8080</p>
</div>
<div className="p-4 text-sm">
@@ -57,7 +57,7 @@ export const IDE = () => {
const maxChars = useSlider();
const useSetMaxChars = useSetSlider();
return (
<div className="flex flex-col p-4 border-r max-h-96 overflow-scroll">
<div className="flex max-h-96 flex-col overflow-scroll border-r p-4">
<div>
<Label>Max Chars {maxChars}</Label>
<Slider
@@ -113,7 +113,7 @@ const Preview = ({ text }: { text: string }) => {
},
},
});
return <CodeBlock className="py-0 m-2">{rendered}</CodeBlock>;
return <CodeBlock className="m-2 py-0">{rendered}</CodeBlock>;
};
function ScrollToBottom() {
@@ -122,7 +122,7 @@ function ScrollToBottom() {
return (
!isAtBottom && (
<button
className="absolute i-ph-arrow-circle-down-fill text-4xl rounded-lg left-[50%] translate-x-[-50%] bottom-0"
className="i-ph-arrow-circle-down-fill absolute bottom-0 left-[50%] translate-x-[-50%] rounded-lg text-4xl"
onClick={() => scrollToBottom()}
/>
)
@@ -136,7 +136,7 @@ export const NodePreview = () => {
const textChunks = useMemo(() => parser.splitText(code), [code, maxChars]);
return (
<StickToBottom
className="block relative max-h-96 overflow-scroll"
className="relative block max-h-96 overflow-scroll"
resize="smooth"
initial="smooth"
>
@@ -154,7 +154,7 @@ export const CodeNodeParserDemo = () => {
const isClient = useIsClient();
if (!isClient) {
return (
<div className="my-2 grid grid-cols-1 md:grid-cols-2 gap-2 border rounded-xl w-full max-h-96">
<div className="my-2 grid max-h-96 w-full grid-cols-1 gap-2 rounded-xl border md:grid-cols-2">
<Skeleton className="h-96" />
<Skeleton className="h-96" />
</div>
@@ -165,13 +165,13 @@ export const CodeNodeParserDemo = () => {
<CodeProvider>
<Suspense
fallback={
<div className="my-2 grid grid-cols-1 md:grid-cols-2 gap-2 border rounded-xl w-full max-h-96">
<div className="my-2 grid max-h-96 w-full grid-cols-1 gap-2 rounded-xl border md:grid-cols-2">
<Skeleton className="h-96" />
<Skeleton className="h-96" />
</div>
}
>
<div className="my-2 grid grid-cols-1 md:grid-cols-2 gap-2 border rounded-xl w-full max-h-96">
<div className="my-2 grid max-h-96 w-full grid-cols-1 gap-2 rounded-xl border md:grid-cols-2">
<IDE />
<NodePreview />
</div>
@@ -75,7 +75,7 @@ function ScrollToBottom() {
return (
!isAtBottom && (
<button
className="absolute i-ph-arrow-circle-down-fill text-4xl rounded-lg left-[50%] translate-x-[-50%] bottom-0"
className="i-ph-arrow-circle-down-fill absolute bottom-0 left-[50%] translate-x-[-50%] rounded-lg text-4xl"
onClick={() => scrollToBottom()}
/>
)
@@ -91,9 +91,9 @@ export function WorkflowStreamingDemo() {
const [total, setTotal] = useState<number>(10);
return (
<div className="flex flex-col items-start w-full gap-2">
<div className="flex flex-row justify-center items-center">
<div className="text-lg mr-2">Compute total</div>{" "}
<div className="flex w-full flex-col items-start gap-2">
<div className="flex flex-row items-center justify-center">
<div className="mr-2 text-lg">Compute total</div>{" "}
<FlowInput value={total} onChange={(value) => setTotal(value)} />
</div>
<Button
@@ -141,7 +141,7 @@ export function WorkflowStreamingDemo() {
>
Start Workflow
</Button>
<StickToBottom className="w-full flex flex-col gap-2 p-2 border border-gray-200 rounded-lg max-h-96 overflow-y-auto">
<StickToBottom className="flex max-h-96 w-full flex-col gap-2 overflow-y-auto rounded-lg border border-gray-200 p-2">
<StickToBottom.Content className="flex flex-col gap-2">
{ui}
</StickToBottom.Content>
+1 -1
View File
@@ -20,7 +20,7 @@ export function Feature({
className={cn("border-l border-t px-6 py-12 md:py-16", className)}
{...props}
>
<div className="mb-4 inline-flex items-center gap-2 text-sm font-medium text-fd-muted-foreground">
<div className="text-fd-muted-foreground mb-4 inline-flex items-center gap-2 text-sm font-medium">
<Icon className="size-4" />
<p>{subheading}</p>
</div>
+1 -1
View File
@@ -60,7 +60,7 @@ export default function FlowInput({
className={clsx(
showCaret ? "caret-primary" : "caret-transparent",
"spin-hide w-[1.5em] bg-transparent py-2 text-center font-[inherit] text-transparent outline-none",
"[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",
"[appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none",
)}
// Make sure to disable kerning, to match NumberFlow:
style={{ fontKerning: "none" }}
+2 -2
View File
@@ -8,7 +8,7 @@ import { IconAI, IconUser } from "./ui/icons";
export function UserMessage({ children }: { children: ReactNode }) {
return (
<div className="group relative flex items-start">
<div className="flex h-8 w-8 shrink-0 select-none items-center justify-center rounded-md border shadow-sm bg-background">
<div className="bg-background flex h-8 w-8 shrink-0 select-none items-center justify-center rounded-md border shadow-sm">
<IconUser />
</div>
<div className="ml-4 flex-1 space-y-2 overflow-hidden px-1">
@@ -54,7 +54,7 @@ export function BotCard({
<div className="group relative flex items-start md:-ml-12">
<div
className={cn(
"flex h-8 w-8 shrink-0 select-none items-center justify-center rounded-md border shadow-sm bg-primary text-primary-foreground",
"bg-primary text-primary-foreground flex h-8 w-8 shrink-0 select-none items-center justify-center rounded-md border shadow-sm",
!showAvatar && "invisible",
)}
>
+1 -1
View File
@@ -25,7 +25,7 @@ export const NpmInstall = () => {
className="flex flex-row items-center justify-center"
>
<code className="mr-2">$ npm i llamaindex</code>
<div className="relative cursor-pointer bg-transparent w-4 h-4">
<div className="relative h-4 w-4 cursor-pointer bg-transparent">
<div
className={`absolute inset-0 transform transition-all duration-300 ${
hasCheckIcon ? "scale-0 opacity-0" : "scale-100 opacity-100"
@@ -0,0 +1,268 @@
import { cn } from "@/lib/utils";
import {
AnimatePresence,
motion,
Transition,
type AnimationControls,
type Target,
type TargetAndTransition,
type VariantLabels,
} from "framer-motion";
import React, {
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useMemo,
useState,
} from "react";
export interface RotatingTextRef {
next: () => void;
previous: () => void;
jumpTo: (index: number) => void;
reset: () => void;
}
export interface RotatingTextProps
extends Omit<
React.ComponentPropsWithoutRef<typeof motion.span>,
"children" | "transition" | "initial" | "animate" | "exit"
> {
texts: string[];
transition?: Transition;
initial?: boolean | Target | VariantLabels;
animate?: boolean | VariantLabels | AnimationControls | TargetAndTransition;
exit?: Target | VariantLabels;
animatePresenceMode?: "sync" | "wait";
animatePresenceInitial?: boolean;
rotationInterval?: number;
staggerDuration?: number;
staggerFrom?: "first" | "last" | "center" | "random" | number;
loop?: boolean;
auto?: boolean;
splitBy?: string;
onNext?: (index: number) => void;
mainClassName?: string;
splitLevelClassName?: string;
elementLevelClassName?: string;
}
export const RotatingText = forwardRef<RotatingTextRef, RotatingTextProps>(
(
{
texts,
transition = { type: "spring", damping: 25, stiffness: 300 },
initial = { y: "100%", opacity: 0 },
animate = { y: 0, opacity: 1 },
exit = { y: "-120%", opacity: 0 },
animatePresenceMode = "wait",
animatePresenceInitial = false,
rotationInterval = 2000,
staggerDuration = 0,
staggerFrom = "first",
loop = true,
auto = true,
splitBy = "characters",
onNext,
mainClassName,
splitLevelClassName,
elementLevelClassName,
...rest
},
ref,
) => {
const [currentTextIndex, setCurrentTextIndex] = useState<number>(0);
const splitIntoCharacters = (text: string): string[] => {
if (typeof Intl !== "undefined" && Intl.Segmenter) {
const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
return Array.from(
segmenter.segment(text),
(segment) => segment.segment,
);
}
return Array.from(text);
};
const elements = useMemo(() => {
const currentText: string = texts[currentTextIndex];
if (splitBy === "characters") {
const words = currentText.split(" ");
return words.map((word, i) => ({
characters: splitIntoCharacters(word),
needsSpace: i !== words.length - 1,
}));
}
if (splitBy === "words") {
return currentText.split(" ").map((word, i, arr) => ({
characters: [word],
needsSpace: i !== arr.length - 1,
}));
}
if (splitBy === "lines") {
return currentText.split("\n").map((line, i, arr) => ({
characters: [line],
needsSpace: i !== arr.length - 1,
}));
}
return currentText.split(splitBy).map((part, i, arr) => ({
characters: [part],
needsSpace: i !== arr.length - 1,
}));
}, [texts, currentTextIndex, splitBy]);
const getStaggerDelay = useCallback(
(index: number, totalChars: number): number => {
const total = totalChars;
if (staggerFrom === "first") return index * staggerDuration;
if (staggerFrom === "last")
return (total - 1 - index) * staggerDuration;
if (staggerFrom === "center") {
const center = Math.floor(total / 2);
return Math.abs(center - index) * staggerDuration;
}
if (staggerFrom === "random") {
const randomIndex = Math.floor(Math.random() * total);
return Math.abs(randomIndex - index) * staggerDuration;
}
return Math.abs((staggerFrom as number) - index) * staggerDuration;
},
[staggerFrom, staggerDuration],
);
const handleIndexChange = useCallback(
(newIndex: number) => {
setCurrentTextIndex(newIndex);
if (onNext) onNext(newIndex);
},
[onNext],
);
const next = useCallback(() => {
const nextIndex =
currentTextIndex === texts.length - 1
? loop
? 0
: currentTextIndex
: currentTextIndex + 1;
if (nextIndex !== currentTextIndex) {
handleIndexChange(nextIndex);
}
}, [currentTextIndex, texts.length, loop, handleIndexChange]);
const previous = useCallback(() => {
const prevIndex =
currentTextIndex === 0
? loop
? texts.length - 1
: currentTextIndex
: currentTextIndex - 1;
if (prevIndex !== currentTextIndex) {
handleIndexChange(prevIndex);
}
}, [currentTextIndex, texts.length, loop, handleIndexChange]);
const jumpTo = useCallback(
(index: number) => {
const validIndex = Math.max(0, Math.min(index, texts.length - 1));
if (validIndex !== currentTextIndex) {
handleIndexChange(validIndex);
}
},
[texts.length, currentTextIndex, handleIndexChange],
);
const reset = useCallback(() => {
if (currentTextIndex !== 0) {
handleIndexChange(0);
}
}, [currentTextIndex, handleIndexChange]);
useImperativeHandle(
ref,
() => ({
next,
previous,
jumpTo,
reset,
}),
[next, previous, jumpTo, reset],
);
useEffect(() => {
if (!auto) return;
const intervalId = setInterval(next, rotationInterval);
return () => clearInterval(intervalId);
}, [next, rotationInterval, auto]);
return (
<motion.span
className={cn(
"relative flex flex-wrap whitespace-pre-wrap",
mainClassName,
)}
{...rest}
layout
transition={transition}
>
<span className="sr-only">{texts[currentTextIndex]}</span>
<AnimatePresence
mode={animatePresenceMode}
initial={animatePresenceInitial}
>
<motion.div
key={currentTextIndex}
className={cn(
splitBy === "lines"
? "flex w-full flex-col"
: "relative flex flex-wrap whitespace-pre-wrap",
)}
layout
aria-hidden="true"
>
{elements.map((wordObj, wordIndex, array) => {
const previousCharsCount = array
.slice(0, wordIndex)
.reduce((sum, word) => sum + word.characters.length, 0);
return (
<span
key={wordIndex}
className={cn("inline-flex", splitLevelClassName)}
>
{wordObj.characters.map((char, charIndex) => (
<motion.span
key={charIndex}
initial={initial}
animate={animate}
exit={exit}
transition={{
...transition,
delay: getStaggerDelay(
previousCharsCount + charIndex,
array.reduce(
(sum, word) => sum + word.characters.length,
0,
),
),
}}
className={cn("inline-block", elementLevelClassName)}
>
{char}
</motion.span>
))}
{wordObj.needsSpace && (
<span className="whitespace-pre"> </span>
)}
</span>
);
})}
</motion.div>
</AnimatePresence>
</motion.span>
);
},
);
RotatingText.displayName = "RotatingText";
+27
View File
@@ -0,0 +1,27 @@
"use client";
import { RotatingText } from "@/components/reactbits/rotating-text";
const supports = [
"Next.js",
"Node.js",
"Hono",
"Express.js",
"Deno",
"Nest.js",
"Waku",
];
export const Supports = () => {
return (
<RotatingText
texts={supports}
mainClassName="inline-flex bg-transparent overflow-hidden justify-center"
initial={{ y: "100%" }}
animate={{ y: 0 }}
exit={{ y: "-120%" }}
staggerDuration={0.025}
transition={{ type: "spring", damping: 30, stiffness: 400 }}
rotationInterval={2000}
/>
);
};
-28
View File
@@ -1,28 +0,0 @@
"use client";
import { useEffect, useState } from "react";
import ReactTextTransition from "react-text-transition";
const supports = [
"Next.js",
"Node.js",
"Hono",
"Express.js",
"Deno",
"Nest.js",
"Waku",
];
export const TextEffect = () => {
const [counter, setCounter] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCounter(
(Math.floor(Math.random() * supports.length) + 1) % supports.length,
);
}, 4000);
return () => {
clearInterval(id);
};
}, []);
return <ReactTextTransition inline>{supports[counter]}</ReactTextTransition>;
};
+4 -4
View File
@@ -21,7 +21,7 @@ const DialogOverlay = React.forwardRef<
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/80",
className,
)}
{...props}
@@ -38,13 +38,13 @@ const DialogContent = React.forwardRef<
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border p-6 shadow-lg duration-200 sm:rounded-lg",
className,
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<DialogPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:pointer-events-none">
<Cross2Icon className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
@@ -102,7 +102,7 @@ const DialogDescription = React.forwardRef<
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
));
+1 -1
View File
@@ -10,7 +10,7 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
<input
type={type}
className={cn(
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
"border-input file:text-foreground placeholder:text-muted-foreground focus-visible:ring-ring flex h-9 w-full rounded-md border bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium focus-visible:outline-none focus-visible:ring-1 disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
ref={ref}
+1 -1
View File
@@ -6,7 +6,7 @@ function Skeleton({
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
className={cn("animate-pulse rounded-md bg-primary/10", className)}
className={cn("bg-primary/10 animate-pulse rounded-md", className)}
{...props}
/>
);
+3 -3
View File
@@ -17,10 +17,10 @@ const Slider = React.forwardRef<
)}
{...props}
>
<SliderPrimitive.Track className="relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20">
<SliderPrimitive.Range className="absolute h-full bg-primary" />
<SliderPrimitive.Track className="bg-primary/20 relative h-1.5 w-full grow overflow-hidden rounded-full">
<SliderPrimitive.Range className="bg-primary absolute h-full" />
</SliderPrimitive.Track>
<SliderPrimitive.Thumb className="block h-4 w-4 rounded-full border border-primary/50 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50" />
<SliderPrimitive.Thumb className="border-primary/50 bg-background focus-visible:ring-ring block h-4 w-4 rounded-full border shadow transition-colors focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:opacity-50" />
</SliderPrimitive.Root>
));
Slider.displayName = SliderPrimitive.Root.displayName;
+1 -1
View File
@@ -9,7 +9,7 @@ const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
return (
<textarea
className={cn(
"flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
"border-input placeholder:text-muted-foreground focus-visible:ring-ring flex min-h-[60px] w-full rounded-md border bg-transparent px-3 py-2 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-1 disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
ref={ref}
+1 -1
View File
@@ -20,7 +20,7 @@ const TooltipContent = React.forwardRef<
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
"bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 overflow-hidden rounded-md px-3 py-1.5 text-xs",
className,
)}
{...props}
@@ -3,28 +3,10 @@ title: Agent Workflow
---
import { DynamicCodeBlock } from 'fumadocs-ui/components/dynamic-codeblock';
import CodeSource from "!raw-loader!../../../../../../../examples/agentworkflow/blog_writer.ts";
import CodeSource from "!raw-loader!../../../../../../../examples/agentworkflow/blog-writer.ts";
import { Tab, Tabs } from "fumadocs-ui/components/tabs";
`AgentWorkflow` is a powerful system that enables you to create and orchestrate one or multiple agents with tools to perform specific tasks. It's built on top of the base `Workflow` system and provides a streamlined interface for agent interactions.
## Installation
You'll need to install the `@llamaindex/workflow` package:
<Tabs groupId="install" items={["npm", "yarn", "pnpm"]} persist>
```shell tab="npm"
npm install @llamaindex/workflow
```
```shell tab="yarn"
yarn add @llamaindex/workflow
```
```shell tab="pnpm"
pnpm add @llamaindex/workflow
```
</Tabs>
Agent Workflows are a powerful system that enables you to create and orchestrate one or multiple agents with tools to perform specific tasks. It's built on top of the base `Workflow` system and provides a streamlined interface for agent interactions.
## Usage
@@ -33,7 +15,7 @@ You'll need to install the `@llamaindex/workflow` package:
The simplest use case is creating a single agent with specific tools. Here's an example of creating an assistant that tells jokes:
```typescript
import { AgentWorkflow, FunctionTool } from "llamaindex";
import { agent, FunctionTool } from "llamaindex";
import { OpenAI } from "@llamaindex/openai";
// Define a joke-telling tool
@@ -45,8 +27,8 @@ const jokeTool = FunctionTool.from(
}
);
// Create an agent workflow with the tool
const workflow = AgentWorkflow.fromTools({
// Create an single agent workflow with the tool
const workflow = agent({
tools: [jokeTool],
llm: new OpenAI({
model: "gpt-4o-mini",
@@ -60,7 +42,7 @@ console.log(result); // Baby Llama is called cria
### Event Streaming
`AgentWorkflow` provides a unified interface for event streaming, making it easy to track and respond to different events during execution:
Agent Workflows provide a unified interface for event streaming, making it easy to track and respond to different events during execution:
```typescript
import { AgentToolCall, AgentStream } from "llamaindex";
@@ -81,7 +63,7 @@ for await (const event of context) {
### Multi-Agent Workflow
`AgentWorkflow` can orchestrate multiple agents, enabling complex interactions and task handoffs. Each agent in a multi-agent workflow requires:
An Agent Workflow can orchestrate multiple agents, enabling complex interactions and task handoffs. Each agent in a multi-agent workflow requires:
- `name`: Unique identifier for the agent
- `description`: Purpose description used for task routing
@@ -91,12 +73,12 @@ for await (const event of context) {
Here's an example of a multi-agent system that combines joke-telling and weather information:
```typescript
import { AgentWorkflow, FunctionAgent, FunctionTool } from "llamaindex";
import { multiAgent, agent, FunctionTool } from "llamaindex";
import { OpenAI } from "@llamaindex/openai";
import { z } from "zod";
// Create a weather agent
const weatherAgent = new FunctionAgent({
const weatherAgent = agent({
name: "WeatherAgent",
description: "Provides weather information for any city",
tools: [
@@ -115,7 +97,7 @@ const weatherAgent = new FunctionAgent({
});
// Create a joke-telling agent
const jokeAgent = new FunctionAgent({
const jokeAgent = agent({
name: "JokeAgent",
description: "Tells jokes and funny stories",
tools: [jokeTool], // Using the joke tool defined earlier
@@ -124,7 +106,7 @@ const jokeAgent = new FunctionAgent({
});
// Create the multi-agent workflow
const workflow = new AgentWorkflow({
const workflow = multiAgent({
agents: [jokeAgent, weatherAgent],
rootAgent: jokeAgent, // Start with the joke agent
});
@@ -119,7 +119,7 @@ Lastly, we run the workflow. The `.run()` method is async, so we use await here
Optionally, you can choose to use a shared context between steps by specifying a context type when creating the workflow. Here's an example where multiple steps access a shared state:
```typescript
import { HandlerContext } from "@llamaindex/workflow";
import { HandlerContext } from "llamaindex";
type MyContextData = {
query: string;
+6
View File
@@ -1,4 +1,5 @@
{
"$schema": "https://turbo.build/schema.json",
"extends": ["//"],
"tasks": {
"build": {
@@ -8,6 +9,11 @@
"next-env.d.ts",
"src/content/docs/cloud/api/**",
"src/content/docs/api/**"
],
"env": [
"LLAMA_CLOUD_API_KEY",
"LLAMA_CLOUD_PIPELINE_ID",
"OPENAI_API_KEY"
]
},
"dev": {
@@ -1,5 +1,14 @@
# @llamaindex/cloudflare-worker-agent-test
## 0.0.144
### Patch Changes
- Updated dependencies [c1b5be5]
- Updated dependencies [40ee761]
- Updated dependencies [40ee761]
- llamaindex@0.9.10
## 0.0.143
### Patch Changes
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/cloudflare-worker-agent-test",
"version": "0.0.143",
"version": "0.0.144",
"type": "module",
"private": true,
"scripts": {
@@ -1,5 +1,11 @@
# @llamaindex/llama-parse-browser-test
## 0.0.54
### Patch Changes
- @llamaindex/cloud@3.0.9
## 0.0.53
### Patch Changes
@@ -1,7 +1,7 @@
{
"name": "@llamaindex/llama-parse-browser-test",
"private": true,
"version": "0.0.53",
"version": "0.0.54",
"type": "module",
"scripts": {
"dev": "vite",
+9
View File
@@ -1,5 +1,14 @@
# @llamaindex/next-agent-test
## 0.1.144
### Patch Changes
- Updated dependencies [c1b5be5]
- Updated dependencies [40ee761]
- Updated dependencies [40ee761]
- llamaindex@0.9.10
## 0.1.143
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/next-agent-test",
"version": "0.1.143",
"version": "0.1.144",
"private": true,
"scripts": {
"dev": "next dev",
@@ -1,5 +1,14 @@
# test-edge-runtime
## 0.1.143
### Patch Changes
- Updated dependencies [c1b5be5]
- Updated dependencies [40ee761]
- Updated dependencies [40ee761]
- llamaindex@0.9.10
## 0.1.142
### Patch Changes
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/nextjs-edge-runtime-test",
"version": "0.1.142",
"version": "0.1.143",
"private": true,
"scripts": {
"dev": "next dev",
@@ -1,5 +1,17 @@
# @llamaindex/next-node-runtime
## 0.1.10
### Patch Changes
- Updated dependencies [aea550a]
- Updated dependencies [c1b5be5]
- Updated dependencies [40ee761]
- Updated dependencies [40ee761]
- @llamaindex/huggingface@0.0.44
- llamaindex@0.9.10
- @llamaindex/readers@2.0.8
## 0.1.9
### Patch Changes
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/next-node-runtime-test",
"version": "0.1.9",
"version": "0.1.10",
"private": true,
"scripts": {
"dev": "next dev",
@@ -1,13 +1,7 @@
"use server";
import { HuggingFaceEmbedding } from "@llamaindex/huggingface";
import { SimpleDirectoryReader } from "@llamaindex/readers/directory";
import {
OpenAI,
OpenAIAgent,
QueryEngineTool,
Settings,
VectorStoreIndex,
} from "llamaindex";
import { OpenAI, OpenAIAgent, Settings, VectorStoreIndex } from "llamaindex";
Settings.llm = new OpenAI({
apiKey: process.env.NEXT_PUBLIC_OPENAI_KEY ?? "FAKE_KEY_TO_PASS_TESTS",
@@ -31,23 +25,20 @@ export async function getOpenAIModelRequest(query: string) {
const reader = new SimpleDirectoryReader();
const documents = await reader.loadData(currentDir);
const index = await VectorStoreIndex.fromDocuments(documents);
const retriever = index.asRetriever({
similarityTopK: 10,
});
const queryEngine = index.asQueryEngine({
retriever,
});
// define the query engine as a tool
const tools = [
new QueryEngineTool({
queryEngine: queryEngine,
index.queryTool({
options: {
similarityTopK: 10,
},
metadata: {
name: "deployment_details_per_env",
description: `This tool can answer detailed questions about deployments happened in various environments.`,
},
}),
];
// create the agent
const agent = new OpenAIAgent({ tools });
@@ -1,5 +1,14 @@
# vite-import-llamaindex
## 0.0.10
### Patch Changes
- Updated dependencies [c1b5be5]
- Updated dependencies [40ee761]
- Updated dependencies [40ee761]
- llamaindex@0.9.10
## 0.0.9
### Patch Changes
@@ -1,7 +1,7 @@
{
"name": "vite-import-llamaindex",
"private": true,
"version": "0.0.9",
"version": "0.0.10",
"type": "module",
"scripts": {
"build": "vite build",
@@ -1,5 +1,14 @@
# @llamaindex/waku-query-engine-test
## 0.0.144
### Patch Changes
- Updated dependencies [c1b5be5]
- Updated dependencies [40ee761]
- Updated dependencies [40ee761]
- llamaindex@0.9.10
## 0.0.143
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/waku-query-engine-test",
"version": "0.0.143",
"version": "0.0.144",
"type": "module",
"private": true,
"scripts": {
@@ -10,10 +10,10 @@ export const Chat = (props: ChatProps) => {
const [response, setResponse] = useState<string | null>(null);
return (
<section className="border-blue-400 -mx-4 mt-4 rounded border border-dashed p-4">
<section className="-mx-4 mt-4 rounded border border-dashed border-blue-400 p-4">
<h2 className="text-lg font-bold">Chat with AI</h2>
{response ? (
<p className="text-sm text-gray-600 max-w-sm">{response}</p>
<p className="max-w-sm text-sm text-gray-600">{response}</p>
) : null}
<form
action={async (formData) => {
@@ -26,7 +26,7 @@ export const Chat = (props: ChatProps) => {
<input
type="text"
name="question"
className="border border-gray-400 rounded-sm px-2 py-0.5 text-sm"
className="rounded-sm border border-gray-400 px-2 py-0.5 text-sm"
/>
<button className="rounded-sm bg-black px-2 py-0.5 text-sm text-white">
Ask
+49
View File
@@ -1,5 +1,54 @@
# examples
## 0.2.9
### Patch Changes
- aea550a: Add factory convenience factory for each LLM provider, e.g. you can use openai instead of 'new OpenAI'
- Updated dependencies [c14a21b]
- Updated dependencies [33f9856]
- Updated dependencies [aea550a]
- Updated dependencies [c1b5be5]
- Updated dependencies [40ee761]
- Updated dependencies [40ee761]
- @llamaindex/azure@0.1.8
- @llamaindex/google@0.1.1
- @llamaindex/huggingface@0.0.44
- @llamaindex/portkey-ai@0.0.41
- @llamaindex/anthropic@0.2.6
- @llamaindex/deepinfra@0.0.44
- @llamaindex/fireworks@0.0.4
- @llamaindex/replicate@0.0.41
- @llamaindex/deepseek@0.0.4
- @llamaindex/together@0.0.4
- @llamaindex/mistral@0.0.13
- @llamaindex/ollama@0.0.48
- @llamaindex/openai@0.1.60
- @llamaindex/vercel@0.0.19
- @llamaindex/groq@0.0.59
- @llamaindex/vllm@0.0.30
- llamaindex@0.9.10
- @llamaindex/workflow@0.0.16
- @llamaindex/core@0.5.8
- @llamaindex/clip@0.0.44
- @llamaindex/jinaai@0.0.4
- @llamaindex/milvus@0.1.8
- @llamaindex/qdrant@0.1.8
- @llamaindex/cloud@3.0.9
- @llamaindex/node-parser@1.0.8
- @llamaindex/cohere@0.0.13
- @llamaindex/mixedbread@0.0.13
- @llamaindex/astra@0.0.13
- @llamaindex/chroma@0.0.13
- @llamaindex/firestore@1.0.6
- @llamaindex/mongodb@0.0.13
- @llamaindex/pinecone@0.0.13
- @llamaindex/postgres@0.0.41
- @llamaindex/upstash@0.0.13
- @llamaindex/weaviate@0.0.13
- @llamaindex/voyage-ai@1.0.5
- @llamaindex/readers@2.0.8
## 0.2.8
### Patch Changes
+2 -2
View File
@@ -1,5 +1,5 @@
import { OpenAI } from "@llamaindex/openai";
import { AgentWorkflow, FunctionTool } from "llamaindex";
import { FunctionTool, agent } from "llamaindex";
import { z } from "zod";
const csvData =
@@ -33,7 +33,7 @@ const userQuestion = "which are the best comedies after 2010?";
const systemPrompt =
"You are a Python interpreter.\n - You are given tasks to complete and you run python code to solve them.\n - The python code runs in a Jupyter notebook. Every time you call $(interpreter) tool, the python code is executed in a separate cell. It's okay to make multiple calls to $(interpreter).\n - Display visualizations using matplotlib or any other visualization library directly in the notebook. Shouldn't save the visualizations to a file, just return the base64 encoded data.\n - You can install any pip package (if it exists) if you need to but the usual packages for data analysis are already preinstalled.\n - You can run any python code you want in a secure environment.";
const workflow = AgentWorkflow.fromTools({
const workflow = agent({
tools: [interpreterTool],
llm,
verbose: false,
+2 -2
View File
@@ -1,5 +1,5 @@
import { OpenAI } from "@llamaindex/openai";
import { AgentWorkflow, FunctionTool } from "llamaindex";
import { FunctionTool, agent } from "llamaindex";
import { z } from "zod";
const sumNumbers = FunctionTool.from(
@@ -27,7 +27,7 @@ const divideNumbers = FunctionTool.from(
);
async function main() {
const workflow = AgentWorkflow.fromTools({
const workflow = agent({
tools: [sumNumbers, divideNumbers],
llm: new OpenAI({ model: "gpt-4o-mini" }),
verbose: false,
+2 -2
View File
@@ -1,12 +1,12 @@
import { OpenAI } from "@llamaindex/openai";
import { AgentStream, AgentWorkflow } from "llamaindex";
import { AgentStream, agent } from "llamaindex";
import { WikipediaTool } from "../wiki";
async function main() {
const llm = new OpenAI({ model: "gpt-4-turbo" });
const wikiTool = new WikipediaTool();
const workflow = AgentWorkflow.fromTools({
const workflow = agent({
tools: [wikiTool],
llm,
verbose: false,
@@ -1,40 +1,38 @@
import { OpenAI } from "@llamaindex/openai";
import { openai } from "@llamaindex/openai";
import fs from "fs";
import {
agent,
AgentToolCall,
AgentToolCallResult,
AgentWorkflow,
FunctionAgent,
FunctionTool,
multiAgent,
tool,
} from "llamaindex";
import os from "os";
import { z } from "zod";
import { WikipediaTool } from "../wiki";
const llm = new OpenAI({
const llm = openai({
model: "gpt-4o-mini",
});
const saveFileTool = FunctionTool.from(
({ content }: { content: string }) => {
const saveFileTool = tool({
name: "saveFile",
description:
"Save the written content into a file that can be downloaded by the user",
parameters: z.object({
content: z.string({
description: "The content to save into a file",
}),
}),
execute: ({ content }: { content: string }) => {
const filePath = os.tmpdir() + "/report.md";
fs.writeFileSync(filePath, content);
return `File saved successfully at ${filePath}`;
},
{
name: "saveFile",
description:
"Save the written content into a file that can be downloaded by the user",
parameters: z.object({
content: z.string({
description: "The content to save into a file",
}),
}),
},
);
});
async function main() {
const reportAgent = new FunctionAgent({
const reportAgent = agent({
name: "ReportAgent",
description:
"Responsible for crafting well-written blog posts based on research findings",
@@ -43,7 +41,7 @@ async function main() {
llm,
});
const researchAgent = new FunctionAgent({
const researchAgent = agent({
name: "ResearchAgent",
description:
"Responsible for gathering relevant information from the internet",
@@ -53,7 +51,7 @@ async function main() {
llm,
});
const workflow = new AgentWorkflow({
const workflow = multiAgent({
agents: [researchAgent, reportAgent],
rootAgent: researchAgent,
});
@@ -3,59 +3,55 @@
* 1. FetchWeatherAgent - Fetches the weather in a city
* 2. TemperatureConverterAgent - Converts the temperature from Fahrenheit to Celsius
*/
import { OpenAI } from "@llamaindex/openai";
import { StopEvent } from "@llamaindex/workflow";
import { openai } from "@llamaindex/openai";
import {
agent,
AgentInput,
AgentOutput,
AgentStream,
AgentToolCall,
AgentToolCallResult,
AgentWorkflow,
FunctionAgent,
FunctionTool,
multiAgent,
StopEvent,
tool,
} from "llamaindex";
import { z } from "zod";
const llm = new OpenAI({
const llm = openai({
model: "gpt-4o-mini",
});
// Define tools for the agents
const temperatureConverterTool = FunctionTool.from(
({ temperature }: { temperature: number }) => {
const temperatureConverterTool = tool({
description: "Convert a temperature from Fahrenheit to Celsius",
name: "fahrenheitToCelsius",
parameters: z.object({
temperature: z.number({
description: "The temperature in Fahrenheit",
}),
}),
execute: ({ temperature }) => {
return ((temperature - 32) * 5) / 9;
},
{
description: "Convert a temperature from Fahrenheit to Celsius",
name: "fahrenheitToCelsius",
parameters: z.object({
temperature: z.number({
description: "The temperature in Fahrenheit",
}),
}),
},
);
});
const temperatureFetcherTool = FunctionTool.from(
({ city }: { city: string }) => {
const temperatureFetcherTool = tool({
description: "Fetch the temperature (in Fahrenheit) for a city",
name: "fetchTemperature",
parameters: z.object({
city: z.string({
description: "The city to fetch the temperature for",
}),
}),
execute: ({ city }) => {
const temperature = Math.floor(Math.random() * 58) + 32;
return `The current temperature in ${city} is ${temperature}°F`;
},
{
description: "Fetch the temperature (in Fahrenheit) for a city",
name: "fetchTemperature",
parameters: z.object({
city: z.string({
description: "The city to fetch the temperature for",
}),
}),
},
);
});
// Create agents
async function multiWeatherAgent() {
const converterAgent = new FunctionAgent({
const converterAgent = agent({
name: "TemperatureConverterAgent",
description:
"An agent that can convert temperatures from Fahrenheit to Celsius.",
@@ -63,7 +59,7 @@ async function multiWeatherAgent() {
llm,
});
const weatherAgent = new FunctionAgent({
const weatherAgent = agent({
name: "FetchWeatherAgent",
description: "An agent that can get the weather in a city. ",
systemPrompt:
@@ -76,7 +72,7 @@ async function multiWeatherAgent() {
});
// Create agent workflow with the agents
const workflow = new AgentWorkflow({
const workflow = multiAgent({
agents: [weatherAgent, converterAgent],
rootAgent: weatherAgent,
verbose: false,
@@ -1,18 +1,17 @@
/**
* This example shows how to use AgentWorkflow as a single agent with tools
*/
import { OpenAI } from "@llamaindex/openai";
import { AgentWorkflow } from "llamaindex";
import { openai } from "@llamaindex/openai";
import { Settings, agent } from "llamaindex";
import { getWeatherTool } from "../agent/utils/tools";
const llm = new OpenAI({
Settings.llm = openai({
model: "gpt-4o",
});
async function singleWeatherAgent() {
const workflow = AgentWorkflow.fromTools({
const workflow = agent({
tools: [getWeatherTool],
llm,
verbose: false,
});
+42 -48
View File
@@ -1,69 +1,63 @@
import fs from "fs";
import {
agent,
AgentToolCall,
AgentToolCallResult,
AgentWorkflow,
FunctionAgent,
FunctionTool,
multiAgent,
tool,
} from "llamaindex";
import { z } from "zod";
import { Anthropic } from "@llamaindex/anthropic";
import { anthropic } from "@llamaindex/anthropic";
const llm = new Anthropic({
model: "claude-3-5-sonnet",
const weatherTool = tool({
name: "weather",
description: "Get the weather",
parameters: z.object({
location: z.string({
description: "The location to get the weather for",
}),
}),
execute: ({ location }) => {
return `The weather in ${location} is sunny`;
},
});
const weatherTool = FunctionTool.from(
(query: { location: string }) => {
return `The weather in ${query.location} is sunny`;
},
{
name: "weather",
description: "Get the weather",
parameters: z.object({
location: z.string({
description: "The location to get the weather for",
}),
const inflationTool = tool({
name: "inflation",
description: "Get the inflation",
parameters: z.object({
location: z.string({
description: "The location to get the inflation for",
}),
}),
execute: ({ location }) => {
return `The inflation in ${location} is 2%`;
},
);
});
const inflationTool = FunctionTool.from(
(query: { location: string }) => {
return `The inflation in ${query.location} is 2%`;
},
{
name: "inflation",
description: "Get the inflation",
parameters: z.object({
location: z.string({
description: "The location to get the inflation for",
}),
const saveFileTool = tool({
name: "saveFile",
description:
"Save the written content into a file that can be downloaded by the user",
parameters: z.object({
content: z.string({
description: "The content to save into a file",
}),
},
);
const saveFileTool = FunctionTool.from(
({ content }: { content: string }) => {
}),
execute: ({ content }) => {
const filePath = "./report.md";
fs.writeFileSync(filePath, content);
return `File saved successfully at ${filePath}`;
},
{
name: "saveFile",
description:
"Save the written content into a file that can be downloaded by the user",
parameters: z.object({
content: z.string({
description: "The content to save into a file",
}),
}),
},
);
});
async function main() {
const reportAgent = new FunctionAgent({
const llm = anthropic({
model: "claude-3-5-sonnet",
});
const reportAgent = agent({
name: "ReportAgent",
description:
"Responsible for creating concise reports about weather and inflation data",
@@ -72,7 +66,7 @@ async function main() {
llm,
});
const researchAgent = new FunctionAgent({
const researchAgent = agent({
name: "ResearchAgent",
description:
"Responsible for gathering relevant information from the internet",
@@ -82,7 +76,7 @@ async function main() {
llm,
});
const workflow = new AgentWorkflow({
const workflow = multiAgent({
agents: [researchAgent, reportAgent],
rootAgent: researchAgent,
});
+1 -1
View File
@@ -1,4 +1,4 @@
import { StartEvent, StopEvent, Workflow } from "@llamaindex/workflow";
import { StartEvent, StopEvent, Workflow } from "llamaindex";
type ContextData = {
counter: number;
+38 -38
View File
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/examples",
"version": "0.2.8",
"version": "0.2.9",
"private": true,
"scripts": {
"lint": "eslint .",
@@ -11,43 +11,43 @@
"@azure/cosmos": "^4.1.1",
"@azure/identity": "^4.4.1",
"@azure/search-documents": "^12.1.0",
"@llamaindex/anthropic": "^0.2.5",
"@llamaindex/astra": "^0.0.12",
"@llamaindex/azure": "^0.1.7",
"@llamaindex/chroma": "^0.0.12",
"@llamaindex/clip": "^0.0.43",
"@llamaindex/cloud": "^3.0.8",
"@llamaindex/cohere": "^0.0.12",
"@llamaindex/core": "^0.5.7",
"@llamaindex/deepinfra": "^0.0.43",
"@llamaindex/anthropic": "^0.2.6",
"@llamaindex/astra": "^0.0.13",
"@llamaindex/azure": "^0.1.8",
"@llamaindex/chroma": "^0.0.13",
"@llamaindex/clip": "^0.0.44",
"@llamaindex/cloud": "^3.0.9",
"@llamaindex/cohere": "^0.0.13",
"@llamaindex/core": "^0.5.8",
"@llamaindex/deepinfra": "^0.0.44",
"@llamaindex/env": "^0.1.29",
"@llamaindex/firestore": "^1.0.5",
"@llamaindex/google": "^0.1.0",
"@llamaindex/groq": "^0.0.58",
"@llamaindex/huggingface": "^0.0.43",
"@llamaindex/milvus": "^0.1.7",
"@llamaindex/mistral": "^0.0.12",
"@llamaindex/mixedbread": "^0.0.12",
"@llamaindex/mongodb": "^0.0.12",
"@llamaindex/node-parser": "^1.0.7",
"@llamaindex/ollama": "^0.0.47",
"@llamaindex/openai": "^0.1.59",
"@llamaindex/pinecone": "^0.0.12",
"@llamaindex/portkey-ai": "^0.0.40",
"@llamaindex/postgres": "^0.0.40",
"@llamaindex/qdrant": "^0.1.7",
"@llamaindex/readers": "^2.0.7",
"@llamaindex/replicate": "^0.0.40",
"@llamaindex/upstash": "^0.0.12",
"@llamaindex/vercel": "^0.0.18",
"@llamaindex/vllm": "^0.0.29",
"@llamaindex/voyage-ai": "^1.0.4",
"@llamaindex/weaviate": "^0.0.12",
"@llamaindex/workflow": "^0.0.15",
"@llamaindex/deepseek": "^0.0.3",
"@llamaindex/fireworks": "^0.0.3",
"@llamaindex/together": "^0.0.3",
"@llamaindex/jinaai": "^0.0.3",
"@llamaindex/firestore": "^1.0.6",
"@llamaindex/google": "^0.1.1",
"@llamaindex/groq": "^0.0.59",
"@llamaindex/huggingface": "^0.0.44",
"@llamaindex/milvus": "^0.1.8",
"@llamaindex/mistral": "^0.0.13",
"@llamaindex/mixedbread": "^0.0.13",
"@llamaindex/mongodb": "^0.0.13",
"@llamaindex/node-parser": "^1.0.8",
"@llamaindex/ollama": "^0.0.48",
"@llamaindex/openai": "^0.1.60",
"@llamaindex/pinecone": "^0.0.13",
"@llamaindex/portkey-ai": "^0.0.41",
"@llamaindex/postgres": "^0.0.41",
"@llamaindex/qdrant": "^0.1.8",
"@llamaindex/readers": "^2.0.8",
"@llamaindex/replicate": "^0.0.41",
"@llamaindex/upstash": "^0.0.13",
"@llamaindex/vercel": "^0.0.19",
"@llamaindex/vllm": "^0.0.30",
"@llamaindex/voyage-ai": "^1.0.5",
"@llamaindex/weaviate": "^0.0.13",
"@llamaindex/workflow": "^0.0.16",
"@llamaindex/deepseek": "^0.0.4",
"@llamaindex/fireworks": "^0.0.4",
"@llamaindex/together": "^0.0.4",
"@llamaindex/jinaai": "^0.0.4",
"@notionhq/client": "^2.2.15",
"@pinecone-database/pinecone": "^4.0.0",
"@vercel/postgres": "^0.10.0",
@@ -56,7 +56,7 @@
"commander": "^12.1.0",
"dotenv": "^16.4.5",
"js-tiktoken": "^1.0.14",
"llamaindex": "^0.9.9",
"llamaindex": "^0.9.10",
"mongodb": "6.7.0",
"postgres": "^3.4.4",
"wikipedia": "^2.1.2",
+1 -1
View File
@@ -5,7 +5,7 @@ import {
StopEvent,
Workflow,
WorkflowEvent,
} from "@llamaindex/workflow";
} from "llamaindex";
const MAX_REVIEWS = 3;
+1 -1
View File
@@ -5,7 +5,7 @@ import {
StopEvent,
Workflow,
WorkflowEvent,
} from "@llamaindex/workflow";
} from "llamaindex";
// Create LLM instance
const llm = new OpenAI();
+1 -6
View File
@@ -1,10 +1,5 @@
import { OpenAI } from "@llamaindex/openai";
import {
StartEvent,
StopEvent,
Workflow,
WorkflowEvent,
} from "@llamaindex/workflow";
import { StartEvent, StopEvent, Workflow, WorkflowEvent } from "llamaindex";
// Create LLM instance
const llm = new OpenAI();
+1 -1
View File
@@ -5,7 +5,7 @@ import {
StopEvent,
Workflow,
WorkflowEvent,
} from "@llamaindex/workflow";
} from "llamaindex";
// Create LLM instance
const llm = new OpenAI();
+1 -1
View File
@@ -1,4 +1,4 @@
import { StartEvent, StopEvent, Workflow } from "@llamaindex/workflow";
import { StartEvent, StopEvent, Workflow } from "llamaindex";
const longRunning = async (_: unknown, ev: StartEvent<string>) => {
await new Promise((resolve) => setTimeout(resolve, 2000)); // Wait for 2 seconds
+1 -6
View File
@@ -1,10 +1,5 @@
import { OpenAI } from "@llamaindex/openai";
import {
StartEvent,
StopEvent,
Workflow,
WorkflowEvent,
} from "@llamaindex/workflow";
import { StartEvent, StopEvent, Workflow, WorkflowEvent } from "llamaindex";
// Create LLM instance
const llm = new OpenAI();
+6 -8
View File
@@ -32,6 +32,7 @@
"madge": "^8.0.0",
"prettier": "^3.4.2",
"prettier-plugin-organize-imports": "^4.1.0",
"prettier-plugin-tailwindcss": "^0.6.11",
"turbo": "^2.4.4",
"typescript": "^5.7.3",
"typescript-eslint": "^8.18.0"
@@ -39,14 +40,11 @@
"packageManager": "pnpm@9.12.3",
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"prettier --check",
"eslint"
"eslint --fix",
"prettier --write"
],
"*.{json,md}": "prettier --check"
},
"pnpm": {
"patchedDependencies": {
"bunchee@6.3.4": "patches/bunchee@6.3.4.patch"
}
"*.{json,md,yml}": [
"prettier --write"
]
}
}
+9
View File
@@ -1,5 +1,14 @@
# @llamaindex/autotool
## 6.0.10
### Patch Changes
- Updated dependencies [c1b5be5]
- Updated dependencies [40ee761]
- Updated dependencies [40ee761]
- llamaindex@0.9.10
## 6.0.9
### Patch Changes
@@ -1,5 +1,15 @@
# @llamaindex/autotool-01-node-example
## 0.0.91
### Patch Changes
- Updated dependencies [c1b5be5]
- Updated dependencies [40ee761]
- Updated dependencies [40ee761]
- llamaindex@0.9.10
- @llamaindex/autotool@6.0.10
## 0.0.90
### Patch Changes
@@ -13,5 +13,5 @@
"scripts": {
"start": "node --import tsx --import @llamaindex/autotool/node ./src/index.ts"
},
"version": "0.0.90"
"version": "0.0.91"
}
+2 -2
View File
@@ -6,7 +6,7 @@
"url": "git+https://github.com/run-llama/LlamaIndexTS.git",
"directory": "packages/autotool"
},
"version": "6.0.9",
"version": "6.0.10",
"description": "auto transpile your JS function to LLM Agent compatible",
"files": [
"dist",
@@ -75,7 +75,7 @@
"@swc/types": "^0.1.12",
"@types/json-schema": "^7.0.15",
"@types/node": "^22.9.0",
"bunchee": "6.3.4",
"bunchee": "6.4.0",
"llamaindex": "workspace:*",
"next": "15.2.0",
"rollup": "^4.28.1",
+7
View File
@@ -1,5 +1,12 @@
# @llamaindex/cloud
## 3.0.9
### Patch Changes
- Updated dependencies [40ee761]
- @llamaindex/core@0.5.8
## 3.0.8
### Patch Changes
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/cloud",
"version": "3.0.8",
"version": "3.0.9",
"type": "module",
"license": "MIT",
"scripts": {
@@ -59,7 +59,7 @@
"@hey-api/openapi-ts": "^0.61.0",
"@llamaindex/core": "workspace:*",
"@llamaindex/env": "workspace:*",
"bunchee": "6.3.4"
"bunchee": "6.4.0"
},
"peerDependencies": {
"@llamaindex/core": "workspace:*",
+1
View File
@@ -1,4 +1,5 @@
{
"$schema": "https://turbo.build/schema.json",
"extends": ["//"],
"tasks": {
"build": {
+7
View File
@@ -1,5 +1,12 @@
# @llamaindex/community
## 0.0.90
### Patch Changes
- Updated dependencies [40ee761]
- @llamaindex/core@0.5.8
## 0.0.89
### Patch Changes
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "@llamaindex/community",
"description": "Community package for LlamaIndexTS",
"version": "0.0.89",
"version": "0.0.90",
"type": "module",
"types": "dist/type/index.d.ts",
"main": "dist/cjs/index.js",
@@ -43,7 +43,7 @@
},
"devDependencies": {
"@types/node": "^22.9.0",
"bunchee": "6.3.4"
"bunchee": "6.4.0"
},
"dependencies": {
"@aws-sdk/client-bedrock-agent-runtime": "^3.706.0",
+6
View File
@@ -1,5 +1,11 @@
# @llamaindex/core
## 0.5.8
### Patch Changes
- 40ee761: Add factory methods tool, agent and multiAgent to simplify agent usage
## 0.5.7
### Patch Changes
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "@llamaindex/core",
"type": "module",
"version": "0.5.7",
"version": "0.5.8",
"description": "LlamaIndex Core Module",
"exports": {
"./agent": {
@@ -316,7 +316,7 @@
"devDependencies": {
"@edge-runtime/vm": "^4.0.4",
"ajv": "^8.17.1",
"bunchee": "6.3.4",
"bunchee": "6.4.0",
"happy-dom": "^15.11.6",
"natural": "^8.0.1"
},
+49 -4
View File
@@ -64,12 +64,52 @@ export class FunctionTool<
parameters: R;
},
): FunctionTool<T, JSONValue, AdditionalToolArgument>;
static from<
R extends z.ZodType,
AdditionalToolArgument extends object = object,
>(
config: Omit<ToolMetadata, "parameters"> & {
parameters: R;
execute: (
input: z.infer<R>,
additionalArg?: AdditionalToolArgument,
) => JSONValue | Promise<JSONValue>;
},
): FunctionTool<
z.infer<R>,
JSONValue | Promise<JSONValue>,
AdditionalToolArgument
>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
static from(fn: any, schema: any): any {
if (schema.parameters instanceof z.ZodSchema) {
static from(fnOrConfig: any, schema?: any): any {
// Handle the case where an object with execute function is passed
if (
typeof schema === "undefined" &&
typeof fnOrConfig === "object" &&
fnOrConfig.execute
) {
const { execute, parameters, ...restConfig } = fnOrConfig;
if (parameters instanceof z.ZodSchema) {
const jsonSchema = zodToJsonSchema(parameters);
return new FunctionTool(
execute,
{
...restConfig,
parameters: jsonSchema,
},
parameters,
);
}
return new FunctionTool(execute, fnOrConfig);
}
// Handle the original cases
if (schema && schema.parameters instanceof z.ZodSchema) {
const jsonSchema = zodToJsonSchema(schema.parameters);
return new FunctionTool(
fn,
fnOrConfig,
{
...schema,
parameters: jsonSchema,
@@ -77,7 +117,7 @@ export class FunctionTool<
schema.parameters,
);
}
return new FunctionTool(fn, schema);
return new FunctionTool(fnOrConfig, schema);
}
get metadata(): BaseTool<T>["metadata"] {
@@ -122,3 +162,8 @@ export class FunctionTool<
return this.#fn.call(null, input, this.#additionalArg);
};
}
/**
* A simpler alias for creating a FunctionTool.
*/
export const tool = FunctionTool.from;
+1 -1
View File
@@ -1 +1 @@
export { FunctionTool } from "./function-tool";
export * from "./function-tool";
+2 -1
View File
@@ -80,8 +80,9 @@ export {
extractText,
imageToDataUrl,
messagesToHistory,
MockLLM,
toToolDescriptions,
} from "./llms";
export { MockLLM } from "./mock";
export { objectEntries } from "./object-entries";
-88
View File
@@ -2,15 +2,6 @@ import { fs } from "@llamaindex/env";
import { filetypemime } from "magic-bytes.js";
import type {
ChatMessage,
ChatResponse,
ChatResponseChunk,
CompletionResponse,
LLM,
LLMChatParamsNonStreaming,
LLMChatParamsStreaming,
LLMCompletionParamsNonStreaming,
LLMCompletionParamsStreaming,
LLMMetadata,
MessageContent,
MessageContentDetail,
MessageContentTextDetail,
@@ -152,82 +143,3 @@ export async function imageToDataUrl(
}
return await blobToDataUrl(input);
}
export class MockLLM implements LLM {
metadata: LLMMetadata;
options: {
timeBetweenToken: number;
responseMessage: string;
};
constructor(options?: {
timeBetweenToken?: number;
responseMessage?: string;
metadata?: LLMMetadata;
}) {
this.options = {
timeBetweenToken: options?.timeBetweenToken ?? 20,
responseMessage: options?.responseMessage ?? "This is a mock response",
};
this.metadata = options?.metadata ?? {
model: "MockLLM",
temperature: 0.5,
topP: 0.5,
contextWindow: 1024,
tokenizer: undefined,
};
}
chat(
params: LLMChatParamsStreaming<object, object>,
): Promise<AsyncIterable<ChatResponseChunk>>;
chat(
params: LLMChatParamsNonStreaming<object, object>,
): Promise<ChatResponse<object>>;
async chat(
params:
| LLMChatParamsStreaming<object, object>
| LLMChatParamsNonStreaming<object, object>,
): Promise<AsyncIterable<ChatResponseChunk> | ChatResponse<object>> {
const responseMessage = this.options.responseMessage;
const timeBetweenToken = this.options.timeBetweenToken;
if (params.stream) {
return (async function* () {
for (const char of responseMessage) {
yield { delta: char, raw: {} };
await new Promise((resolve) => setTimeout(resolve, timeBetweenToken));
}
})();
}
return {
message: { content: responseMessage, role: "assistant" },
raw: {},
};
}
async complete(
params: LLMCompletionParamsStreaming,
): Promise<AsyncIterable<CompletionResponse>>;
async complete(
params: LLMCompletionParamsNonStreaming,
): Promise<CompletionResponse>;
async complete(
params: LLMCompletionParamsStreaming | LLMCompletionParamsNonStreaming,
): Promise<AsyncIterable<CompletionResponse> | CompletionResponse> {
const responseMessage = this.options.responseMessage;
const timeBetweenToken = this.options.timeBetweenToken;
if (params.stream) {
return (async function* () {
for (const char of responseMessage) {
yield { delta: char, text: char, raw: {} };
await new Promise((resolve) => setTimeout(resolve, timeBetweenToken));
}
})();
}
return { text: responseMessage, raw: {} };
}
}
+93
View File
@@ -0,0 +1,93 @@
// TODO: move to a test package
import { ToolCallLLM } from "../llms/base";
import type {
ChatResponse,
ChatResponseChunk,
CompletionResponse,
LLMChatParamsNonStreaming,
LLMChatParamsStreaming,
LLMCompletionParamsNonStreaming,
LLMCompletionParamsStreaming,
LLMMetadata,
} from "../llms/type";
export class MockLLM extends ToolCallLLM {
metadata: LLMMetadata;
options: {
timeBetweenToken: number;
responseMessage: string;
};
supportToolCall: boolean = false;
constructor(options?: {
timeBetweenToken?: number;
responseMessage?: string;
metadata?: LLMMetadata;
}) {
super();
this.options = {
timeBetweenToken: options?.timeBetweenToken ?? 20,
responseMessage: options?.responseMessage ?? "This is a mock response",
};
this.metadata = options?.metadata ?? {
model: "MockLLM",
temperature: 0.5,
topP: 0.5,
contextWindow: 1024,
tokenizer: undefined,
};
}
chat(
params: LLMChatParamsStreaming<object, object>,
): Promise<AsyncIterable<ChatResponseChunk>>;
chat(
params: LLMChatParamsNonStreaming<object, object>,
): Promise<ChatResponse<object>>;
async chat(
params:
| LLMChatParamsStreaming<object, object>
| LLMChatParamsNonStreaming<object, object>,
): Promise<AsyncIterable<ChatResponseChunk> | ChatResponse<object>> {
const responseMessage = this.options.responseMessage;
const timeBetweenToken = this.options.timeBetweenToken;
if (params.stream) {
return (async function* () {
for (const char of responseMessage) {
yield { delta: char, raw: {} };
await new Promise((resolve) => setTimeout(resolve, timeBetweenToken));
}
})();
}
return {
message: { content: responseMessage, role: "assistant" },
raw: {},
};
}
async complete(
params: LLMCompletionParamsStreaming,
): Promise<AsyncIterable<CompletionResponse>>;
async complete(
params: LLMCompletionParamsNonStreaming,
): Promise<CompletionResponse>;
async complete(
params: LLMCompletionParamsStreaming | LLMCompletionParamsNonStreaming,
): Promise<AsyncIterable<CompletionResponse> | CompletionResponse> {
const responseMessage = this.options.responseMessage;
const timeBetweenToken = this.options.timeBetweenToken;
if (params.stream) {
return (async function* () {
for (const char of responseMessage) {
yield { delta: char, text: char, raw: {} };
await new Promise((resolve) => setTimeout(resolve, timeBetweenToken));
}
})();
}
return { text: responseMessage, raw: {} };
}
}
+36 -1
View File
@@ -1,4 +1,4 @@
import { FunctionTool } from "@llamaindex/core/tools";
import { FunctionTool, tool } from "@llamaindex/core/tools";
import { describe, expect, test, vi } from "vitest";
import { z } from "zod";
@@ -27,6 +27,41 @@ describe("FunctionTool", () => {
});
});
test("create with execute attribute", async () => {
// Mock function to be passed as execute attribute
const mockExecute = vi.fn().mockImplementation(({ content }) => {
return `File saved with content: ${content}`;
});
const config = {
name: "saveFile",
description: "Save the content into a file",
parameters: z.object({
content: z.string({
description: "The content to save into a file",
}),
}),
execute: mockExecute,
};
// Create tool using an execute attribute
const saveTool = FunctionTool.from(config);
// Call the tool and verify
const result = await saveTool.call({ content: "test content" });
expect(mockExecute).toHaveBeenCalledOnce();
expect(mockExecute).toHaveBeenCalledWith(
{ content: "test content" },
undefined,
);
expect(result).toBe("File saved with content: test content");
// Test tool alias
const saveTool2 = tool(config);
const result2 = await saveTool2.call({ content: "test content" });
expect(result2).toBe("File saved with content: test content");
});
test("bind additional argument", () => {
type AdditionalHelloArgument = {
question?: string;
+1
View File
@@ -1,4 +1,5 @@
{
"$schema": "https://turbo.build/schema.json",
"extends": ["//"],
"tasks": {
"build": {
+1 -1
View File
@@ -119,7 +119,7 @@
"@huggingface/transformers": "^3.0.2",
"@types/node": "^22.9.0",
"@types/readable-stream": "^4.0.15",
"bunchee": "6.3.4",
"bunchee": "6.4.0",
"vitest": "^2.1.5"
},
"dependencies": {
+1
View File
@@ -1,4 +1,5 @@
{
"$schema": "https://turbo.build/schema.json",
"extends": ["//"],
"tasks": {
"build": {
+9
View File
@@ -1,5 +1,14 @@
# @llamaindex/experimental
## 0.0.160
### Patch Changes
- Updated dependencies [c1b5be5]
- Updated dependencies [40ee761]
- Updated dependencies [40ee761]
- llamaindex@0.9.10
## 0.0.159
### Patch Changes
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@llamaindex/experimental",
"description": "Experimental package for LlamaIndexTS",
"version": "0.0.159",
"version": "0.0.160",
"type": "module",
"types": "dist/type/index.d.ts",
"main": "dist/cjs/index.js",
+16
View File
@@ -1,5 +1,21 @@
# llamaindex
## 0.9.10
### Patch Changes
- c1b5be5: feat: make AgentWorkflow llm param optional
- 40ee761: Add factory methods tool, agent and multiAgent to simplify agent usage
- 40ee761: feat: add asQueryTool to index
- Updated dependencies [aea550a]
- Updated dependencies [c1b5be5]
- Updated dependencies [40ee761]
- @llamaindex/openai@0.1.60
- @llamaindex/workflow@0.0.16
- @llamaindex/core@0.5.8
- @llamaindex/cloud@3.0.9
- @llamaindex/node-parser@1.0.8
## 0.9.9
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "llamaindex",
"version": "0.9.9",
"version": "0.9.10",
"license": "MIT",
"type": "module",
"keywords": [
+1
View File
@@ -67,6 +67,7 @@ export * from "@llamaindex/core/storage/index-store";
export * from "@llamaindex/core/storage/kv-store";
export * from "@llamaindex/core/utils";
export * from "@llamaindex/openai";
export * from "@llamaindex/workflow";
export * from "@llamaindex/workflow/agent";
export * from "./agent/index.js";
export * from "./cloud/index.js";
@@ -2,15 +2,21 @@ import type {
BaseChatEngine,
ContextChatEngineOptions,
} from "@llamaindex/core/chat-engine";
import type { ToolMetadata } from "@llamaindex/core/llms";
import type { BaseQueryEngine } from "@llamaindex/core/query-engine";
import type { BaseSynthesizer } from "@llamaindex/core/response-synthesizers";
import type { BaseRetriever } from "@llamaindex/core/retriever";
import type { BaseNode, Document } from "@llamaindex/core/schema";
import type { BaseDocumentStore } from "@llamaindex/core/storage/doc-store";
import type { BaseIndexStore } from "@llamaindex/core/storage/index-store";
import type { JSONSchemaType } from "ajv";
import { runTransformations } from "../ingestion/IngestionPipeline.js";
import { Settings } from "../Settings.js";
import type { StorageContext } from "../storage/StorageContext.js";
import {
type QueryEngineParam,
QueryEngineTool,
} from "../tools/QueryEngineTool.js";
export interface BaseIndexInit<T> {
storageContext: StorageContext;
@@ -19,6 +25,24 @@ export interface BaseIndexInit<T> {
indexStruct: T;
}
/**
* Common parameter type for queryTool and asQueryTool
*/
export type QueryToolParams = (
| {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
options: any;
retriever?: never;
}
| {
options?: never;
retriever?: BaseRetriever;
}
) & {
responseSynthesizer?: BaseSynthesizer;
metadata?: ToolMetadata<JSONSchemaType<QueryEngineParam>> | undefined;
};
/**
* Indexes are the data structure that we store our nodes and embeddings in so
* they can be retrieved for our queries.
@@ -61,6 +85,22 @@ export abstract class BaseIndex<T> {
options?: Omit<ContextChatEngineOptions, "retriever">,
): BaseChatEngine;
/**
* Returns a query tool by calling asQueryEngine.
* Either options or retriever can be passed, but not both.
* If options are provided, they are passed to generate a retriever.
*/
asQueryTool(params: QueryToolParams): QueryEngineTool {
if (params.options) {
params.retriever = this.asRetriever(params.options);
}
return new QueryEngineTool({
queryEngine: this.asQueryEngine(params),
metadata: params?.metadata,
});
}
/**
* Insert a document into the index.
* @param document
@@ -76,4 +116,33 @@ export abstract class BaseIndex<T> {
refDocId: string,
deleteFromDocStore?: boolean,
): Promise<void>;
/**
* Alias for asRetriever
* @param options
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
retriever(options?: any): BaseRetriever {
return this.asRetriever(options);
}
/**
* Alias for asQueryEngine
* @param options you can supply your own custom Retriever and ResponseSynthesizer
*/
queryEngine(options?: {
retriever?: BaseRetriever;
responseSynthesizer?: BaseSynthesizer;
}): BaseQueryEngine {
return this.asQueryEngine(options);
}
/**
* Alias for asQueryTool
* Either options or retriever can be passed, but not both.
* If options are provided, they are passed to generate a retriever.
*/
queryTool(params: QueryToolParams): QueryEngineTool {
return this.asQueryTool(params);
}
}
@@ -19,7 +19,7 @@ const DEFAULT_PARAMETERS: JSONSchemaType<QueryEngineParam> = {
export type QueryEngineToolParams = {
queryEngine: BaseQueryEngine;
metadata: ToolMetadata<JSONSchemaType<QueryEngineParam>>;
metadata?: ToolMetadata<JSONSchemaType<QueryEngineParam>> | undefined;
};
export type QueryEngineParam = {
+7
View File
@@ -1,5 +1,12 @@
# @llamaindex/node-parser
## 1.0.8
### Patch Changes
- Updated dependencies [40ee761]
- @llamaindex/core@0.5.8
## 1.0.7
### Patch Changes
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/node-parser",
"version": "1.0.7",
"version": "1.0.8",
"description": "Node parser for LlamaIndex",
"type": "module",
"exports": {
@@ -43,7 +43,7 @@
"@llamaindex/env": "workspace:*",
"@types/html-to-text": "^9.0.4",
"@types/node": "^22.9.0",
"bunchee": "6.3.4",
"bunchee": "6.4.0",
"tree-sitter": "^0.22.1",
"web-tree-sitter": "^0.24.4"
},
+1
View File
@@ -1,4 +1,5 @@
{
"$schema": "https://turbo.build/schema.json",
"extends": ["//"],
"tasks": {
"build": {
@@ -1,5 +1,13 @@
# @llamaindex/anthropic
## 0.2.6
### Patch Changes
- aea550a: Add factory convenience factory for each LLM provider, e.g. you can use openai instead of 'new OpenAI'
- Updated dependencies [40ee761]
- @llamaindex/core@0.5.8
## 0.2.5
### Patch Changes
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "@llamaindex/anthropic",
"description": "Anthropic Adapter for LlamaIndex",
"version": "0.2.5",
"version": "0.2.6",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
@@ -31,7 +31,7 @@
"test": "vitest run"
},
"devDependencies": {
"bunchee": "6.3.4",
"bunchee": "6.4.0",
"vitest": "^2.1.5"
},
"dependencies": {
+2 -14
View File
@@ -1,14 +1,2 @@
export {
AnthropicAgent,
AnthropicAgentWorker,
type AnthropicAgentParams,
} from "./agent";
export {
ALL_AVAILABLE_ANTHROPIC_LEGACY_MODELS,
ALL_AVAILABLE_ANTHROPIC_MODELS,
ALL_AVAILABLE_V3_5_MODELS,
ALL_AVAILABLE_V3_MODELS,
Anthropic,
AnthropicSession,
type AnthropicAdditionalChatOptions,
} from "./llm";
export * from "./agent";
export * from "./llm";
+9 -1
View File
@@ -60,7 +60,7 @@ const defaultAnthropicSession: {
* @param options
* @returns
*/
export function getAnthropicSession(options: ClientOptions = {}) {
function getAnthropicSession(options: ClientOptions = {}) {
let session = defaultAnthropicSession.find((session) => {
return isDeepEqual(session.options, options);
})?.session;
@@ -586,3 +586,11 @@ export class Anthropic extends ToolCallLLM<
};
}
}
/**
* Convenience function to create a new Anthropic instance.
* @param init - Optional initialization parameters for the Anthropic instance.
* @returns A new Anthropic instance.
*/
export const anthropic = (init?: ConstructorParameters<typeof Anthropic>[0]) =>
new Anthropic(init);
+9
View File
@@ -1,5 +1,14 @@
# @llamaindex/clip
## 0.0.44
### Patch Changes
- Updated dependencies [aea550a]
- Updated dependencies [40ee761]
- @llamaindex/openai@0.1.60
- @llamaindex/core@0.5.8
## 0.0.43
### Patch Changes
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "@llamaindex/clip",
"description": "Clip Embedding Adapter for LlamaIndex",
"version": "0.0.43",
"version": "0.0.44",
"type": "module",
"types": "dist/index.d.ts",
"main": "dist/index.cjs",
@@ -39,7 +39,7 @@
"dev": "bunchee --watch"
},
"devDependencies": {
"bunchee": "6.3.4"
"bunchee": "6.4.0"
},
"dependencies": {
"@huggingface/transformers": "^3.0.2",

Some files were not shown because too many files have changed in this diff Show More