Skip to content

Pollination#127

Closed
GauravKarakoti wants to merge 5 commits intohuamanraj:mainfrom
GauravKarakoti:Pollination
Closed

Pollination#127
GauravKarakoti wants to merge 5 commits intohuamanraj:mainfrom
GauravKarakoti:Pollination

Conversation

@GauravKarakoti
Copy link
Copy Markdown
Contributor

@GauravKarakoti GauravKarakoti commented Feb 27, 2026

Closes #126

Also add NEXT_PUBLIC_POLLINATIONS_API_KEY in your .env

Summary by CodeRabbit

  • New Features

    • Content summarizer now returns real AI-generated summaries.
  • Improvements

    • Token-based API authentication with fallback for reliability.
    • Configurable/default AI models via environment settings.
    • More reliable image generation behavior and clearer failure feedback.
    • Enhanced error handling and more user-friendly messages for AI requests.
  • Chores

    • Updated development dependency versions.

@vercel
Copy link
Copy Markdown

vercel Bot commented Feb 27, 2026

@GauravKarakoti is attempting to deploy a commit to the huamanraj's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Feb 27, 2026

Warning

Rate limit exceeded

@GauravKarakoti has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 13 minutes and 54 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 3f1d3e5 and 3c12351.

📒 Files selected for processing (1)
  • src/components/tools/ContentSummarizer.tsx
📝 Walkthrough

Walkthrough

Replaced local/mocked logic with real Pollinations v1 API calls across text, chat, image hooks and UI components; standardized endpoints to gen.pollinations.ai, added token/key authentication (NEXT_PUBLIC_POLLINATIONS_TOKEN || POLLINATIONS_API_KEY), and relaxed model types to string with env-driven defaults.

Changes

Cohort / File(s) Summary
Dependency
package.json
Dev dependency @types/node pinned from ^20 to ^20.19.35.
Text Hook
src/hooks/use-pollinations-text.ts
Switched endpoint to https://gen.pollinations.ai/v1/chat/completions; added Authorization Bearer token when present; centralized headers; retry/backoff retained; model type broadened to string and default via NEXT_PUBLIC_POLLINATIONS_TEXT_MODEL.
Chat Hook
src/hooks/use-pollinations-chat.ts
Endpoint now https://gen.pollinations.ai/v1/chat/completions; token fallback NEXT_PUBLIC_POLLINATIONS_TOKEN
Image Hook
src/hooks/use-pollinations-image.ts
Image URL base changed to https://gen.pollinations.ai/image/...; query params built with URLSearchParams (width, height, nologo, model, optional key param from token); model type broadened to string with env default NEXT_PUBLIC_POLLINATIONS_IMAGE_MODEL.
UI Components
src/components/tools/ContentSummarizer.tsx, src/components/tools/ImageGenerator.tsx
Replaced in-function mocks/timeouts with real fetch calls to gen.pollinations.ai endpoints; ContentSummarizer POSTs chat messages with system prompt based on summaryLength and uses env model; ImageGenerator builds image URL via URLSearchParams and includes token/key when present; added error handling and finalization flows.
Types/Interfaces
src/hooks/...
Several option interfaces updated: model fields changed from specific unions to string across text/chat/image hooks.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant App as App (UI / hooks)
    participant Pollinations as Pollinations API

    User->>App: Request summary or image
    App->>App: Build payload / URL (include model default, build headers or key)
    App->>Pollinations: POST/GET https://gen.pollinations.ai/... (Authorization: Bearer token OR ?key=token)
    Pollinations-->>App: Return result (text content or image URL) or error
    App-->>User: Render content or show error
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

✨ No more fakes, the endpoints hum alive,
Tokens tucked in env, models now can thrive,
Images baked by URLs, summaries fetched and shown,
Gen Pollinations answers, wired straight to home 🌱

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Title check ⚠️ Warning Title 'Pollination' is vague and does not convey the specific changes made to the API integration or environment configuration updates. Revise title to clearly describe the main change, e.g., 'Update Pollinations API integration to new endpoints with env-based configuration'.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed PR successfully updates Pollinations API to new endpoints, implements token-based authentication, makes models configurable via environment variables, and uses cost-effective models.
Out of Scope Changes check ✅ Passed All changes are directly related to updating Pollinations API integration per issue #126; dependency version bump in package.json supports the overall modernization effort.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/hooks/use-pollinations-chat.ts (1)

31-31: Remove unnecessary any[] type annotation.

prev is already typed as ChatMessage[] from useState<ChatMessage[]>. The explicit any[] weakens type safety.

Fix
-    setMessages((prev: any[]) => [...prev, newUserMessage]);
+    setMessages((prev) => [...prev, newUserMessage]);

Same applies to line 71.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/hooks/use-pollinations-chat.ts` at line 31, The setMessages updater in
use-pollinations-chat uses an unnecessary any[] annotation for the callback
parameter; remove the explicit type so TypeScript will infer the correct
ChatMessage[] type from the state (or explicitly use ChatMessage[] if you
prefer) in both occurrences where setMessages((prev: any[]) => [...prev,
newUserMessage]) appears (also apply the same change to the second occurrence
around line 71) so you restore proper typing and avoid weakening type safety.
src/components/tools/ImageGenerator.tsx (1)

33-45: Consider using usePollinationsImage hook.

This component duplicates image generation logic that already exists in use-pollinations-image.ts. Using the hook would reduce duplication and ensure consistent behavior.

That said, the API integration changes here are correct.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/components/tools/ImageGenerator.tsx` around lines 33 - 45, The
ImageGenerator component duplicates the Pollinations fetch logic; replace the
manual URL/build-and-fetch block in ImageGenerator.tsx with the existing
usePollinationsImage hook from use-pollinations-image.ts: remove the
URLSearchParams/token/url/fetch code and instead call the hook (e.g.,
usePollinationsImage({ prompt, width, height, model: 'flux', nologo: true }))
and use its returned state/handler to trigger image generation and receive the
response; ensure you pass the same parameters (prompt, width, height, model,
nologo and token fallback) and update any local state/props usage to consume the
hook's result so behavior remains identical.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/components/tools/ContentSummarizer.tsx`:
- Around line 62-63: The code in ContentSummarizer directly reads
result.choices[0].message.content which can throw if the API response shape is
unexpected; update the logic in the async handler that sets summary (where
response.json() is assigned to result and setSummary is called) to use optional
chaining and a safe fallback — e.g., derive content via
result?.choices?.[0]?.message?.content ?? result?.choices?.[0]?.text ?? '' — and
only call setSummary with that safe value (or bail/handle error if no content).

In `@src/hooks/use-pollinations-chat.ts`:
- Line 9: The text hook's model union (the "model" optional property in
use-pollinations-chat.ts) is missing the 'claude-fast' option; update the type
declaration for model?: 'openai' | 'gemini-fast' | 'mistral' to include '|
'claude-fast'' so it matches the chat hook's allowed models (ensure the same
literal 'claude-fast' string is used).

---

Nitpick comments:
In `@src/components/tools/ImageGenerator.tsx`:
- Around line 33-45: The ImageGenerator component duplicates the Pollinations
fetch logic; replace the manual URL/build-and-fetch block in ImageGenerator.tsx
with the existing usePollinationsImage hook from use-pollinations-image.ts:
remove the URLSearchParams/token/url/fetch code and instead call the hook (e.g.,
usePollinationsImage({ prompt, width, height, model: 'flux', nologo: true }))
and use its returned state/handler to trigger image generation and receive the
response; ensure you pass the same parameters (prompt, width, height, model,
nologo and token fallback) and update any local state/props usage to consume the
hook's result so behavior remains identical.

In `@src/hooks/use-pollinations-chat.ts`:
- Line 31: The setMessages updater in use-pollinations-chat uses an unnecessary
any[] annotation for the callback parameter; remove the explicit type so
TypeScript will infer the correct ChatMessage[] type from the state (or
explicitly use ChatMessage[] if you prefer) in both occurrences where
setMessages((prev: any[]) => [...prev, newUserMessage]) appears (also apply the
same change to the second occurrence around line 71) so you restore proper
typing and avoid weakening type safety.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between d4e8139 and d71d95f.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (6)
  • package.json
  • src/components/tools/ContentSummarizer.tsx
  • src/components/tools/ImageGenerator.tsx
  • src/hooks/use-pollinations-chat.ts
  • src/hooks/use-pollinations-image.ts
  • src/hooks/use-pollinations-text.ts

Comment thread src/components/tools/ContentSummarizer.tsx Outdated
Comment thread src/hooks/use-pollinations-chat.ts Outdated
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@huamanraj
Copy link
Copy Markdown
Owner

keep the api key server site! it is a secreat key and also keep llm model in env

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (2)
src/hooks/use-pollinations-text.ts (1)

46-54: ⚠️ Potential issue | 🔴 Critical

Same secret-handling issue: client-side token usage must be removed.

Line 46-54 repeats browser-side credential usage; move this call behind a server endpoint.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/hooks/use-pollinations-text.ts` around lines 46 - 54, The client-side
hook usePollinationsText currently reads process.env and sets a token variable
and Authorization header, then calls
https://gen.pollinations.ai/v1/chat/completions directly; remove all secret
handling and the direct external fetch from the hook and instead call an
internal server endpoint (e.g. POST /api/pollinations) from usePollinationsText
without referencing process.env or building Authorization in the browser;
implement a server-side route/function that reads the server-only env var
(POLLINATIONS_API_KEY), forwards the request to
https://gen.pollinations.ai/v1/chat/completions with the Authorization header,
and returns the response to the client so the client code (usePollinationsText)
no longer exposes credentials.
src/hooks/use-pollinations-chat.ts (1)

36-41: ⚠️ Potential issue | 🔴 Critical

Same secret-handling issue: token read/sent from client hook.

This repeats the root cause already flagged: browser-side token auth cannot keep API keys secret.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/hooks/use-pollinations-chat.ts` around lines 36 - 41, The hook reads
NEXT_PUBLIC_POLLINATIONS_TOKEN or POLLINATIONS_API_KEY into token and adds it to
headers in use-pollinations-chat.ts (token, headers), exposing a secret in
client code; remove client-side usage of POLLINATIONS_API_KEY and stop adding
Authorization in this hook, instead call a server-side API route (e.g.,
/api/pollinations) that injects the real secret on the server and forwards
requests to Pollinations, or use a server-only function that returns proxied
responses; update the hook to call that server endpoint without any secret and
adjust any handler functions that relied on token/headers accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/components/tools/ContentSummarizer.tsx`:
- Around line 39-58: The client-side code in ContentSummarizer.tsx currently
reads tokens (NEXT_PUBLIC_POLLINATIONS_TOKEN / POLLINATIONS_API_KEY) and calls
Pollinations directly (fetch to
https://gen.pollinations.ai/v1/chat/completions), exposing secrets and
hardcoding the model; move this logic server-side by implementing an API route
(e.g., /api/pollinations/summarize) that reads POLLINATIONS_API_KEY from server
env, composes the request (including Authorization and model selection) and
proxies the response; then update ContentSummarizer (and similarly
use-pollinations-text.ts, use-pollinations-chat.ts, ImageGenerator.tsx) to call
the new server route without using NEXT_PUBLIC_* or accessing
POLLINATIONS_API_KEY, and ensure the server route validates/sanitizes input and
returns errors/response to the client.

In `@src/hooks/use-pollinations-chat.ts`:
- Line 31: The updater callback for setMessages is using prev: any[] but the
state is ChatMessage[]; change both updater signatures (the one that appends
newUserMessage and the one that appends the bot reply) to use (prev:
ChatMessage[]) => [...prev, newUserMessage] / [...prev, newBotMessage] so the
updater matches the declared ChatMessage[] state (refer to setMessages,
ChatMessage, newUserMessage and the corresponding newBotMessage usage).

---

Duplicate comments:
In `@src/hooks/use-pollinations-chat.ts`:
- Around line 36-41: The hook reads NEXT_PUBLIC_POLLINATIONS_TOKEN or
POLLINATIONS_API_KEY into token and adds it to headers in
use-pollinations-chat.ts (token, headers), exposing a secret in client code;
remove client-side usage of POLLINATIONS_API_KEY and stop adding Authorization
in this hook, instead call a server-side API route (e.g., /api/pollinations)
that injects the real secret on the server and forwards requests to
Pollinations, or use a server-only function that returns proxied responses;
update the hook to call that server endpoint without any secret and adjust any
handler functions that relied on token/headers accordingly.

In `@src/hooks/use-pollinations-text.ts`:
- Around line 46-54: The client-side hook usePollinationsText currently reads
process.env and sets a token variable and Authorization header, then calls
https://gen.pollinations.ai/v1/chat/completions directly; remove all secret
handling and the direct external fetch from the hook and instead call an
internal server endpoint (e.g. POST /api/pollinations) from usePollinationsText
without referencing process.env or building Authorization in the browser;
implement a server-side route/function that reads the server-only env var
(POLLINATIONS_API_KEY), forwards the request to
https://gen.pollinations.ai/v1/chat/completions with the Authorization header,
and returns the response to the client so the client code (usePollinationsText)
no longer exposes credentials.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between d71d95f and b1254cd.

📒 Files selected for processing (5)
  • src/components/tools/ContentSummarizer.tsx
  • src/components/tools/ImageGenerator.tsx
  • src/hooks/use-pollinations-chat.ts
  • src/hooks/use-pollinations-image.ts
  • src/hooks/use-pollinations-text.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/hooks/use-pollinations-image.ts
  • src/components/tools/ImageGenerator.tsx

Comment thread src/components/tools/ContentSummarizer.tsx Outdated
Comment thread src/hooks/use-pollinations-chat.ts Outdated
@GauravKarakoti
Copy link
Copy Markdown
Contributor Author

Done... switched NEXT_PUBLIC_POLLINATIONS_API_KEY to POLLINATIONS_API_KEY and added NEXT_PUBLIC_POLLINATIONS_TEXT_MODEL
NEXT_PUBLIC_POLLINATIONS_IMAGE_MODEL

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/hooks/use-pollinations-chat.ts (2)

9-13: ⚠️ Potential issue | 🟠 Major

temperature and reasoning_effort are no-ops right now.

These options are exposed in PollinationsChatOptions but never sent in the payload. Either forward them or remove them from the public interface.

Suggested fix
       const payload: Record<string, unknown> = {
         model: options.model || defaultModel,
         messages: [...messages, newUserMessage]
       };

+      if (options.temperature !== undefined) {
+        payload.temperature = options.temperature;
+      }
+
       if (options.max_tokens !== undefined) {
         payload.max_tokens = options.max_tokens;
       }
+
+      if (options.reasoning_effort !== undefined) {
+        payload.reasoning_effort = options.reasoning_effort;
+      }

Also applies to: 45-52

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/hooks/use-pollinations-chat.ts` around lines 9 - 13, The
PollinationsChatOptions interface exposes temperature and reasoning_effort but
they are not forwarded in the request payload; update the hook
(usePollinationsChat) to include options.temperature and
options.reasoning_effort when building the request body (where the chat payload
is assembled—e.g., the function that sends the request or
buildRequestBody/sendMessage inside usePollinationsChat) or remove these fields
from PollinationsChatOptions if not supported; ensure the request keys match the
API names (temperature and reasoning_effort) and update all places referenced by
PollinationsChatOptions (including the payload assembly used around lines
~45-52) so the public interface and actual payload are consistent.

67-71: ⚠️ Potential issue | 🟠 Major

Guard response shape before dereferencing choices[0].

If the provider returns a partial/error payload, this will throw before your catch can produce a clean user-facing error.

Suggested fix
       const result = await response.json();
+      const content = result?.choices?.[0]?.message?.content;
+      if (!content) {
+        throw new Error('Empty response from API');
+      }
       const assistantMessage: ChatMessage = {
         role: 'assistant',
-        content: result.choices[0].message.content
+        content
       };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/hooks/use-pollinations-chat.ts` around lines 67 - 71, The code
dereferences result.choices[0].message.content without validating the response
shape; update the logic after response.json() to check that result exists,
result.choices is an array with at least one element, and that
result.choices[0].message and .content are defined before constructing
assistantMessage (or throw/return a controlled error/fallback). Locate the
result variable and the assistantMessage creation and add a guard (e.g.,
validate Array.isArray(result.choices) && result.choices.length>0 &&
result.choices[0].message?.content) and handle the invalid shape by
logging/throwing a clear error or substituting a safe default.
src/hooks/use-pollinations-image.ts (1)

28-72: ⚠️ Potential issue | 🟠 Major

Add cancellation guard for Image() callbacks.

Without cleanup, fast prompt/option changes can let an older request win and overwrite the latest state.

Suggested fix
   useEffect(() => {
     if (!prompt) {
       setImageUrl(null);
       setLoading(false);
       return;
     }
+    let isActive = true;

     const generateImage = async () => {
       setImageUrl(null);
       setLoading(true);
       setError(null);

       try {
@@
         const img = new Image();
         img.onload = () => {
+          if (!isActive) return;
           setImageUrl(url);
           setLoading(false);
         };
         img.onerror = () => {
+          if (!isActive) return;
           setError('Failed to load image');
           setLoading(false);
         };
         img.src = url;
@@
     };

     generateImage();
+    return () => {
+      isActive = false;
+    };
   }, [prompt, options.model, options.width, options.height, options.seed, options.nologo, options.enhance, options.private]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/hooks/use-pollinations-image.ts` around lines 28 - 72, The Image
onload/onerror callbacks in generateImage can race and update state for
out-of-date requests; add a cancellation guard and cleanup so only the latest
invocation updates state: create a local cancelled flag or requestId inside
generateImage (or the surrounding useEffect) and check it at the start of each
onload/onerror before calling setImageUrl/setError/setLoading, and in the
useEffect cleanup set cancelled=true and detach callbacks (img.onload =
img.onerror = null and optionally img.src = ''), ensuring generateImage,
img.onload, and img.onerror are the symbols you modify.
♻️ Duplicate comments (1)
src/components/tools/ContentSummarizer.tsx (1)

39-60: ⚠️ Potential issue | 🔴 Critical

Move Pollinations auth/calls server-side; client-side key handling is still unsafe.

This client component reads token env vars and calls Pollinations directly. In Next.js, NEXT_PUBLIC_* values are public in the browser bundle, and non-NEXT_PUBLIC_* values are not available client-side. That means this pattern either exposes credentials or silently drops auth.
Same pattern is present in src/hooks/use-pollinations-chat.ts, src/hooks/use-pollinations-text.ts, src/hooks/use-pollinations-image.ts, and src/components/tools/ImageGenerator.tsx.

Suggested fix (client-side part)
-      const token = process.env.NEXT_PUBLIC_POLLINATIONS_TOKEN || process.env.POLLINATIONS_API_KEY;
-      const headers: HeadersInit = { 'Content-Type': 'application/json' };
-      if (token) headers['Authorization'] = `Bearer ${token}`;
+      const headers: HeadersInit = { 'Content-Type': 'application/json' };
@@
-      const defaultModel = process.env.NEXT_PUBLIC_POLLINATIONS_TEXT_MODEL || "openai";
-
-      const response = await fetch("https://gen.pollinations.ai/v1/chat/completions", {
+      const response = await fetch("/api/pollinations/summarize", {
         method: "POST",
         headers,
         body: JSON.stringify({
-          model: defaultModel,
-          messages: [
-            { role: "system", content: systemPrompt },
-            { role: "user", content: `Please summarize the following text:\n\n${inputText}` }
-          ]
+          inputText,
+          summaryLength
         })
       });

Run this to verify scope and blast radius:

#!/bin/bash
# Expectation:
# 1) no Pollinations credential reads in client files
# 2) Pollinations upstream calls only inside server routes

rg -n --type ts --type tsx 'process\.env\.(NEXT_PUBLIC_POLLINATIONS_TOKEN|POLLINATIONS_API_KEY|NEXT_PUBLIC_POLLINATIONS_[A-Z_]+)' src
rg -n --type ts --type tsx '"use client"' src/components src/hooks
fd "route.ts" src/app/api 2>/dev/null || true
rg -n --type ts --type tsx 'gen\.pollinations\.ai|pollinations' src/app/api 2>/dev/null || true

Refs:
https://nextjs.org/docs/app/guides/environment-variables
https://nextjs.org/docs/app/building-your-application/rendering/server-components
https://auth.pollinations.ai/

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/components/tools/ContentSummarizer.tsx` around lines 39 - 60, The client
component ContentSummarizer.tsx (references: token, headers, defaultModel,
systemPrompt, inputText, and the fetch to
"https://gen.pollinations.ai/v1/chat/completions") must not read non-public env
vars or call Pollinations directly; instead create a server API route that reads
process.env.POLLINATIONS_API_KEY/ NEXT_PRIVATE var and forwards a sanitized
request to Pollinations (including Authorization header and model/messages),
then update ContentSummarizer to call that internal route (no env reads, no
Authorization header) and pass only necessary payload; apply the same refactor
to use-pollinations-chat.ts, use-pollinations-text.ts,
use-pollinations-image.ts, and ImageGenerator.tsx so all Pollinations network
calls and secret access occur server-side.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@src/hooks/use-pollinations-chat.ts`:
- Around line 9-13: The PollinationsChatOptions interface exposes temperature
and reasoning_effort but they are not forwarded in the request payload; update
the hook (usePollinationsChat) to include options.temperature and
options.reasoning_effort when building the request body (where the chat payload
is assembled—e.g., the function that sends the request or
buildRequestBody/sendMessage inside usePollinationsChat) or remove these fields
from PollinationsChatOptions if not supported; ensure the request keys match the
API names (temperature and reasoning_effort) and update all places referenced by
PollinationsChatOptions (including the payload assembly used around lines
~45-52) so the public interface and actual payload are consistent.
- Around line 67-71: The code dereferences result.choices[0].message.content
without validating the response shape; update the logic after response.json() to
check that result exists, result.choices is an array with at least one element,
and that result.choices[0].message and .content are defined before constructing
assistantMessage (or throw/return a controlled error/fallback). Locate the
result variable and the assistantMessage creation and add a guard (e.g.,
validate Array.isArray(result.choices) && result.choices.length>0 &&
result.choices[0].message?.content) and handle the invalid shape by
logging/throwing a clear error or substituting a safe default.

In `@src/hooks/use-pollinations-image.ts`:
- Around line 28-72: The Image onload/onerror callbacks in generateImage can
race and update state for out-of-date requests; add a cancellation guard and
cleanup so only the latest invocation updates state: create a local cancelled
flag or requestId inside generateImage (or the surrounding useEffect) and check
it at the start of each onload/onerror before calling
setImageUrl/setError/setLoading, and in the useEffect cleanup set cancelled=true
and detach callbacks (img.onload = img.onerror = null and optionally img.src =
''), ensuring generateImage, img.onload, and img.onerror are the symbols you
modify.

---

Duplicate comments:
In `@src/components/tools/ContentSummarizer.tsx`:
- Around line 39-60: The client component ContentSummarizer.tsx (references:
token, headers, defaultModel, systemPrompt, inputText, and the fetch to
"https://gen.pollinations.ai/v1/chat/completions") must not read non-public env
vars or call Pollinations directly; instead create a server API route that reads
process.env.POLLINATIONS_API_KEY/ NEXT_PRIVATE var and forwards a sanitized
request to Pollinations (including Authorization header and model/messages),
then update ContentSummarizer to call that internal route (no env reads, no
Authorization header) and pass only necessary payload; apply the same refactor
to use-pollinations-chat.ts, use-pollinations-text.ts,
use-pollinations-image.ts, and ImageGenerator.tsx so all Pollinations network
calls and secret access occur server-side.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between b1254cd and 3f1d3e5.

📒 Files selected for processing (5)
  • src/components/tools/ContentSummarizer.tsx
  • src/components/tools/ImageGenerator.tsx
  • src/hooks/use-pollinations-chat.ts
  • src/hooks/use-pollinations-image.ts
  • src/hooks/use-pollinations-text.ts

@GauravKarakoti GauravKarakoti closed this by deleting the head repository Apr 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Update pollination apis as new doc

2 participants