Skip to content

Instantly share code, notes, and snippets.

@dylanlebouef0
Created April 29, 2025 14:28
Show Gist options
  • Save dylanlebouef0/a465daaa3cbf91253a3009a1ce5d2ad0 to your computer and use it in GitHub Desktop.
Save dylanlebouef0/a465daaa3cbf91253a3009a1ce5d2ad0 to your computer and use it in GitHub Desktop.
Ethereum + OpenAI integration using Chainlink
pragma solidity ^0.6.7;
import "@chainlink/contracts/src/v0.6/ChainlinkClient.sol";
import "@chainlink/contracts/src/v0.6/vendor/Ownable.sol";
contract ChatGPT is ChainlinkClient, Ownable {
uint256 private fee;
address private oracle;
bytes32 private jobId;
event ResponseReceived(
bytes32 indexed requestId,
uint256 indexed statusCode,
string indexed data
);
constructor(address _oracle, string memory _jobId, uint256 _fee) public {
setChainlinkToken(0xa36085F69e2889c224210F603D836748e7dC0088);
oracle = _oracle;
jobId = stringToBytes32(_jobId);
fee = _fee;
}
function requestChatGPT(string memory prompt) public returns (bytes32 requestId) {
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
request.add("get", "https://api.openai.com/v1/engines/davinci-codex/completions");
request.addHeader("Authorization", "Bearer YOUR_OPEN_AI_KEY");
request.addHeader("Content-Type", "application/json");
request.add("prompt", prompt);
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfill(bytes32 _requestId, uint256 _statusCode, string memory _data) public recordChainlinkFulfillment(_requestId) {
emit ResponseReceived(_requestId, _statusCode, _data);
}
function stringToBytes32(string memory source) private pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment