Hugging Face Gradio API integrate with Nextjs 14.2

I wanted to deploy my ML model on web, so i hosted the model on hugging face and wanted to use the api for using it with my own UI.
console error image is added for reference.
The Web framework is not contacting with the HF is the problem here, please help.

1.
root_folder/src/app/llms/mta/page.tsx

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
const [text, setText] = useState("");
const [temperature, setTemperature] = useState(0.7);
const [maxLength, setMaxLength] = useState(50);
const [model, setModel] = useState("gpt2");
const [loading, setLoading] = useState(false);
const [generatedText, setGeneratedText] = useState("");
const handleSubmit = async (e: { preventDefault: () => void; }) => {
e.preventDefault();
setLoading(true);
try {
const response = await fetch('../../api/get-text', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
text,
temperature,
maxLength,
model,
}),
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const result = await response.json();
setGeneratedText(result);
toast.success("Text generated successfully!");
} catch (error) {
console.error(error);
toast.error("An error occurred while generating text.");
}
setLoading(false);
};
</code>
<code> const [text, setText] = useState(""); const [temperature, setTemperature] = useState(0.7); const [maxLength, setMaxLength] = useState(50); const [model, setModel] = useState("gpt2"); const [loading, setLoading] = useState(false); const [generatedText, setGeneratedText] = useState(""); const handleSubmit = async (e: { preventDefault: () => void; }) => { e.preventDefault(); setLoading(true); try { const response = await fetch('../../api/get-text', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ text, temperature, maxLength, model, }), }); if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } const result = await response.json(); setGeneratedText(result); toast.success("Text generated successfully!"); } catch (error) { console.error(error); toast.error("An error occurred while generating text."); } setLoading(false); }; </code>
  
  const [text, setText] = useState("");
  const [temperature, setTemperature] = useState(0.7);
  const [maxLength, setMaxLength] = useState(50);
  const [model, setModel] = useState("gpt2");
  const [loading, setLoading] = useState(false);
  const [generatedText, setGeneratedText] = useState("");

  const handleSubmit = async (e: { preventDefault: () => void; }) => {
    e.preventDefault();
    setLoading(true);
    try {
        const response = await fetch('../../api/get-text', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              text,
              temperature,
              maxLength,
              model,
            }),
          });
          
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }
  
      const result = await response.json();
      setGeneratedText(result);
      toast.success("Text generated successfully!");
    } catch (error) {
      console.error(error);
      toast.error("An error occurred while generating text.");
    }
    setLoading(false);
  };

root_folder/src/app/api/get-text.js

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
import { Client } from "@gradio/client";
require('dotenv').config();
export default async function handler(req, res) {
if (req.method !== 'POST') {
res.status(405).json({ message: 'Method not allowed' });
return;
}
const { text, temperature, maxLength, model } = req.body;
try {
const client = await Client.connect("hexronus/portfolio", {
hf_token: `hf_${process.env.MTAText}`
});
const result = await client.predict("/predict", {
text: text || 'Hi',
temperature: temperature || 0.7,
maxLength: maxLength || '100',
model: model || 'gpt2',
});
res.status(200).json(result.data);
} catch (error) {
console.error(error);
res.status(500).json({ message: 'An error occurred while generating text.' });
}
}
</code>
<code> import { Client } from "@gradio/client"; require('dotenv').config(); export default async function handler(req, res) { if (req.method !== 'POST') { res.status(405).json({ message: 'Method not allowed' }); return; } const { text, temperature, maxLength, model } = req.body; try { const client = await Client.connect("hexronus/portfolio", { hf_token: `hf_${process.env.MTAText}` }); const result = await client.predict("/predict", { text: text || 'Hi', temperature: temperature || 0.7, maxLength: maxLength || '100', model: model || 'gpt2', }); res.status(200).json(result.data); } catch (error) { console.error(error); res.status(500).json({ message: 'An error occurred while generating text.' }); } } </code>

import { Client } from "@gradio/client";
require('dotenv').config();

export default async function handler(req, res) {
  
  if (req.method !== 'POST') {
    res.status(405).json({ message: 'Method not allowed' });
    return;
  }
  const { text, temperature, maxLength, model } = req.body;

  try {
    const client = await Client.connect("hexronus/portfolio", {
      hf_token: `hf_${process.env.MTAText}`
    });

    const result = await client.predict("/predict", {
      text: text || 'Hi',
      temperature: temperature || 0.7,
      maxLength: maxLength || '100',
      model: model || 'gpt2',
    });
    
    res.status(200).json(result.data);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'An error occurred while generating text.' });
  }
}

Hugging Face API doc

API Name: /predict

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { Client } from "@gradio/client";
const client = await Client.connect("hexronus/portfolio");
const result = await client.predict("/predict", {
text: "Hello!!",
temperature: 0.1,
maxLength: 10,
model: "gpt2",
});
console.log(result.data);
</code>
<code>import { Client } from "@gradio/client"; const client = await Client.connect("hexronus/portfolio"); const result = await client.predict("/predict", { text: "Hello!!", temperature: 0.1, maxLength: 10, model: "gpt2", }); console.log(result.data); </code>
import { Client } from "@gradio/client";

const client = await Client.connect("hexronus/portfolio");
const result = await client.predict("/predict", {       
    text: "Hello!!",        
    temperature: 0.1,       
    maxLength: 10,      
    model: "gpt2", 
});

console.log(result.data);

Parameters

  • text (string, Required)

    • The input value that is provided in the “Input Text” Textbox component.
  • temperature (number, Default: 0.7)

    • The input value that is provided in the “Temperature” Slider component.
  • maxLength (number, Default: 50)

    • The input value that is provided in the “Max Length” Slider component.
  • model (string, Required)

    • The input value that is provided in the “Model” Dropdown component.

Returns

  • string
    • The output value that appears in the “Generated Text” Textbox component.

First i tried all sorts of data format matching, i thought that may be the problem, then i checked that if my codebase at HF is faulty and the code may not be working there, but it is working, i ran the spaces gradio api for .py in colab and it worked fine but just i am not getting how to use it as an api in nextjs, also when added with page.tsx file in the client render the parameter taking part is causing problems as when we pass params by user we use the “use client” method which won’t be supported as it is an api call.

New contributor

hexronus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật