Step 1 - Obtain Your Credentials from The Terra Dashboard
Step 2 - Create an MVP Chat App with Flask
# app.py
import os
import json
import logging
from flask import Flask, render_template, request, redirect, url_for, Response
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from terra.base_client import Terra
logging.basicConfig(level=logging.INFO)
_LOGGER = logging.getLogger("app")
terra = Terra(api_key='<API-KEY>',
              dev_id='<DEV-ID>',
              secret='<SIGNING-SECRET>')
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///chat.db'
db = SQLAlchemy(app)
# ... (rest of the code remains the same)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
    <title>Terra AI Coach</title>
</head>
<body>
    <h1>Terra AI Coach</h1>
    <div class="container mt-5">
        <div id="chat-box" class="mb-3">
            {% for message in messages %}
            {% if message.is_user %}
            <div class="alert alert-primary" role="alert">
                {{ message.text }}
            </div>
            {% else %}
            <div class="alert alert-secondary" role="alert">
                {{ message.text | safe }}
            </div>
            {% endif %}
            {% endfor %}
        </div>
        <hr>
        <form action="{{ url_for('send') }}" method="post">
            <textarea class="form-control" name="message" placeholder="Enter your message"
                style="margin-bottom: 10px;"></textarea>
            <button type="submit" class="btn btn-primary">ASK</button>
        </form>
    </div>
</body>
</html>
Step 3 - Connect a Terra Webhook with Your Server
Step 4 - Add an AI Health Overview
# gpt.py
import os
import json
from openai import OpenAI
from flask import current_app
client = OpenAI(
    api_key=os.environ.get("OPENAI_API_KEY"),
)
def health_overview(question):
    completion = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": """
             Act as an advanced AI personal health coach.
             You provide short insights into health data from a wearable.
             """},
            {"role": "user",
             "content": f"{question}. Respond with HTML and Bootstrap classes!"
             }
        ]
    )
    return completion.choices[0].message.content
# The data is verified
if verified:
    health_data = body['data'][0]['measurements_data']['measurements'][0]
    instance_path = app.instance_path
    json_file_path = os.path.join(instance_path, 'health.json')
    if not os.path.exists(json_file_path):
        with open(json_file_path, 'w') as json_file:
            _LOGGER.info('Saving data into a JSON file..')
            json.dump(health_data, json_file)
    return Response(status=201)
# Handle GET requests
if request.method == 'GET':
    messages = Message.query.order_by(Message.timestamp).all()
    return render_template('index.html', messages=messages)
# Handle GET requests
if request.method == 'GET':
    messages = Message.query.order_by(Message.timestamp).all()
    return render_template('index.html', messages=messages)
<body>
    <h1>Terra AI Coach</h1>
    <div class="container mt-5">
        <div>
            <h1>Health Overview</h1>
            {{ overview | safe }}
            <hr>
            <h1>Chat with Your AI Coach</h1>
        </div>
        <div id="chat-box" class="mb-3">
            {% for message in messages %}
                {% if message.is_user %}
                    <div class="alert alert-primary" role="alert">
                        {{ message.text }}
                    </div>
                {% else %}
                    <div class="alert alert-secondary" role="alert">
                        {{ message.text | safe }}
                    </div>
                {% endif %}
            {% endfor %}
        </div>
        <hr>
        <form action="{{ url_for('send') }}" method="post">
            <textarea class="form-control" name="message" placeholder="Enter your message" style="margin-bottom: 10px;"></textarea>
            <button type="submit" class="btn btn-primary">ASK</button>
        </form>
    </div>
</body>
Step 5 - Use AI to Make Your Chat a Personal Fitness Coach
def ask(question):
    instance_path = current_app.instance_path
    json_file_path = os.path.join(instance_path, 'health.json')
    with open(json_file_path, 'r') as json_file:
        health_data = json.load(json_file)
    completion = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": f"""
             Act as an advanced AI personal health coach.
             Provide short insights into health data from a wearable.
             Here is the data you should base your insights on:
             {health_data}
             """},
            {"role": "user",
             "content": f"{question}. Respond with HTML and Bootstrap classes!"
             }
        ]
    )
    return completion.choices[0].message.content















.png)















