
AI Real State Agent
Deprecated
Pricing
Pay per event

AI Real State Agent
Deprecated
This AI agent helps users discover their ideal home effortlessly. Simply input preferences like budget, number of bedrooms, bathrooms, pet-friendliness, and the AI does the rest. It analyzes listings, filters properties based on your criteria and delivers tailored recommendations.
0.0 (0)
Pricing
Pay per event
0
Monthly users
2
Runs succeeded
>99%
Last modified
4 days ago
.dockerignore
1# configurations
2.idea
3.vscode
4
5# crawlee and apify storage folders
6apify_storage
7crawlee_storage
8storage
9
10# installed files
11node_modules
12
13# git folder
14.git
15
16# dist folder
17dist
.editorconfig
1root = true
2
3[*]
4indent_style = space
5indent_size = 2
6charset = utf-8
7trim_trailing_whitespace = true
8insert_final_newline = true
9end_of_line = lf
.env.example
1APIFY_TOKEN="apify_api_1234"
2ACTOR_TEST_PAY_PER_EVENT=true
3LANGSMITH_TRACING=false
4LANGSMITH_ENDPOINT="https://api.smith.langchain.com"
5LANGSMITH_API_KEY="lsv2_pt_1234"
6LANGSMITH_PROJECT="langsmith-cool-project-name"
7OPENAI_API_KEY="sk-proj-1234"
.eslintrc
1{
2 "root": false,
3 "env": {
4 "browser": true,
5 "es2020": true,
6 "node": true
7 },
8 "extends": [
9 "@apify/eslint-config-ts"
10 ],
11 "parserOptions": {
12 "project": "./tsconfig.json",
13 "ecmaVersion": 2020
14 },
15 "ignorePatterns": [
16 "node_modules",
17 "dist",
18 "**/*.d.ts"
19 ],
20 "rules": {
21 "indent": ["error", 2],
22 "comma-dangle": ["off", 0],
23 "prefer-rest-params": ["off", 0],
24 "max-len": ["error", { "ignoreComments": true, "ignoreStrings": true, "ignoreUrls": true, "ignoreTemplateLiterals": true }]
25 }
26}
.gitignore
1# This file tells Git which files shouldn't be added to source control
2
3.idea
4.vscode
5storage
6apify_storage
7crawlee_storage
8node_modules
9dist
10tsconfig.tsbuildinfo
11.env
12
13# Added by Apify CLI
14.venv
.gitpod.yml
1image: gitpod/workspace-base:latest
2tasks:
3 - name: main
4 init: >
5 nvm use lts/jod &&
6 npm install -g npm@11 &&
7 npm install -g eslint@^8.50.0 &&
8 npm install -g apify-cli
9 command: echo "Login to apify to get an API Key, export your APIFY_TOKEN, create an INPUT.json file and run npm start!"
10 - name: config
11 before: >
12 (([[ ! -z $GITCONFIG ]] &&
13 echo $GITCONFIG | base64 -d > ~/.gitconfig &&
14 chmod 644 ~/.gitconfig) || unset GITCONFIG) &&
15 (([[ ! -z $GNUPG_1 ]] &&
16 rm -rf ~/.gnupg &&
17 cd / &&
18 echo $GNUPG_1$GNUPG_2 | base64 -d | tar --no-same-owner -xzf -) || unset GNUPG_1)
19 command: echo "Ready! Start a new terminal session in order to use GPG." && exit
LICENSE
1Apache License
2 Version 2.0, January 2004
3 http://www.apache.org/licenses/
4
5 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
7 1. Definitions.
8
9 "License" shall mean the terms and conditions for use, reproduction,
10 and distribution as defined by Sections 1 through 9 of this document.
11
12 "Licensor" shall mean the copyright owner or entity authorized by
13 the copyright owner that is granting the License.
14
15 "Legal Entity" shall mean the union of the acting entity and all
16 other entities that control, are controlled by, or are under common
17 control with that entity. For the purposes of this definition,
18 "control" means (i) the power, direct or indirect, to cause the
19 direction or management of such entity, whether by contract or
20 otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 outstanding shares, or (iii) beneficial ownership of such entity.
22
23 "You" (or "Your") shall mean an individual or Legal Entity
24 exercising permissions granted by this License.
25
26 "Source" form shall mean the preferred form for making modifications,
27 including but not limited to software source code, documentation
28 source, and configuration files.
29
30 "Object" form shall mean any form resulting from mechanical
31 transformation or translation of a Source form, including but
32 not limited to compiled object code, generated documentation,
33 and conversions to other media types.
34
35 "Work" shall mean the work of authorship, whether in Source or
36 Object form, made available under the License, as indicated by a
37 copyright notice that is included in or attached to the work
38 (an example is provided in the Appendix below).
39
40 "Derivative Works" shall mean any work, whether in Source or Object
41 form, that is based on (or derived from) the Work and for which the
42 editorial revisions, annotations, elaborations, or other modifications
43 represent, as a whole, an original work of authorship. For the purposes
44 of this License, Derivative Works shall not include works that remain
45 separable from, or merely link (or bind by name) to the interfaces of,
46 the Work and Derivative Works thereof.
47
48 "Contribution" shall mean any work of authorship, including
49 the original version of the Work and any modifications or additions
50 to that Work or Derivative Works thereof, that is intentionally
51 submitted to Licensor for inclusion in the Work by the copyright owner
52 or by an individual or Legal Entity authorized to submit on behalf of
53 the copyright owner. For the purposes of this definition, "submitted"
54 means any form of electronic, verbal, or written communication sent
55 to the Licensor or its representatives, including but not limited to
56 communication on electronic mailing lists, source code control systems,
57 and issue tracking systems that are managed by, or on behalf of, the
58 Licensor for the purpose of discussing and improving the Work, but
59 excluding communication that is conspicuously marked or otherwise
60 designated in writing by the copyright owner as "Not a Contribution."
61
62 "Contributor" shall mean Licensor and any individual or Legal Entity
63 on behalf of whom a Contribution has been received by Licensor and
64 subsequently incorporated within the Work.
65
66 2. Grant of Copyright License. Subject to the terms and conditions of
67 this License, each Contributor hereby grants to You a perpetual,
68 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 copyright license to reproduce, prepare Derivative Works of,
70 publicly display, publicly perform, sublicense, and distribute the
71 Work and such Derivative Works in Source or Object form.
72
73 3. Grant of Patent License. Subject to the terms and conditions of
74 this License, each Contributor hereby grants to You a perpetual,
75 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 (except as stated in this section) patent license to make, have made,
77 use, offer to sell, sell, import, and otherwise transfer the Work,
78 where such license applies only to those patent claims licensable
79 by such Contributor that are necessarily infringed by their
80 Contribution(s) alone or by combination of their Contribution(s)
81 with the Work to which such Contribution(s) was submitted. If You
82 institute patent litigation against any entity (including a
83 cross-claim or counterclaim in a lawsuit) alleging that the Work
84 or a Contribution incorporated within the Work constitutes direct
85 or contributory patent infringement, then any patent licenses
86 granted to You under this License for that Work shall terminate
87 as of the date such litigation is filed.
88
89 4. Redistribution. You may reproduce and distribute copies of the
90 Work or Derivative Works thereof in any medium, with or without
91 modifications, and in Source or Object form, provided that You
92 meet the following conditions:
93
94 (a) You must give any other recipients of the Work or
95 Derivative Works a copy of this License; and
96
97 (b) You must cause any modified files to carry prominent notices
98 stating that You changed the files; and
99
100 (c) You must retain, in the Source form of any Derivative Works
101 that You distribute, all copyright, patent, trademark, and
102 attribution notices from the Source form of the Work,
103 excluding those notices that do not pertain to any part of
104 the Derivative Works; and
105
106 (d) If the Work includes a "NOTICE" text file as part of its
107 distribution, then any Derivative Works that You distribute must
108 include a readable copy of the attribution notices contained
109 within such NOTICE file, excluding those notices that do not
110 pertain to any part of the Derivative Works, in at least one
111 of the following places: within a NOTICE text file distributed
112 as part of the Derivative Works; within the Source form or
113 documentation, if provided along with the Derivative Works; or,
114 within a display generated by the Derivative Works, if and
115 wherever such third-party notices normally appear. The contents
116 of the NOTICE file are for informational purposes only and
117 do not modify the License. You may add Your own attribution
118 notices within Derivative Works that You distribute, alongside
119 or as an addendum to the NOTICE text from the Work, provided
120 that such additional attribution notices cannot be construed
121 as modifying the License.
122
123 You may add Your own copyright statement to Your modifications and
124 may provide additional or different license terms and conditions
125 for use, reproduction, or distribution of Your modifications, or
126 for any such Derivative Works as a whole, provided Your use,
127 reproduction, and distribution of the Work otherwise complies with
128 the conditions stated in this License.
129
130 5. Submission of Contributions. Unless You explicitly state otherwise,
131 any Contribution intentionally submitted for inclusion in the Work
132 by You to the Licensor shall be under the terms and conditions of
133 this License, without any additional terms or conditions.
134 Notwithstanding the above, nothing herein shall supersede or modify
135 the terms of any separate license agreement you may have executed
136 with Licensor regarding such Contributions.
137
138 6. Trademarks. This License does not grant permission to use the trade
139 names, trademarks, service marks, or product names of the Licensor,
140 except as required for reasonable and customary use in describing the
141 origin of the Work and reproducing the content of the NOTICE file.
142
143 7. Disclaimer of Warranty. Unless required by applicable law or
144 agreed to in writing, Licensor provides the Work (and each
145 Contributor provides its Contributions) on an "AS IS" BASIS,
146 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 implied, including, without limitation, any warranties or conditions
148 of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 PARTICULAR PURPOSE. You are solely responsible for determining the
150 appropriateness of using or redistributing the Work and assume any
151 risks associated with Your exercise of permissions under this License.
152
153 8. Limitation of Liability. In no event and under no legal theory,
154 whether in tort (including negligence), contract, or otherwise,
155 unless required by applicable law (such as deliberate and grossly
156 negligent acts) or agreed to in writing, shall any Contributor be
157 liable to You for damages, including any direct, indirect, special,
158 incidental, or consequential damages of any character arising as a
159 result of this License or out of the use or inability to use the
160 Work (including but not limited to damages for loss of goodwill,
161 work stoppage, computer failure or malfunction, or any and all
162 other commercial damages or losses), even if such Contributor
163 has been advised of the possibility of such damages.
164
165 9. Accepting Warranty or Additional Liability. While redistributing
166 the Work or Derivative Works thereof, You may choose to offer,
167 and charge a fee for, acceptance of support, warranty, indemnity,
168 or other liability obligations and/or rights consistent with this
169 License. However, in accepting such obligations, You may act only
170 on Your own behalf and on Your sole responsibility, not on behalf
171 of any other Contributor, and only if You agree to indemnify,
172 defend, and hold each Contributor harmless for any liability
173 incurred by, or claims asserted against, such Contributor by reason
174 of your accepting any such warranty or additional liability.
175
176 END OF TERMS AND CONDITIONS
177
178 APPENDIX: How to apply the Apache License to your work.
179
180 To apply the Apache License to your work, attach the following
181 boilerplate notice, with the fields enclosed by brackets "[]"
182 replaced with your own identifying information. (Don't include
183 the brackets!) The text should be enclosed in the appropriate
184 comment syntax for the file format. We also recommend that a
185 file or class name and description of purpose be included on the
186 same "printed page" as the copyright notice for easier
187 identification within third-party archives.
188
189 Copyright [yyyy] [name of copyright owner]
190
191 Licensed under the Apache License, Version 2.0 (the "License");
192 you may not use this file except in compliance with the License.
193 You may obtain a copy of the License at
194
195 http://www.apache.org/licenses/LICENSE-2.0
196
197 Unless required by applicable law or agreed to in writing, software
198 distributed under the License is distributed on an "AS IS" BASIS,
199 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 See the License for the specific language governing permissions and
201 limitations under the License.
environment.d.ts
1declare global {
2 namespace NodeJS {
3 interface ProcessEnv {
4 APIFY_TOKEN: string;
5 LANGSMITH_TRACING: string;
6 LANGSMITH_ENDPOINT: string;
7 LANGSMITH_API_KEY: string;
8 LANGSMITH_PROJECT: string;
9 OPENAI_API_KEY: string;
10 ZIP_API_KEY: string;
11 NODE_ENV: 'development' | 'production';
12 }
13 }
14}
15
16// If this file has no import/export statements (i.e. is a script)
17// convert it into a module by adding an empty export statement.
18export {}
package.json
1{
2 "name": "ai-real-state-agent",
3 "version": "0.0.1",
4 "type": "module",
5 "description": "This is an example of a Crawlee project.",
6 "engines": {
7 "node": ">=22.0.0"
8 },
9 "dependencies": {
10 "@langchain/core": "^0.3.42",
11 "@langchain/langgraph": "^0.2.54",
12 "@langchain/openai": "^0.4.4",
13 "apify": "^3.3.2",
14 "dotenv": "^16.4.7",
15 "langchain": "^0.3.19",
16 "zod": "^3.24.2"
17 },
18 "devDependencies": {
19 "@apify/eslint-config-ts": "^0.3.0",
20 "@apify/tsconfig": "^0.1.0",
21 "@eslint/js": "^9.21.0",
22 "@types/node": "^22.0.0",
23 "@typescript-eslint/eslint-plugin": "^7.18.0",
24 "@typescript-eslint/parser": "^7.18.0",
25 "eslint": "^8.57.1",
26 "globals": "^16.0.0",
27 "tsx": "^4.4.0",
28 "typescript": "~5.5.0",
29 "typescript-eslint": "^8.26.0"
30 },
31 "scripts": {
32 "start": "npm run start:dev",
33 "start:prod": "node dist/main.js",
34 "start:dev": "tsx src/main.ts",
35 "build": "tsc",
36 "lint": "eslint src",
37 "test": "echo \"Error: oops, the actor has no tests yet, sad!\" && exit 1"
38 },
39 "author": "It's not you it's me",
40 "license": "ISC"
41}
tsconfig.json
1{
2 "extends": "@apify/tsconfig",
3 "compilerOptions": {
4 "module": "NodeNext",
5 "moduleResolution": "NodeNext",
6 "target": "ES2022",
7 "outDir": "dist",
8 "noUnusedLocals": false,
9 "skipLibCheck": true,
10 "lib": ["DOM"],
11 },
12 "include": [
13 "./*.d.ts",
14 "./src/**/*",
15 ]
16}
.actor/Dockerfile
1# Specify the base Docker image. You can read more about
2# the available images at https://docs.apify.com/sdk/js/docs/guides/docker-images
3# You can also use any other image from Docker Hub.
4FROM apify/actor-node:22 AS builder
5
6# Check preinstalled packages
7RUN npm ls crawlee apify puppeteer playwright
8
9# Copy just package.json and package-lock.json
10# to speed up the build using Docker layer cache.
11COPY package*.json ./
12
13# Install all dependencies. Don't audit to speed up the installation.
14RUN npm install --include=dev --audit=false
15
16# Next, copy the source files using the user set
17# in the base image.
18COPY . ./
19
20# Install all dependencies and build the project.
21# Don't audit to speed up the installation.
22RUN npm run build
23
24# Create final image
25FROM apify/actor-node:22
26
27# Check preinstalled packages
28RUN npm ls crawlee apify puppeteer playwright
29
30# Copy just package.json and package-lock.json
31# to speed up the build using Docker layer cache.
32COPY package*.json ./
33
34# Install NPM packages, skip optional and development dependencies to
35# keep the image small. Avoid logging too much and print the dependency
36# tree for debugging
37RUN npm --quiet set progress=false \
38 && npm install --omit=dev --omit=optional \
39 && echo "Installed NPM packages:" \
40 && (npm list --omit=dev --all || true) \
41 && echo "Node.js version:" \
42 && node --version \
43 && echo "NPM version:" \
44 && npm --version \
45 && rm -r ~/.npm
46
47# Copy built JS files from builder image
48COPY /usr/src/app/dist ./dist
49
50# Next, copy the remaining files and directories with the source code.
51# Since we do this after NPM install, quick build will be really fast
52# for most source file changes.
53COPY . ./
54
55# Create and run as a non-root user.
56RUN adduser -h /home/apify -D apify && \
57 chown -R apify:apify ./
58USER apify
59
60# Run the image.
61CMD npm run start:prod --silent
.actor/actor.json
1{
2 "actorSpecification": 1,
3 "name": "ai-real-state-agent",
4 "version": "0.1",
5 "buildTag": "latest",
6 "title": "AI Real State Agent",
7 "description": "AI agent that uses a multi-agent approach to find you the best home recommendations using a natural language prompt.",
8 "meta": {
9 "templateId": "ts-empty"
10 },
11 "environmentVariables": {
12 "OPENAI_API_KEY": "@defaultOpenaiApiKey",
13 "APIFY_TOKEN": "@defaultApifyToken"
14 },
15 "dockerfile": "./Dockerfile",
16 "input": "./input_schema.json",
17 "storages": {
18 "dataset": "./dataset_schema.json"
19 }
20}
.actor/dataset_schema.json
1{
2 "actorSpecification": 1,
3 "views": {
4 "overview": {
5 "title": "Overview",
6 "transformation": {
7 "fields": ["actorName", "response"]
8 },
9 "display": {
10 "component": "table",
11 "properties": {
12 "actorName": {
13 "label": "Actor name",
14 "format": "text"
15 },
16 "response": {
17 "label": "Actor evaluation",
18 "format": "text"
19 }
20 }
21 }
22 }
23 }
24}
.actor/input_schema.json
1{
2 "title": "Web Automation Agent",
3 "type": "object",
4 "schemaVersion": 1,
5 "properties": {
6 "instructions": {
7 "title": "Instructions for the AI Real State Agent",
8 "type": "string",
9 "description": "Ask the agent for help to find the perfect home.",
10 "editor": "textarea",
11 "prefill": "I want to buy a house with a pool in Miami for less than 1 million dollars. Can you help me?"
12 },
13 "openaiApiKey": {
14 "title": "OpenAI API key",
15 "type": "string",
16 "description": "The API key for accessing OpenAI. You can get it from <a href='https://platform.openai.com/account/api-keys' target='_blank' rel='noopener'>OpenAI platform</a>.",
17 "editor": "textfield",
18 "isSecret": true
19 },
20 "model": {
21 "title": "GPT model",
22 "type": "string",
23 "description": "Select a GPT model. See <a href='https://platform.openai.com/docs/models/overview' target='_blank' rel='noopener'>models overview</a>. Keep in mind that each model has different pricing and features.",
24 "editor": "select",
25 "default": "gpt-4o-mini",
26 "prefill": "gpt-4o-mini",
27 "enum": ["gpt-4o", "gpt-4o-mini", "gpt-3.5-turbo", "o3-mini", "o1-mini"]
28 }
29 },
30 "required": ["instructions", "model"]
31}
.actor/pay_per_event.json
1{
2 "actor-start-gb": {
3 "eventTitle": "Actor start per 1 GB",
4 "eventDescription": "Flat fee for starting an Actor run for each 1 GB of memory.",
5 "eventPriceUsd": 0.01
6 },
7 "openai-1000-tokens-gpt-4o": {
8 "eventTitle": "Price per 1000 OpenAI tokens for gpt-4o",
9 "eventDescription": "Flat fee for every 1000 tokens (input/output) used with gpt-4o.",
10 "eventPriceUsd": 0.01
11 },
12 "openai-1000-tokens-gpt-4o-mini": {
13 "eventTitle": "Price per 1000 OpenAI tokens for gpt-4o-mini",
14 "eventDescription": "Flat fee for every 1000 tokens (input/output) used with gpt-4o-mini.",
15 "eventPriceUsd": 0.0006
16 },
17 "openai-1000-tokens-gpt-3.5-turbo": {
18 "eventTitle": "Price per 1000 OpenAI tokens for gpt-3.5-turbo",
19 "eventDescription": "Flat fee for every 1000 tokens (input/output) used with gpt-3.5-turbo.",
20 "eventPriceUsd": 0.0015
21 },
22 "openai-1000-tokens-gpt-o3-mini": {
23 "eventTitle": "Price per 1000 OpenAI tokens for gpt-o3-mini",
24 "eventDescription": "Flat fee for every 1000 tokens (input/output) used with gpt-o3-mini.",
25 "eventPriceUsd": 0.0044
26 },
27 "openai-1000-tokens-gpt-o1-mini": {
28 "eventTitle": "Price per 1000 OpenAI tokens for gpt-o1-mini",
29 "eventDescription": "Flat fee for every 1000 tokens (input/output) used with gpt-o1-mini.",
30 "eventPriceUsd": 0.0044
31 },
32 "duck-duck-go": {
33 "eventTitle": "Price per Duck Duck Go search",
34 "eventDescription": "Flat fee for every Duck Duck Go search.",
35 "eventPriceUsd": 0.01
36 },
37 "website-scraper':": {
38 "eventTitle": "Price per web page scraped",
39 "eventDescription": "Flat fee for every web page scraped.",
40 "eventPriceUsd": 0.01
41 },
42 "zillow-search':": {
43 "eventTitle": "Price per Zillow search result",
44 "eventDescription": "Flat fee for every result when searching Zillow.",
45 "eventPriceUsd": 0.002
46 },
47 "zip-code-search": {
48 "eventTitle": "Price per Zip Code search",
49 "eventDescription": "Flat fee for every Zip Code search.",
50 "eventPriceUsd": 0.01
51 }
52}
src/main.ts
1import dotenv from 'dotenv';
2import { Actor, ApifyClient, log } from 'apify';
3import { StateGraph, StateGraphArgs, START, END } from '@langchain/langgraph';
4import LocationExpertAgent from './agents/location_expert.js';
5import ResearcherAgent from './agents/researcher.js';
6import { chargeForActorStart } from './utils/ppe_handler.js';
7
8// if available, .env variables are loaded
9dotenv.config();
10
11/**
12 * Actor input schema
13 */
14type Input = {
15 instructions: string;
16 modelName?: string;
17 openaiApiKey?: string;
18 debug?: boolean;
19}
20
21/**
22 * Actor initialization code
23*/
24await Actor.init();
25await chargeForActorStart();
26
27const userToken = Actor.getEnv().token;
28if (!userToken) {
29 throw new Error('User token is required. Use `apify login` and export your secret as APIFY_TOKEN.');
30}
31
32// Handle and validate input
33const {
34 instructions,
35 modelName = 'gpt-4o-mini',
36 openaiApiKey,
37 debug,
38} = await Actor.getInput() as Input;
39if (debug) {
40 log.setLevel(log.LEVELS.DEBUG);
41} else {
42 log.setLevel(log.LEVELS.INFO);
43}
44// if available, the Actor uses the user's openaiApiKey. Otherwise it charges for use.
45const tokenCostActive = (openaiApiKey ?? '').length === 0;
46if (tokenCostActive) {
47 log.info("No openaiApiKey was detected. You'll be charged for token usage.");
48} else {
49 log.info("Env openaiApiKey detected. You won't be charged for token usage.");
50}
51if (!instructions) {
52 throw new Error('Instructions are required. Create an INPUT.json file in the `storage/key_value_stores/default` folder and add the respective keys.');
53}
54
55// Apify is used to call tools and manage datasets
56const apifyClient = new ApifyClient({
57 token: userToken,
58});
59
60/**
61 * LangGraph StateGraph schema
62 */
63type StateSchema = {
64 instructions: string;
65 bestLocations: string;
66 recommendations: string[];
67 output: string;
68}
69
70const graphState: StateGraphArgs<StateSchema>['channels'] = {
71 instructions: {
72 value: (x?: string, y?: string) => y ?? x ?? '',
73 default: () => instructions,
74 },
75 bestLocations: {
76 value: (x?: string, y?: string) => y ?? x ?? '',
77 default: () => '',
78 },
79 recommendations: {
80 value: (x?: string[], y?: string[]) => y ?? x ?? [],
81 default: () => [],
82 },
83 output: {
84 value: (x?: string, y?: string) => y ?? x ?? '',
85 default: () => '',
86 },
87};
88
89async function locationExpert(state: StateSchema) {
90 // The researcher agent gets initialized
91 const locationExpertAgent = new LocationExpertAgent({
92 apifyClient,
93 modelName,
94 openaiApiKey: openaiApiKey ?? process.env.OPENAI_API_KEY,
95 log,
96 });
97 const { agentExecutor, costHandler } = locationExpertAgent;
98 const response = await agentExecutor.invoke({ input: state.instructions });
99 log.debug(`locationExpert 🤖 : ${response.output}`);
100 await costHandler.logOrChargeForTokens(modelName, tokenCostActive);
101 return { bestLocations: response.output };
102}
103
104async function researcher(state: StateSchema) {
105 // The researcher agent gets initialized
106 const researcherAgent = new ResearcherAgent({
107 apifyClient,
108 modelName,
109 openaiApiKey: openaiApiKey ?? process.env.OPENAI_API_KEY,
110 log,
111 });
112 const { agentExecutor, costHandler } = researcherAgent;
113 const input = 'The user asked sent this exact query:\n\n'
114 + `'${state.instructions}'\n\n`
115 + 'You asked someone for help to get the best locations in that city and state. '
116 + 'The answer you received was this:\n\n'
117 + `'${state.bestLocations}'\n\n`
118 + 'Please answer the user accordingly.';
119 const response = await agentExecutor.invoke({ input });
120 await costHandler.logOrChargeForTokens(modelName, tokenCostActive);
121 return { output: response.output };
122}
123
124const graph = new StateGraph({ channels: graphState })
125 .addNode('location_expert', locationExpert)
126 .addNode('researcher', researcher)
127 .addEdge(START, 'location_expert')
128 .addEdge('location_expert', 'researcher')
129 .addEdge('researcher', END);
130
131const runnable = graph.compile();
132const response = await runnable.invoke(
133 { input: instructions },
134 { configurable: { thread_id: 42 } }, // this line shows that the agent can be thread-aware
135);
136
137log.debug(`Agent 🤖 : ${response.output}`);
138
139await Actor.pushData({
140 actorName: 'AI Real State Agent',
141 response: response.output,
142});
143
144await Actor.exit();
src/agents/location_expert.ts
1import { Log, ApifyClient } from 'apify';
2import { ChatPromptTemplate } from '@langchain/core/prompts';
3import { createToolCallingAgent, AgentExecutor } from 'langchain/agents';
4import { ChatOpenAI } from '@langchain/openai';
5import { StructuredToolInterface } from '@langchain/core/tools';
6import DuckDuckGo from '../tools/duck_duck_go.js';
7import WebsiteScraper from '../tools/website_scraper.js';
8// import ZipCodeSearch from '../tools/zip_code_search.js';
9import { CostHandler } from '../utils/cost_handler.js';
10
11/**
12 * Interface for parameters required by LocationExpertAgent class.
13 */
14export interface LocationExpertAgentParams {
15 apifyClient: ApifyClient,
16 modelName: string,
17 openaiApiKey: string,
18 log: Log | Console;
19}
20
21/**
22 * Tool that uses the MagicTool function. This is an example function to use as template.
23 */
24export class LocationExpertAgent {
25 protected log: Log | Console;
26 protected apifyClient: ApifyClient;
27 public agentExecutor: AgentExecutor;
28 public costHandler: CostHandler;
29
30 constructor(fields?: LocationExpertAgentParams) {
31 this.log = fields?.log ?? console;
32 this.apifyClient = fields?.apifyClient ?? new ApifyClient();
33 this.costHandler = new CostHandler(fields?.modelName ?? 'gpt-4o-mini', this.log);
34 const llm = new ChatOpenAI({
35 model: fields?.modelName,
36 apiKey: fields?.openaiApiKey,
37 temperature: 0,
38 callbacks: [
39 this.costHandler,
40 ],
41 });
42 const tools = this.buildTools(this.apifyClient, this.log);
43 const prompt = this.buildPrompt();
44 const agent = createToolCallingAgent({
45 llm,
46 tools,
47 prompt,
48 });
49 this.agentExecutor = new AgentExecutor({
50 agent,
51 tools,
52 verbose: false,
53 maxIterations: 5,
54 });
55 }
56
57 protected buildTools(
58 apifyClient: ApifyClient, log: Log | Console
59 ): StructuredToolInterface[] {
60 // Tools are initialized to be passed to the agent
61 const duckDuckGo = new DuckDuckGo({ apifyClient, log });
62 const websiteScraper = new WebsiteScraper({ apifyClient, log });
63 // const zipCodeSearch = new ZipCodeSearch({ log });
64 return [
65 duckDuckGo,
66 websiteScraper,
67 // zipCodeSearch,
68 ];
69 }
70
71 protected buildPrompt(): ChatPromptTemplate {
72 return ChatPromptTemplate.fromMessages([
73 ['system',
74 'You are a experienced real state agent that wants to help the user to find the perfect home. '
75 + "You will stick to the following steps, but notify the user if you get stuck or can't continue. "
76 + 'Step 1. The user will ask you for advice regarding a specific city in the US. '
77 + 'If the user does not provide a state (like CA or NY), try to guess to which state a city belongs to. '
78 + 'If the user does not provide a state, try to guess to which state a city belongs to. '
79 + 'If from the input you cannot get a city and a state or you think that the city is not in US territory, '
80 + 'end the conversation and help the user with the input. '
81 + "Make sure to convert the state to a two-letter ISO standard. For example, if the user says 'New York', store it as 'NY' before using it. \n"
82 // 2. Fetch best Zip Codes to live using DuckDuckGo
83 + 'Step 2. With the city and state in hand, use DuckDuckGo replacing the following query: '
84 + "'best places to live near [city], [state] by zip code site:niche.com'. "
85 + 'If there the results, use a website scraper on the URLs you think will show you this information. '
86 + 'Iterate until you find the best 3 Zip Codes near the selected city. '
87 + "For best performance when using the website scraper, you can use method='getBestZipCodesToLive' and output=null'. "
88 + 'Instead of answering the original question, just return the top 3 Zip Codes and explain to the user why you selected those Zip Codes. \n'
89 ],
90 ['placeholder', '{chat_history}'],
91 ['human', '{input}'],
92 ['placeholder', '{agent_scratchpad}'],
93 ]);
94 }
95}
96
97export default LocationExpertAgent;
src/agents/researcher.ts
1import { Log, ApifyClient } from 'apify';
2import { ChatPromptTemplate } from '@langchain/core/prompts';
3import { createToolCallingAgent, AgentExecutor } from 'langchain/agents';
4import { ChatOpenAI } from '@langchain/openai';
5import { StructuredToolInterface } from '@langchain/core/tools';
6import ZillowSearch from '../tools/zillow_search.js';
7import { CostHandler } from '../utils/cost_handler.js';
8
9/**
10 * Interface for parameters required by ResearcherAgent class.
11 */
12export interface ResearcherAgentParams {
13 apifyClient: ApifyClient,
14 modelName: string,
15 openaiApiKey: string,
16 log: Log | Console;
17}
18
19/**
20 * Tool that uses the MagicTool function. This is an example function to use as template.
21 */
22export class ResearcherAgent {
23 protected log: Log | Console;
24 protected apifyClient: ApifyClient;
25 public agentExecutor: AgentExecutor;
26 public costHandler: CostHandler;
27
28 constructor(fields?: ResearcherAgentParams) {
29 this.log = fields?.log ?? console;
30 this.apifyClient = fields?.apifyClient ?? new ApifyClient();
31 this.costHandler = new CostHandler(fields?.modelName ?? 'gpt-4o-mini', this.log);
32 const llm = new ChatOpenAI({
33 model: fields?.modelName,
34 apiKey: fields?.openaiApiKey,
35 temperature: 0,
36 callbacks: [
37 this.costHandler,
38 ],
39 });
40 const tools = this.buildTools(this.apifyClient, this.log);
41 const prompt = this.buildPrompt();
42 const agent = createToolCallingAgent({
43 llm,
44 tools,
45 prompt,
46 });
47 this.agentExecutor = new AgentExecutor({
48 agent,
49 tools,
50 verbose: false,
51 maxIterations: 5,
52 });
53 }
54
55 protected buildTools(
56 apifyClient: ApifyClient, log: Log | Console
57 ): StructuredToolInterface[] {
58 // Tools are initialized to be passed to the agent
59 const zillowSearch = new ZillowSearch({ apifyClient, log });
60 return [
61 zillowSearch,
62 ];
63 }
64
65 protected buildPrompt(): ChatPromptTemplate {
66 return ChatPromptTemplate.fromMessages([
67 ['system',
68 'You are a experienced real state agent that wants to help the user to find the perfect home. '
69 + "You will stick to the following steps, but notify the user if you get stuck or can't continue. "
70 + 'Step 1. Using the selected Zip Codes, search on Zillow for properties that match the user requirements. '
71 // + "Remember: Don't perform a Zillow Search until you find a good ranking (every search costs money and you want to save). "
72 + 'The user must specify if he or she is looking to rent or buy a property (default to rent if the information is not given). '
73 + 'The user can specify if the ideal property has a minimum value (default to 1 if the information is not given). '
74 + 'The user can specify if the ideal property has a maximum value (default to 1000 if the information is not given). '
75 + 'Inform the user of the assumptions you make before delivering any results. \n'
76 + 'Step 2. Based on the results, use your expertise to recommend the best 5 properties that you found. '
77 + 'The user may have specified other requests like pets, pool, beds, baths, sqft, gym, etc. '
78 + 'Filter the results based on this information or notify the user if you are unable to do so. '
79 + 'Make sure that you show the address, price and a link to view more information about the chosen properties. '
80 + 'At the end, please explain why you chose those properties. '
81 ],
82 ['placeholder', '{chat_history}'],
83 ['human', '{input}'],
84 ['placeholder', '{agent_scratchpad}'],
85 ]);
86 }
87}
88
89export default ResearcherAgent;
src/tools/duck_duck_go.ts
1import { Log, ApifyClient } from 'apify';
2import { StructuredTool } from '@langchain/core/tools';
3import { z } from 'zod';
4import { chargeForToolUsage } from '../utils/ppe_handler.js';
5
6/**
7 * Interface for parameters required by DuckDuckGo class.
8 */
9export interface DuckDuckGoParams {
10 apifyClient: ApifyClient;
11 log: Log | Console;
12}
13
14/**
15 * Tool that uses the DuckDuckGo function
16 */
17export class DuckDuckGo extends StructuredTool {
18 protected log: Log | Console;
19 protected apifyClient: ApifyClient;
20
21 name = 'duck_duck_go';
22
23 description = 'Performs a search on the search engine DuckDuckGo and returns a stringified JSON with the results.';
24
25 schema = z.object({
26 keywords: z.string(),
27 locale: z.enum(['us-en', 'uk-en', 'cz-cs', 'cl-es']) || undefined,
28 maximum: z.number() || undefined,
29 });
30
31 constructor(fields?: DuckDuckGoParams) {
32 super(...arguments);
33 this.log = fields?.log ?? console;
34 this.apifyClient = fields?.apifyClient ?? new ApifyClient();
35 }
36
37 override async _call(arg: z.output<typeof this.schema>) {
38 const actorInput = {
39 keywords: arg.keywords,
40 proxy: {
41 useApifyProxy: true,
42 apifyProxyGroups: [
43 'RESIDENTIAL'
44 ],
45 apifyProxyCountry: 'US'
46 },
47 locale: arg.locale ?? 'us-en',
48 operation: 'st',
49 safe: 'Partial',
50 daterange: 'all',
51 img_type: 'all',
52 img_size: 'all',
53 vid_duration: 'all',
54 maximum: arg.maximum ?? 5,
55 timeout: 30
56 };
57 this.log.debug(
58 `Calling DuckDuckGo with input: ${JSON.stringify(actorInput)}`
59 );
60 const actorRun = await this.apifyClient
61 .actor('canadesk/duckduckgo-serp-api')
62 .call(actorInput);
63 const dataset = await this.apifyClient
64 .dataset(actorRun.defaultDatasetId)
65 .listItems();
66 const { items } = dataset;
67 this.log.debug(`DuckDuckGo response: ${JSON.stringify(items)}`);
68 await chargeForToolUsage(this.name, 1);
69 return JSON.stringify(items);
70 }
71}
72
73export default DuckDuckGo;
src/tools/magictool.ts
1import { Log } from 'apify';
2import { Tool } from '@langchain/core/tools';
3
4/**
5 * Interface for parameters required by MagicTool class.
6 */
7export interface MagicToolParams {
8 apiKey?: string;
9 log: Log | Console;
10}
11
12/**
13 * Tool that uses the MagicTool function. This is an example function to use as template.
14 */
15export class MagicTool extends Tool {
16 static override lc_name() {
17 return 'MagicTool';
18 }
19
20 protected log: Log | Console;
21 protected apiKey: string;
22
23 name = 'magic_function';
24
25 description = 'Applies a magic function to an input.';
26
27 constructor(fields?: MagicToolParams) {
28 super(...arguments);
29 this.log = fields?.log ?? console;
30 const apiKey = fields?.apiKey ?? process.env.SECRET_API_KEY ?? '';
31 if (apiKey === undefined) {
32 this.log.debug(
33 "Secret API key not set. You can set it as 'SECRET_API_KEY' in your environment variables."
34 );
35 }
36 this.apiKey = apiKey;
37 }
38
39 async _call(rawInput: string) {
40 this.log.debug(`rawInput: ${rawInput}`);
41 const number = parseInt(rawInput, 10);
42 return `${number + 2}`;
43 }
44}
45
46export default MagicTool;
src/tools/website_scraper.ts
1import { Log, ApifyClient } from 'apify';
2import { StructuredTool } from '@langchain/core/tools';
3import { z } from 'zod';
4import { chargeForToolUsage } from '../utils/ppe_handler.js';
5
6/**
7 * Interface for parameters required by WebsiteScraper class.
8 */
9export interface WebsiteScraperParams {
10 apifyClient: ApifyClient;
11 log: Log | Console;
12}
13
14/**
15 * An example input that serves as a good default
16 */
17const sampleInput = {
18 method: 'getAllItems',
19 output: '{"results":[""]}',
20};
21
22/**
23 * Tool that uses the WebsiteScraper function
24 */
25export class WebsiteScraper extends StructuredTool {
26 protected log: Log | Console;
27 protected apifyClient: ApifyClient;
28
29 name = 'website_scraper';
30
31 description = 'Scrapes a URL aiming the search based on a method (for example: getAllItems) and returns a stringified JSON with the results using the specified output format (for example: {"results":[""]}).';
32
33 schema = z.object({
34 url: z.string(),
35 method: z.string() || undefined,
36 // output: z.string() || undefined || null,
37 });
38
39 constructor(fields?: WebsiteScraperParams) {
40 super(...arguments);
41 this.log = fields?.log ?? console;
42 this.apifyClient = fields?.apifyClient ?? new ApifyClient();
43 }
44
45 override async _call(arg: z.output<typeof this.schema>) {
46 const actorInput = {
47 url: arg.url,
48 method: arg.method ?? sampleInput.method,
49 output: sampleInput.output,
50 };
51 const callOptions = {
52 timeout: 60,
53 };
54 this.log.debug(
55 `Calling WebsiteScraper with input: ${JSON.stringify(actorInput)}`
56 );
57 const actorRun = await this.apifyClient
58 .actor('zeeb0t/web-scraping-api---scrape-any-website')
59 .call(actorInput, callOptions);
60 const dataset = await this.apifyClient
61 .dataset(actorRun.defaultDatasetId)
62 .listItems();
63 const { items } = dataset;
64 this.log.debug(`WebsiteScraper response: ${JSON.stringify(items)}`);
65 await chargeForToolUsage(this.name, 1);
66 return JSON.stringify(items);
67 }
68}
69
70export default WebsiteScraper;
src/tools/zillow_search.ts
1import { Log, ApifyClient } from 'apify';
2import { StructuredTool } from '@langchain/core/tools';
3import { z } from 'zod';
4import { chargeForToolUsage } from '../utils/ppe_handler.js';
5
6/**
7 * Interface for parameters required by ZillowSearch class.
8 */
9export interface ZillowSearchParams {
10 apifyClient: ApifyClient;
11 log: Log | Console;
12}
13
14/**
15 * Tool that uses the ZillowSearch function
16 */
17export class ZillowSearch extends StructuredTool {
18 protected log: Log | Console;
19 protected apifyClient: ApifyClient;
20
21 name = 'zillow_search';
22
23 description = 'Searches for properties on Zillow based on a list of Zip Codes (at least one) and returns a stringified JSON with the results.';
24
25 schema = z.object({
26 zipCodes: z.string().array(),
27 minimumPrice: z.number(),
28 maximumPrice: z.number(),
29 forRent: z.boolean(),
30 });
31
32 constructor(fields?: ZillowSearchParams) {
33 super(...arguments);
34 this.log = fields?.log ?? console;
35 this.apifyClient = fields?.apifyClient ?? new ApifyClient();
36 }
37
38 override async _call(arg: z.output<typeof this.schema>) {
39 const actorInput = {
40 forRent: arg.forRent,
41 forSaleByAgent: true,
42 forSaleByOwner: true,
43 priceMax: arg.maximumPrice,
44 priceMin: arg.minimumPrice,
45 sold: false,
46 zipCodes: arg.zipCodes,
47 };
48 this.log.debug(
49 `Calling ZillowSearch with input: ${JSON.stringify(actorInput)}`
50 );
51 const actorRun = await this.apifyClient
52 .actor('maxcopell/zillow-zip-search')
53 .call(actorInput);
54 const dataset = await this.apifyClient
55 .dataset(actorRun.defaultDatasetId)
56 .listItems();
57 await chargeForToolUsage(this.name, dataset.total);
58 // returns only the top 10 properties to avoid sending too much data
59 // NOTE: this tool could return the dataset-id and use another tool to read it
60 const cappedItems = dataset.items.slice(0, 10);
61 this.log.debug(`ZillowSearch response: ${JSON.stringify(cappedItems)}`);
62 return JSON.stringify(cappedItems);
63 }
64}
65
66export default ZillowSearch;
src/tools/zip_code_search.ts
1import { Log } from 'apify';
2import { StructuredTool } from '@langchain/core/tools';
3import { z } from 'zod';
4import { chargeForToolUsage } from '../utils/ppe_handler.js';
5
6/**
7 * Interface for parameters required by ZipCodeSearch class.
8 */
9export interface ZipCodeSearchParams {
10 apiKey?: string;
11 log: Log | Console;
12}
13
14/**
15 * Tool that uses the ZipCodeSearch function
16 */
17export class ZipCodeSearch extends StructuredTool {
18 protected log: Log | Console;
19 protected apiKey: string;
20
21 name = 'zip_code_search';
22
23 description = 'Returns a list of Zip Codes for a city and the state it belongs to.';
24
25 schema = z.object({
26 city: z.string(),
27 state: z.string(),
28 });
29
30 constructor(fields?: ZipCodeSearchParams) {
31 super(...arguments);
32 this.log = fields?.log ?? console;
33 const apiKey = fields?.apiKey ?? process.env.ZIP_API_KEY ?? '';
34 if (apiKey === undefined) {
35 this.log.debug(
36 "Secret API key not set. You can set it as 'ZIP_API_KEY' in your environment variables."
37 );
38 }
39 this.apiKey = apiKey;
40 }
41
42 protected buildUrl = (city: string, state: string): string => {
43 const baseUrl = `https://www.zipcodeapi.com/rest/${this.apiKey}/city-zips.json`;
44 return `${baseUrl}/${city}/${state}`;
45 };
46
47 override async _call(arg: z.output<typeof this.schema>) {
48 const serviceUrl = this.buildUrl(arg.city, arg.state);
49 this.log.debug(
50 `Calling ZipCodeSearch with city='${arg.city}' and state='${arg.state}'`
51 );
52 const resp = await fetch(serviceUrl);
53 const json = await resp.json();
54 this.log.debug(`ZipCodeSearch response: ${JSON.stringify(json)}`);
55 await chargeForToolUsage(this.name, 1);
56 const zipCodes = (json.zip_codes || []).join(', ');
57 return zipCodes;
58 }
59}
60
61export default ZipCodeSearch;
src/utils/cost_handler.ts
1import { Log } from 'apify';
2import { BaseTracer } from 'langchain/callbacks';
3import { Run } from '@langchain/core/tracers/tracer_langchain';
4import { GPT_MODEL_LIST, OpenaiAPICost } from './openai_models.js';
5import { chargeForModelTokens } from './ppe_handler.js';
6
7interface TotalCost {
8 usd: number;
9 inputTokens: number;
10 outputTokens: number;
11 totalModelCalls: number;
12}
13
14export class CostHandler extends BaseTracer {
15 protected log: Log | Console;
16 name: string;
17 modelName: string;
18 modelCost: OpenaiAPICost;
19 totalCost: TotalCost;
20
21 constructor(modelName: string, log?: Log | Console) {
22 super();
23 this.log = log ?? console;
24 this.name = 'cost_handler';
25 this.modelName = modelName;
26 this.modelCost = GPT_MODEL_LIST[this.modelName].cost;
27 this.totalCost = {
28 usd: 0,
29 inputTokens: 0,
30 outputTokens: 0,
31 totalModelCalls: 0,
32 };
33 }
34
35 // NOTE: We do not need to persist runs in this handler.
36 // eslint-disable-next-line @typescript-eslint/no-unused-vars
37 persistRun(_run: Run) {
38 return Promise.resolve();
39 }
40
41 /**
42 * Logs tokens usage in $.
43 * @returns void
44 */
45 override onLLMEnd(run: Run) {
46 const tokenUsage = run?.outputs?.llmOutput?.tokenUsage;
47 if (tokenUsage) {
48 const inputCostsUSD = this.modelCost.input
49 * (tokenUsage.promptTokens / 1000);
50 const outputCostsUSD = this.modelCost.output
51 * (tokenUsage.completionTokens / 1000);
52 const callCostUSD = inputCostsUSD + outputCostsUSD;
53 this.totalCost.usd += inputCostsUSD + outputCostsUSD;
54 this.totalCost.inputTokens += tokenUsage.promptTokens;
55 this.totalCost.outputTokens += tokenUsage.completionTokens;
56 this.totalCost.totalModelCalls++;
57 const durationSecs = run.end_time && run.start_time
58 && (run.end_time - run.start_time) / 1000;
59 this.log.debug(`LLM model call processed`,
60 {
61 durationSecs,
62 callCostUSD,
63 totalCostUSD: this.totalCost.usd,
64 inputTokens: this.totalCost.inputTokens,
65 outputTokens: this.totalCost.outputTokens,
66 }
67 );
68 }
69 }
70
71 override onLLMStart(run: Run) {
72 this.log.debug(`Calling LLM model`, run);
73 }
74
75 getTotalCost() {
76 return this.totalCost;
77 }
78
79 async logOrChargeForTokens(modelName: string, tokenCostActive: boolean) {
80 const costs = this.totalCost;
81 if (tokenCostActive) {
82 const tokens = costs.inputTokens + costs.outputTokens;
83 const tokensCost = this.modelCost.output * (tokens / 1000);
84 this.log.info(`Total tokens processed: ${tokens}. Usage cost: ${tokensCost}`);
85 await chargeForModelTokens(modelName, tokens);
86 } else {
87 this.log.info(`Estimated OpenAI cost: $${costs.usd} USD`);
88 }
89 }
90}
src/utils/openai_models.ts
1export interface OpenaiAPICost {
2 input: number; // USD cost per 1000 tokens
3 output: number; // USD cost per 1000 tokens
4}
5
6export interface GPTModelConfig {
7 model: string;
8 maxTokens: number;
9 maxOutputTokens?: number;
10 interface: 'text' | 'chat';
11 cost: OpenaiAPICost; // USD cost per 1000 tokens
12}
13
14/**
15* List of GPT models that can be used.
16* Should be in sync with https://platform.openai.com/docs/models/
17* Last updated on 2025-03-09
18*/
19export const GPT_MODEL_LIST: {[key: string]: GPTModelConfig} = {
20 'gpt-4o': {
21 model: 'gpt-4o',
22 maxTokens: 16384,
23 interface: 'chat',
24 cost: {
25 input: 0.0025,
26 output: 0.01,
27 },
28 },
29 'gpt-4o-mini': {
30 model: 'gpt-4o-mini',
31 maxTokens: 16384,
32 interface: 'chat',
33 cost: {
34 input: 0.00015,
35 output: 0.0006,
36 },
37 },
38 'gpt-3.5-turbo': {
39 model: 'gpt-3.5-turbo',
40 maxTokens: 8192,
41 interface: 'chat',
42 cost: {
43 input: 0.0005,
44 output: 0.0015,
45 },
46 },
47 'o3-mini': {
48 model: 'o3-mini',
49 maxTokens: 4096,
50 interface: 'chat',
51 cost: {
52 input: 0.0011,
53 output: 0.0044,
54 },
55 },
56 'o1-mini': {
57 model: 'o1-mini',
58 maxTokens: 2048,
59 interface: 'chat',
60 cost: {
61 input: 0.0011,
62 output: 0.0044,
63 },
64 },
65};
src/utils/ppe_events.ts
1export const PPE_EVENT = {
2 ACTOR_START_GB: 'actor-start-gb',
3 GPT_4O: 'openai-1000-tokens-gpt-4o',
4 GPT_4O_MINI: 'openai-1000-tokens-gpt-4o-mini',
5 GPT_3_5_TURBO: 'openai-1000-tokens-gpt-3.5-turbo',
6 GPT_O3_MINI: 'openai-1000-tokens-gpt-o3-mini',
7 GPT_O1_MINI: 'openai-1000-tokens-gpt-o1-mini',
8 DUCK_DUCK_GO: 'duck-duck-go-search',
9 WEBSITE_SCRAPER: 'site-scraped',
10 ZILLOW_SEARCH: 'zillow-results',
11 ZIP_CODE_SEARCH: 'zip-code-search',
12} as const;
src/utils/ppe_handler.ts
1import { Actor, log } from 'apify';
2import { PPE_EVENT } from './ppe_events.js';
3
4/**
5 * Charges for the tokens used by a specific model.
6 *
7 * @param modelName - The name of the model.
8 * @param tokens - The number of tokens to charge for.
9 * @throws Will throw an error if the model name is unknown.
10 */
11export async function chargeForModelTokens(modelName: string, tokens: number) {
12 const tokensK = Math.ceil(tokens / 1000);
13 log.debug(`Charging for ${tokens} tokens (${tokensK}k) for model ${modelName}`);
14 let eventName: string = PPE_EVENT.GPT_4O;
15 switch (modelName) {
16 case 'gpt-4o-mini':
17 eventName = PPE_EVENT.GPT_4O_MINI;
18 break;
19 case 'gpt-3.5-turbo':
20 eventName = PPE_EVENT.GPT_3_5_TURBO;
21 break;
22 case 'gpt-o3-mini':
23 eventName = PPE_EVENT.GPT_O3_MINI;
24 break;
25 case 'gpt-o1-mini':
26 eventName = PPE_EVENT.GPT_O1_MINI;
27 break;
28 default:
29 eventName = PPE_EVENT.GPT_4O;
30 break;
31 }
32 await Actor.charge(
33 { eventName, count: tokensK }
34 );
35}
36
37export async function chargeForActorStart() {
38 if (
39 Actor.getChargingManager()
40 .getChargedEventCount(PPE_EVENT.ACTOR_START_GB) === 0
41 ) {
42 const count = Math.ceil((Actor.getEnv().memoryMbytes || 1024) / 1024);
43 await Actor.charge({ eventName: PPE_EVENT.ACTOR_START_GB, count });
44 }
45}
46
47export async function chargeForToolUsage(toolName: string, count: number) {
48 log.debug(`Charging #${count} times for tool ${toolName}`);
49 let eventName: string = '';
50 switch (toolName) {
51 case 'duck_duck_go':
52 eventName = PPE_EVENT.DUCK_DUCK_GO;
53 break;
54 case 'website_scraper':
55 eventName = PPE_EVENT.WEBSITE_SCRAPER;
56 break;
57 case 'zillow_search':
58 eventName = PPE_EVENT.ZILLOW_SEARCH;
59 break;
60 case 'zip_code_search':
61 eventName = PPE_EVENT.ZIP_CODE_SEARCH;
62 break;
63 default:
64 eventName = '';
65 break;
66 }
67 await Actor.charge({ eventName, count });
68}
Pricing
Pricing model
Pay per eventThis Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Actor start per 1 GB
$0.010
Flat fee for starting an Actor run for each 1 GB of memory.
Price per 1000 OpenAI tokens for gpt-4o
$0.010
Flat fee for every 1000 tokens (input/output) used with gpt-4o.
Price per 1000 OpenAI tokens for gpt-4o-mini
$0.001
Flat fee for every 1000 tokens (input/output) used with gpt-4o-mini.
Price per 1000 OpenAI tokens for gpt-3.5-turbo
$0.002
Flat fee for every 1000 tokens (input/output) used with gpt-3.5-turbo.
Price per 1000 OpenAI tokens for gpt-o3-mini
$0.004
Flat fee for every 1000 tokens (input/output) used with gpt-o3-mini.
Price per 1000 OpenAI tokens for gpt-o1-mini
$0.004
Flat fee for every 1000 tokens (input/output) used with gpt-o1-mini.
Price per Duck Duck Go search
$0.010
Flat fee for every Duck Duck Go search.
Price per web page scraped
$0.010
Flat fee for every web page scraped.
Price per Zillow search result
$0.002
Flat fee for every result when searching Zillow.
Price per Zip Code search
$0.010
Flat fee for every Zip Code search.