Skip to content
Dashboard

The importance of adapting quickly in an ever-changing AI world.

Link to headingAgents

await generateText({
model: openai('gpt-4o'),
system: "You are a product feedback analyzer. You summarize a piece of feedback, then determine whether it is positive, negative, or neutral."
prompt: userFeedback,
});

await generateText({
model: openai('gpt-4-turbo'),
system: "You are a product feedback analyzer. You summarize feedback, then determine whether it is positive, negative, or neutral. If the feedback is not neutral, you send a message to our Slack channel with that feedback. Always clean the feedback before summarizing or categorizing. "
prompt: userFeedback,
tools: {
cleanUserFeedback: tool({
description: "Removes spam, PII, and profanity from raw user feedback",
parameters: z.object({userFeedback: z.string() }),
execute: async ({userFeedback}) => cleanUserFeedback(userFeedback),
}),
sendMessageToSlack: tool({
description: "Sends feedback to Slack"
parameters: z.object({ sentiment: z.enum(["positive", "negative", "neutral"), feedbackSummary: z.string()}),
execute: async ({ sentiment, feedbackSummary }) => {
sendMessageToSlack(sentiment, feedbackSummary)
process.exit(0);
},
}),
},
maxToolRoundtrips: 10,
});

Link to headingProviders

Link to headingEmbeddings

// 'embedding' is a single embedding object (number[])
const { embedding } = await embed({
model: openai.embedding('text-embedding-3-small'),
value: 'sunny day at the beach'
});

// 'embeddings' is an array of embedding objects (number[][]).
// It is sorted in the same order as the input values.
const { embeddings } = await embedMany({
model: openai.embedding('text-embedding-3-small'),
values: [
'sunny day at the beach',
'rainy afternoon in the city',
],
});
console.log(`Similarity from -1 to 1: ${cosineSimilarity(embeddings[0], embeddings[1])}`)

Link to headingDX Improvements

const result = await streamObject({
model: openai('gpt-4-turbo'),
schema: z.object({
name: z.object({
firstName: z.string(),
lastName: z.string(),
})
})
prompt: "Generate a random name",
onFinish({ object, error, usage, ...rest}) {
console.log("Token usage:", usage);
if (object === undefined) {
console.error("Error": error);
} else {
console.log("Success!", JSON.stringify(object, null, 2))
}
}
})

const result = await streamObject({
model: openai('gpt-4-turbo'),
schema: z.object({
name: z.object({
firstName: z.string(),
lastName: z.string()
})
}),
prompt: "Generate a random name"
});
result.object.then(({ name }) => {
// Use the fully typed, final object with no ts-ignore needed
console.log("Name:", name.firstName, name.lastName);
});

app/api/chat/route.ts
export async function POST(req: Request) {
const { messages } = await req.json();
const result = await streamText({
model: openai('gpt-4-turbo'),
messages: convertToCoreMessages(messages),
tools: {
// client-side tool that starts user interaction:
askForConfirmation: {
description: "Ask the user for confirmation",
parameters: z.object({message: z.string().describe("The message to ask for confirmation") }),
},
// client-side tool that gets the user's location:
getLocation: {
description:
"Get the user location. Always ask for confirmation before using this tool.",
parameters: z.object({}),
},
}
})
}

app/page.tsx
export default function Chat() {
const {
messages,
input,
handleInputChange,
handleSubmit,
addToolResult
} = useChat({
maxToolRoundtrips: 5,
// run client-side tools that are automatically executed
async function onToolCall({ toolCall }) {
if (toolCall.toolName === 'getLocation') {
return getUserLocation();
}
}
});
return (
<div>
{messages?.map((m: Message) => (
<div key={m.id}>
<strong>{m.role}:</strong>
{m.content}
{m.toolInvocations?.map((toolInvocation: ToolInvocation) => {
const toolCallId = toolInvocation.toolCallId;
const addResult = (result: string) =>
addToolResult({ toolCallId, result });
// render confirmation tool (client-side tool with user interaction)
if (toolInvocation.toolName === 'askForConfirmation') {
return (
<div key={toolCallId}>
{'result' in toolInvocation ? (
<b>
{toolInvocation.args.message}: {toolInvocation.result}
</b>
) : (
<>
{toolInvocation.args.message}:{' '}
<button onClick={() => addResult('Yes')}>Yes</button>
<button onClick={() => addResult('No')}>No</button>
</>
)}
</div>
);
}
})}
</div>
))}
<form onSubmit={handleSubmit}>
<input value={input} onChange={handleInputChange} />
</form>
</div>
);
}

Link to headingConclusion

Ship production-grade AI applications faster with Vercel

Talk to our team to learn more about building AI-powered applications at your organization.

Contact Us