Skip to content

HashWarlock/ai-agent-template-red-pill

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation



Host your AI Agent Contract on Phala's decentralized serverless cloud.
Explore the docs »

View Demo · Report Bug · Discord

Architecure Overview

🤖 What Is This?!

The OpenAI AI Agent template is a MINIMAL template to build an AI Agent that can be hosted on Phala Network's decentralized hosting protocol. Unlike Vercel or other FaaS, it allows you to publish your AI Agent compiled code to IPFS and hosts it on a fully decentralized FaaS cloud with the following benefits:

  • 💨 Ship Fast: Build and ship with familiar toolchain in minutes
  • ⛑️ Secure: Execution guarded by rock solid TEE / Intel SGX
  • 🔒 Private: Host API keys and user privacy at ease
  • 💎 Unstoppable: Powered by IPFS and Phala's 35k+ decentralized TEE workers

Getting Started

Prepare

Install dependencies

npm install

Testing Locally

Create .env file and add your OpenAI API Key

cp .env.local .env

Get an OpenAI API Key from Redpill

Go to https://red-pill.ai/dashboard and claim your OpenAI API Key by swapping some ETH for wGPT at https://app.uniswap.org/explore/tokens/base/0x74F62Bc1961028C22b8080961c6534f4eDD49D6C

Video: https://youtu.be/ZoJwbLNhbWE

In .env file replace YOUR_OPENAI_KEY with your API Key

OPENAI_API_KEY="YOUR_OPENAI_KEY"

Build your Agent

npm run build

Test your Agent locally

npm run test

Expected Test Results

INPUT: {"method":"GET","path":"/ipfs/QmVHbLYhhYA5z6yKpQr4JWr3D54EhbSsh7e7BFAAyrkkMf","queries":{"chatQuery":["Who are you?"]},"secret":{"openaiApiKey":"YOUR_OPENAI_KEY"},"headers":{}}
GET RESULT: {
  status: 200,
  body: '\n' +
    '    <!DOCTYPE html>\n' +
    '    <html lang="en">\n' +
    '        <head>\n' +
    '            <meta charset="utf-8" />\n' +
    '            <title>TestUI</title>\n' +
    '        </head>\n' +
    '        <body>\n' +
    '            <div align="center">\n' +
    '                <p>I am an AI-powered digital assistant here to help answer your questions and assist you with various tasks. How can I assist you today?</p>\n' +
    '            </div>\n' +
    '        </body>\n' +
    '    </html>',
  headers: {
    'Content-Type': 'text/html; charset=UTF-8',
    'Access-Control-Allow-Origin': '*'
  }
}


INPUT: {"method":"POST","path":"/ipfs/QmVHbLYhhYA5z6yKpQr4JWr3D54EhbSsh7e7BFAAyrkkMf","queries":{"chatQuery":["When did humans land on the moon?"]},"secret":{"openaiApiKey":"YOUR_OPENAI_KEY"},"headers":{},"body":"{\"untrustedData\":{\"fid\":2,\"url\":\"https://fcpolls.com/polls/1\",\"messageHash\":\"0xd2b1ddc6c88e865a33cb1a565e0058d757042974\",\"timestamp\":1706243218,\"network\":1,\"buttonIndex\":2,\"castId\":{\"fid\":226,\"hash\":\"0xa48dd46161d8e57725f5e26e34ec19c13ff7f3b9\"}},\"trustedData\":{\"messageBytes\":\"d2b1ddc6c88e865a33cb1a565e0058d757042974...\"}}"}
POST RESULT: {
  status: 200,
  body: '\n' +
    '    <!DOCTYPE html>\n' +
    '    <html lang="en">\n' +
    '        <head>\n' +
    '            <meta charset="utf-8" />\n' +
    '            <title>TestUI</title>\n' +
    '        </head>\n' +
    '        <body>\n' +
    '            <div align="center">\n' +
    "                <p>Humans first landed on the moon on July 20, 1969, during NASA's Apollo 11 mission.</p>\n" +
    '            </div>\n' +
    '        </body>\n' +
    '    </html>',
  headers: {
    'Content-Type': 'text/html; charset=UTF-8',
    'Access-Control-Allow-Origin': '*'
  }
}

Publish Your AI Agent

Upload your compiled AI Agent code to IPFS.

npm run publish

Upon a successful upload, the command should show the URL to access your AI Agent.

AI Agent deployed at: https://agents.phala.network/ipfs/QmQu9AmBL13tyGpxgg5ASt96WQ669p63rnJRWiAo9st8ns/0

Make sure to add your secrets to ensure your AI Agent works properly.

New to thirdweb? We use thirdweb Storage to host IPFS contents. If you are new to thirdweb, the command will guide you to create your account or login to your existing account from the browser. (You may need to forward port 8976 if you are accessing a remote console via SSH.)
Did thirdweb fail to publish? If thirdweb takes too long to install or fails to publish, use the following command:
curl -F file=@./dist/index.js https://agents.phala.network/ipfs 

Access the Published AI Agent

Once published, your AI Agent is available at the URL: https://agents.phala.network/ipfs/<your-cid>. You can get it from the "Publish to IPFS" step.

You can test it with curl.

curl https://agents.phala.network/ipfs/<your-cid>

Add Secrets

By default, all the compiled JS code is visible for anyone to view if they look at IPFS CID. This makes private info like API keys, signer keys, etc. vulnerable to be stolen. To protect devs from leaking keys, we have added a field called secret in the Request object. It allows you to store secrets in a vault for your AI Agent to access.

How to Add Secrets

The steps to add a secret is simple. We will add the OpenAI API Key in this example by creating a secret JSON object with the openaiApiKey:

{"openaiApiKey": "<OPENAI_API_KEY>"}

Then in your frame code, you will be able to access the secret key via req.secret object:

async function POST(req: Request): Promise<Response> {
    const apiKey = req.secret?.apiKey
}

Note: Before continuing, make sure to publish your compiled AI Agent JS code, so you can add secrets to the CID.

Open terminal Use curl to POST your secrets to https://agents.phala.network/vaults. Replace IPFS_CID with the CID to the compile JS code in IPFS, and replace <OPENAI_API_KEY> with your OpenAI API key. Note that you can name the secret field name something other than openaiApiKey, but you will need to access the key in your index.ts file with the syntax req.secret?.<your-secret-field-name> as string

The command will look like this:

curl https://agents.phala.network/vaults -H 'Content-Type: application/json' -d '{"cid": "IPFS_CID", "data": {"openaiApiKey": "<OPENAI_API_KEY>"}}'
# Output:
# {"token":"e85ae53d2ba4ca8d","key":"e781ef31210e0362","succeed":true}

The API returns a token and a key. The key is the id of your secret. It can be used to specify which secret you are going to pass to your frame. The token can be used by the developer to access the raw secret. You should never leak the token.

To verify the secret, run the following command where key and token are replaced with the values from adding your secret to the vault.

curl https://agents.phala.network/vaults/<key>/<token>

Expected output:

{"data":{"openaiApiKey":"<OPENAI_API_KEY>"},"succeed":true}

If you are using secrets, make sure that your URL is set in the following syntax where cid is the IPFS CID of your compiled JS file and key is the key from adding secrets to your vault.

https://agents.phala.network/ipfs/<cid>?key=<key>

Example: https://agents.phala.network/ipfs/Qma2WjqWqW8wYG2tEQ9YFUgyVrMDA9VzvkkdeFny7Smn3R/0?key=686df81d326fa5f2&chatQuery=When%20did%20humans%20land%20on%20the%20moon

Access Queries

To help create custom logic, we have an array variable named queries that can be accessed in the Request class. To access the queries array variable chatQuery value at index 0, the syntax will look as follows:

const query = req.queries.chatQuery[0] as string;

The example at https://agents.phala.network/ipfs/Qma2WjqWqW8wYG2tEQ9YFUgyVrMDA9VzvkkdeFny7Smn3R/0?key=686df81d326fa5f2&chatQuery=When%20did%20humans%20land%20on%20the%20moon will have a value of When did humans land on the moon. queries can have any field name, so chatQuery is just an example of a field name and not a mandatory name, but remember to update your index.ts file logic to use your expected field name.

FAQ

What packages can I use in the AI Agent server?
  • Most of the npm packages are supported: viem, onchainkit, ….
  • Some packages with some advanced features are not supported:
    • Large code size. Compiled bundle should be less than 500kb.
    • Large memory usage, like image generation
    • Web Assembly
    • Browser only features: local storage, service workers, etc
What’s the spec of the Javascript runtime?
  • The code runs inside a tailored QuickJS engine
  • Available features: ES2023, async, fetch, setTimeout, setInterval, bigint
  • Resource limits
    • Max execution time ~30s
    • Max memory usage: 16 mb
    • Max code size: 500 kb
    • Limited CPU burst: CPU time between async calls is limited. e.g. Too complex for-loop may hit the burst limit.
Why is the serverless platform secure?
  • Your AI Agent code on is fully secure, private, and permissionless. Nobody can manipulate your program, steal any data from it, or censor it.
  • Security: The code is executed in the decentralized TEE network running on Phala Network. It runs code inside a secure blackbox (called enclave) created by the CPU. It generates cryptographic proofs verifiable on Phala blockchain. It proves that the hosted code is exactly the one you deployed.
  • Privacy: You can safely put secrets like API keys or user privacy on Phala Network. The code runs inside TEE hardware blackboxs. The memory of the program is fully encrypted by the TEE. It blocks any unauthorized access to your data.
  • Learn more at Phala Network Homepage
What's TEE / Intel SGX?

About

AI Agent Contract using RedPill to connect to LLM APIs

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published