Power Your dApp with ChatGPT

Gelato Team

Jun 27, 2023

The combination of AI and Web3 has the potential to address existing challenges in the field of AI while unlocking numerous innovative opportunities. By bringing AI onto the blockchain, smart contracts gain the ability to make autonomous decisions and predictions based on dynamic on-chain data. This can lead to entirely new functionalities, all without human input. AI agents may also use crypto infrastructure for payments and to access digital resources like storage, compute, and bandwidth.

For example, imagine an AI programmed to write code for companies. This AI, working 24/7, could be employed through blockchain-based smart contracts and automatically paid for each pull request it successfully merges. This not only shows a real-world application but also signals a new era in software development.

Across sectors, this union of AI and Web3 is already creating ripples. In DeFi, machine learning powers predictive analysis and dynamic parameter adjustments. In gaming, AI enhances player experiences through adaptive content. In social media, AI drives automated posting and personalized content feeds. These are just a few examples of what’s possible.

In this tutorial, we’ll explore how Gelato’s Web3 Functions enable smart contracts to harness the OpenAI ChatGPT API for generating creative content. With Web3 Functions, smart contracts can seamlessly access off-chain data. In our demo application, Gelato Web3 Functions connect to the OpenAI API to generate content and automate posts every 8 hours.

AI-enabled Content Posting

The workflow begins with the LensGelatoGPT smart contract, which manages prompts for AI content creation. It communicates with LensHub.sol, the core Lens Protocol contract, to ensure actions are performed by the rightful profile owners.

Gelato Web3 Functions then:

  • Fetch prompts from LensGelatoGPT

  • Generate content via OpenAI

  • Validate metadata with LensClient

  • Upload metadata to IPFS via Web3.Storage

  • Call LensHub.post() to publish content on Lens

The result: automated AI-generated content appears on Lenster, a social app built with Lens Protocol — all executed by Gelato Web3 Functions.

Prerequisites

  • Access to Gelato Web3 Functions beta

  • Installed Node.js v16+, NPM, and Git

  • A Web3 wallet (e.g. MetaMask)

  • Accounts on Alchemy, Web3.Storage, and OpenAI

Set Up Your Dev Environment

git clone https://github.com/gelatodigital/lensgpt-tutorial.git
cd lensgpt-tutorial
yarn install

Configure Secrets

Fill in the following in your .env file:

  • Alchemy API ID

  • Private Key from your wallet

  • OpenAI API Key

  • Web3.Storage API Key

LensGelatoGPT Smart Contract

The contract validates profile ownership and manages prompts:

function setPrompt(uint256 _profileId, string calldata _prompt) 
  external payable onlyProfileOwner(_profileId) {
  require(msg.value == fee, "fee required");
  require(bytes(_prompt).length <= 160, "prompt too long");
  require(lensHub.getDispatcher(_profileId) == dedicatedMsgSender, "dispatcher invalid");
  _profileIds.add(_profileId);
  promptByProfileId[_profileId] = _prompt;
}

Other functions include stopPrompt(), getPaginatedPrompts(), and collectFee().

LensGelatoGPT Web3 Function

This Web3 Function fetches prompts, calls OpenAI to generate text, uploads the result to IPFS, and posts content to LensHub.

// Fetch prompts
const prompts = await lensGelatoGpt.getPaginatedPrompts(start, end);

// Generate AI text with OpenAI
const response = await openai.createCompletion({ model: "text-davinci-003", prompt });
const text = response.data.choices[0].text;

// Upload metadata to IPFS
const cid = await storage.put([myFile]);
const contentURI = `https://${cid}.ipfs.w3s.link/publication.json`;

// Post on LensHub
callDatas.push({
  to: lensHubAddress,
  data: iface.encodeFunctionData("post", [postData]),
});

Deploy & Run

Deploy the contract on Polygon Mumbai:

npx hardhat run deploy/LensGelatoGPT.deploy.ts --network mumbai

Deploy the Web3 Function:

npx hardhat w3f-deploy lensChatGPT

You’ll get an IPFS CID. Use it to create a new task in the Gelato dashboard: https://beta.app.gelato.cloud/new-task

Create a Web3 Function Task via UI

  1. Go to the provided link with your CID.

  2. Enter user arguments (lensGelatoGPT, lensHubAddress, collectModule).

  3. Select the network (e.g. Mumbai).

  4. Add secrets (Web3.Storage and OpenAI keys).

  5. Name the task and confirm creation with your wallet.

Monitor Your Task

Use the Web3 Functions Task dashboard to track:

  • Executions per run

  • Logs from your code

  • Storage state and secrets

Conclusion

We explored how to integrate AI and blockchain by combining OpenAI, Web3.Storage, Lens Protocol, and Gelato. This workflow enables automated, AI-powered content generation and posting — a tangible example of the convergence of AI and Web3.

Happy coding, and welcome to the internet of tomorrow!

Dive Deeper with Gelato

Web3 Functions let developers create serverless, decentralized applications with ease.

Ready to build?

Start with a testnet, launch your mainnet in days, and scale with industry-leading UX.

Ready to build?

Start with a testnet, launch your mainnet in days, and scale with industry-leading UX.

Ready to build?

Start with a testnet, launch your mainnet in days, and scale with industry-leading UX.

Ready to build?

Start with a testnet, launch your mainnet in days, and scale with industry-leading UX.