Skip to content

🎯 使用 Agent

生成文本

typescript
const result = await myAgent.generate({
  prompt: 'What is the weather like?',
});
console.log(result.text);

流式响应

typescript
const stream = myAgent.stream({
  prompt: 'Tell me a story',
});

for await (const chunk of stream.textStream) {
  console.log(chunk);
}

响应 UI 消息(API 路由)

typescript
// app/api/chat/route.ts
import { createAgentUIStreamResponse } from 'ai';

export async function POST(request: Request) {
  const { messages } = await request.json();

  return createAgentUIStreamResponse({
    agent: myAgent,
    messages,
  });
}

端到端类型安全

typescript
import { ToolLoopAgent, InferAgentUIMessage } from 'ai';

const myAgent = new ToolLoopAgent({
  // ... configuration
});

// 推断 UIMessage 类型
export type MyAgentUIMessage = InferAgentUIMessage<typeof myAgent>;

// 在客户端组件中使用
'use client';
import { useChat } from '@ai-sdk/react';
import type { MyAgentUIMessage } from '@/agent/my-agent';

export function Chat() {
  const { messages } = useChat<MyAgentUIMessage>();
  // 完整的类型安全
}

前端面试知识库