Add Search to a Chatbot
Give a chatbot a clear policy for when to search and how to handle results.
Use OptimAI Search when an answer needs current web or social evidence. Do not search every conversational turn; search when freshness or citations matter.
Search policy
- Search for current events, prices, releases, policies, or questions that require sources.
- Use the user's complete question as the query and add a timeframe or domain when it improves precision.
- Keep the user informed while the asynchronous search is running.
- Answer from the completed result and show the cited source links.
- If retrieval fails, explain whether the problem was credentials, request shape, rate limiting, or temporary service availability.
Server-side request
Keep the API key in the chatbot backend:
const response = await fetch(
"https://api-onchain.optimai.network/external/v1/search",
{
method: "POST",
headers: {
"X-API-Key": process.env.OPTIMAI_API_KEY ?? "",
"Content-Type": "application/json",
"Idempotency-Key": `chat-${messageId}`,
},
body: JSON.stringify({ query: userQuestion }),
},
)Poll the returned ID, then pass result.answer and result.citations to the
chat UI. Never expose OPTIMAI_API_KEY in a browser bundle.