This documentation explains how to integrate Reset The Future's financial intelligence APIs with AI agents, enabling them to provide sophisticated financial insights and services.
Reset The Future APIs provide a comprehensive suite of financial intelligence capabilities designed specifically for AI agents, including:
Our APIs are optimized for integration with leading AI platforms, including OpenAI (GPT-4), Anthropic Claude, and Google Gemini.
To access our APIs, you'll need an API key:
Our API is documented using the OpenAPI specification. You can access the schema in the following ways:
https://resetthefuture-main-6c663d7.zuplo.app/openapi.json
This schema includes agent-specific extensions that help AI agents understand when and how to use our APIs.
import openai
import requests
import json
# Fetch the OpenAPI schema
schema_url = "https://resetthefuture-main-6c663d7.zuplo.app/openapi.json"
api_schema = requests.get(schema_url).json()
# Convert OpenAPI schema to OpenAI function format
def convert_paths_to_functions(schema):
functions = []
for path, methods in schema["paths"].items():
for method, details in methods.items():
if method.lower() == "post": # Focusing on POST endpoints
function_name = details.get("operationId", path.replace("/", "_"))
# Get parameters from schema
parameters = {}
if "requestBody" in details and "content" in details["requestBody"]:
content = details["requestBody"]["content"]
if "application/json" in content and "schema" in content["application/json"]:
schema_ref = content["application/json"]["schema"]
if "$ref" in schema_ref:
ref_path = schema_ref["$ref"].split("/")
ref_name = ref_path[-1]
if ref_name in schema["components"]["schemas"]:
properties = schema["components"]["schemas"][ref_name]["properties"]
for prop, prop_details in properties.items():
parameters[prop] = {
"type": prop_details.get("type", "string"),
"description": prop_details.get("description", "")
}
elif "properties" in schema_ref:
for prop, prop_details in schema_ref["properties"].items():
parameters[prop] = {
"type": prop_details.get("type", "string"),
"description": prop_details.get("description", "")
}
functions.append({
"name": function_name,
"description": details.get("x-function-description", details.get("description", "")),
"parameters": {
"type": "object",
"properties": parameters,
"required": details.get("requestBody", {}).get("required", [])
}
})
return functions
# Convert the OpenAPI schema to OpenAI function format
functions = convert_paths_to_functions(api_schema)
# Use with OpenAI
client = openai.OpenAI(api_key="your-openai-api-key")
# Example user query
user_query = "Can you analyze if my client with a satisfaction score of 2 is likely to churn?"
# Call OpenAI with the functions
response = client.chat.completions.create(
model="gpt-4-turbo",
messages=[{"role": "user", "content": user_query}],
functions=functions,
function_call="auto"
)
# Process the response
assistant_message = response.choices[0].message
if assistant_message.function_call:
# Extract function call details
function_name = assistant_message.function_call.name
function_args = json.loads(assistant_message.function_call.arguments)
# Call Reset The Future API
api_endpoint = next((p for p, m in api_schema["paths"].items()
if any(d.get("operationId") == function_name
for _, d in m.items())), None)
if api_endpoint:
print(f"Calling API endpoint: {api_endpoint}")
# Make the actual API call
api_response = requests.post(
f"https://resetthefuture-main-6c663d7.zuplo.app{api_endpoint}",
headers={
"Content-Type": "application/json",
"X-API-Key": "your-reset-the-future-api-key"
},
json=function_args
)
# Return API response to OpenAI for interpretation
final_response = client.chat.completions.create(
model="gpt-4-turbo",
messages=[
{"role": "user", "content": user_query},
assistant_message,
{
"role": "function",
"name": function_name,
"content": json.dumps(api_response.json())
}
]
)
print("AI Agent Response:")
print(final_response.choices[0].message.content)
import anthropic
import requests
import json
# Fetch the OpenAPI schema
schema_url = "https://resetthefuture-main-6c663d7.zuplo.app/openapi.json"
api_schema = requests.get(schema_url).json()
# Prepare the schema for Claude's tool use
tools = [
{
"name": "reset_the_future_api",
"description": "Financial intelligence APIs for wealth management",
"input_schema": {
"type": "object",
"properties": {
"endpoint": {
"type": "string",
"enum": [path for path in api_schema["paths"].keys()],
"description": "The API endpoint to call"
},
"parameters": {
"type": "object",
"description": "The parameters for the API call"
}
},
"required": ["endpoint", "parameters"]
}
}
]
# Initialize the Claude client
client = anthropic.Anthropic(api_key="your-anthropic-api-key")
# Example user query
user_query = "Can you predict if my client with a satisfaction score of 2 is likely to churn?"
# Call Claude with the tools
message = client.messages.create(
model="claude-3-opus-20240229",
max_tokens=1024,
messages=[{"role": "user", "content": user_query}],
tools=tools,
system=f"You are a financial advisor assistant. You have access to Reset The Future's financial APIs. Use them when needed to provide accurate financial insights. Here's information about the available endpoints: {json.dumps([{'path': path, 'description': methods.get('post', {}).get('description', '')} for path, methods in api_schema['paths'].items()])}"
)
# Process the response
if message.content[0].type == "tool_use":
tool_use = message.content[0].tool_use
if tool_use.name == "reset_the_future_api":
tool_params = json.loads(tool_use.input)
endpoint = tool_params["endpoint"]
parameters = tool_params["parameters"]
# Make the actual API call
api_response = requests.post(
f"https://resetthefuture-main-6c663d7.zuplo.app{endpoint}",
headers={
"Content-Type": "application/json",
"X-API-Key": "your-reset-the-future-api-key"
},
json=parameters
)
# Return API response to Claude for interpretation
tool_response = {"response": api_response.json()}
final_message = client.messages.create(
model="claude-3-opus-20240229",
max_tokens=1024,
messages=[
{"role": "user", "content": user_query},
{"role": "assistant", "content": [
{"type": "tool_use", "tool_use": tool_use}
]},
{"role": "user", "content": [
{"type": "tool_result", "tool_result": {
"tool_use_id": tool_use.id,
"content": json.dumps(tool_response)
}}
]}
]
)
print("AI Agent Response:")
print(final_message.content[0].text)
import google.generativeai as genai
import requests
import json
# Fetch the OpenAPI schema
schema_url = "https://resetthefuture-main-6c663d7.zuplo.app/openapi.json"
api_schema = requests.get(schema_url).json()
# Configure the Gemini API client
genai.configure(api_key="your-gemini-api-key")
# Convert OpenAPI schema to Gemini function format
def prepare_gemini_tools(schema):
tools = []
for path, methods in schema["paths"].items():
for method, details in methods.items():
if method.lower() == "post": # Focusing on POST endpoints
function_name = details.get("operationId", path.replace("/", "_"))
# Get parameters schema
parameters_schema = {}
required_params = []
if "requestBody" in details and "content" in details["requestBody"]:
content = details["requestBody"]["content"]
if "application/json" in content and "schema" in content["application/json"]:
schema_ref = content["application/json"]["schema"]
if "$ref" in schema_ref:
ref_path = schema_ref["$ref"].split("/")
ref_name = ref_path[-1]
if ref_name in schema["components"]["schemas"]:
schema_obj = schema["components"]["schemas"][ref_name]
parameters_schema = {
"type": "OBJECT",
"properties": {}
}
for prop, prop_details in schema_obj.get("properties", {}).items():
prop_type = prop_details.get("type", "STRING").upper()
if prop_type == "INTEGER":
prop_type = "NUMBER"
parameters_schema["properties"][prop] = {
"type": prop_type,
"description": prop_details.get("description", "")
}
required_params = schema_obj.get("required", [])
elif "properties" in schema_ref:
parameters_schema = {
"type": "OBJECT",
"properties": {}
}
for prop, prop_details in schema_ref["properties"].items():
prop_type = prop_details.get("type", "STRING").upper()
if prop_type == "INTEGER":
prop_type = "NUMBER"
parameters_schema["properties"][prop] = {
"type": prop_type,
"description": prop_details.get("description", "")
}
required_params = schema_ref.get("required", [])
tools.append({
"function_declarations": [{
"name": function_name,
"description": details.get("x-function-description", details.get("description", "")),
"parameters": parameters_schema
}]
})
return tools
# Create Gemini model with tools
gemini_tools = prepare_gemini_tools(api_schema)
model = genai.GenerativeModel(
model_name="gemini-1.5-pro",
tools=gemini_tools
)
# Example user query
user_query = "Can you help predict if a client with a satisfaction score of 2 is at risk of churning?"
# Call Gemini with the tools
response = model.generate_content(user_query)
# Process the response
if hasattr(response, "candidates") and response.candidates:
candidate = response.candidates[0]
if hasattr(candidate, "content") and candidate.content:
for part in candidate.content.parts:
if hasattr(part, "function_call"):
function_call = part.function_call
# Extract function details
function_name = function_call.name
function_args = function_call.args
# Find the corresponding API endpoint
api_endpoint = next((p for p, m in api_schema["paths"].items()
if any(d.get("operationId") == function_name
for _, d in m.items())), None)
if api_endpoint:
print(f"Calling API endpoint: {api_endpoint}")
# Make the actual API call
api_response = requests.post(
f"https://resetthefuture-main-6c663d7.zuplo.app{api_endpoint}",
headers={
"Content-Type": "application/json",
"X-API-Key": "your-reset-the-future-api-key"
},
json=function_args
)
# Return API response to Gemini for interpretation
function_response = {
"name": function_name,
"response": api_response.json()
}
final_response = model.generate_content([
{"text": user_query},
{"text": f"Function response: {json.dumps(function_response)}"}
])
print("AI Agent Response:")
print(final_response.text)
Always securely store and manage your API keys:
Implement robust error handling to provide a seamless user experience:
try:
api_response = requests.post(
f"https://resetthefuture-main-6c663d7.zuplo.app{endpoint}",
headers={
"Content-Type": "application/json",
"X-API-Key": "your-api-key"
},
json=parameters,
timeout=10 # Set appropriate timeout
)
api_response.raise_for_status() # Raise an exception for 4XX/5XX responses
# Process successful response
result = api_response.json()
except requests.exceptions.HTTPError as http_err:
# Handle HTTP errors (4XX, 5XX)
if api_response.status_code == 401:
error_message = "Authentication failed. Please check your API key."
elif api_response.status_code == 429:
error_message = "Rate limit exceeded. Please try again later."
else:
error_message = f"HTTP error: {http_err}"
except requests.exceptions.ConnectionError:
error_message = "Connection error. Please check your internet connection."
except requests.exceptions.Timeout:
error_message = "Request timed out. The service might be experiencing high load."
except requests.exceptions.RequestException as err:
error_message = f"An error occurred: {err}"
except ValueError: # JSON parsing error
error_message = "Error parsing response from the API."
Our API responses include x-agent-response-interpretation
fields that help AI agents understand how to interpret the results. Make sure to pass the complete API response to your AI agent for proper interpretation.
For more complex integrations, consider implementing a middleware layer:
// Example Node.js Express middleware
const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());
app.post('/agent-gateway', async (req, res) => {
try {
const { query, context } = req.body;
// Step 1: Send query to AI agent to determine which API to call
const agentResponse = await callAIAgent(query, context);
// Step 2: If agent decides to call our API, make the call
if (agentResponse.callApi) {
const apiResponse = await axios.post(
`https://resetthefuture-main-6c663d7.zuplo.app${agentResponse.endpoint}`,
agentResponse.parameters,
{
headers: {
'Content-Type': 'application/json',
'X-API-Key': process.env.RESET_THE_FUTURE_API_KEY
}
}
);
// Step 3: Send API response back to AI agent for interpretation
const finalResponse = await callAIAgent(query, context, apiResponse.data);
res.json({
answer: finalResponse.answer,
data: apiResponse.data
});
} else {
res.json({
answer: agentResponse.answer
});
}
} catch (error) {
console.error('Error:', error);
res.status(500).json({ error: 'An error occurred processing your request' });
}
});
function callAIAgent(query, context, apiResponse = null) {
// Implementation depends on which AI platform you're using
// ...
}
app.listen(3000, () => {
console.log('Agent gateway running on port 3000');
});
By integrating Reset The Future's financial intelligence APIs with AI agents, you can provide sophisticated financial insights and services to your users without building complex financial modeling capabilities from scratch.