# Project export: Healthiator

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: TreeHacks 2024
- Tagline: Easily compare medical costs across hospitals, tailored to your condition, insurance plan vs out-of-pocket payment with Healthiator. Uncover savings and take control of your healthcare journey.
- Devpost: https://devpost.com/software/healthiator
- GitHub: https://github.com/elenaxx2022/healthiator
- Demo: https://pitch.com/v/healthiator-g9crp5
- Result: winner (Fetch.ai: Smartest AI Agent Prize (Top 2 Teams - $3k Cash))
- Team: 1 GitHub contributor(s) — elenaxx2022 (1 commits)

## Devpost submission (written by the team)

### Inspiration

As a patient in the United States you do not know what costs you are facing when you receive treatment at a hospital or if your insurance plan covers the expenses. Patients are faced with unexpected bills and left with expensive copayments. In some instances patients would pay less if they cover the expenses out of pocket instead of using their insurance plan.

### What it does

Healthiator provides patients with a comprehensive overview of medical procedures that they will need to undergo for their health condition and sums up the total costs of that treatment depending on which hospital they go-to, and if they pay the treatment out-of-pocket or through their insurance. This allows patients to choose the most cost-effective treatment and understand the medical expenses they are facing. A second feature healthiator provides is that once patients receive their actual hospital bill they can claim inaccuracies. Healthiator helps patients with billing disputes by leveraging AI to handle the process of negotiating fair pricing.

### How we built it

We used a combination of Together.AI and Fetch.AI. We have several smart agents running in Fetch.AI each responsible for one of the features. For instance, we get the online and instant data from the hospitals (publicly available under the Good Faith act/law) about the prices and cash discounts using one agent and then use together.ai's API to integrate those information in the negotiation part. Ethics The reason is that although our end purpose is to help people get medical treatment by reducing the fear of surprise bills and actually making healthcare more affordable, we are aware that any wrong suggestions or otherwise violations of the user's privacy have significant consequences. Giving the user as much information as possible while keeping away from making clinical suggestions and false/hallucinated information was the most challenging part in our work.

### Challenges we ran into

Finding actionable data from the hospitals was one of the most challenging parts as each hospital has their own format and assumptions and it was not straightforward at all how to integrate them all into a single database. Another challenge was making various APIs and third parties work together in time.

### Accomplishments we're proud of

Solving a relevant social issue. Everyone we talked to has experienced the problem of not knowing the costs they're facing for different procedures at hospitals and if their insurance covers it. While it is an anxious process for everyone, this fact might prevent and delay a number of people from going to hospitals and getting the care that they urgently need. This might result in health conditions that could have had a better outcome if treated earlier.

### What we learned

How to work with convex fetch.api and together.api.

### What's next

As a next step, we want to set-up a database and take the medical costs directly from the files published by hospitals.

## README (from the GitHub repository)

# healthiator
Easily compare medical costs across hospitals, tailored to your condition, insurance plan vs out-of-pocket payment with Healthiator. Uncover savings and take control of your healthcare journey.

## Inspiration
As a patient in the United States you do not know what costs you are facing when you receive treatment at a hospital or if your insurance plan covers the expenses. Patients are faced with unexpected bills and left with expensive copayments. In some instances patients would pay less if they cover the expenses out of pocket instead of using their insurance plan.

## What it does
Healthiator provides patients with a comprehensive overview of medical procedures that they will need to undergo for their health condition and sums up the total costs of that treatment depending on which hospital they go-to, and if they pay the treatment out-of-pocket or through their insurance. 
This allows patients to choose the most cost-effective treatment and understand the medical expenses they are facing. A second feature healthiator provides is that once patients receive their actual hospital bill they can claim inaccuracies. Healthiator helps patients with billing disputes by leveraging AI to handle the process of negotiating fair pricing. 

## How we built it
We used a combination of Together.AI and Fetch.AI. We have several smart agents running in Fetch.AI each responsible for one of the features. For instance, we get the online and instant data from the hospitals (publicly available under the Good Faith act/law) about the prices and cash discounts using one agent and then use together.ai's API to integrate those information in the negotiation part.

## Ethics
The ethics of the project was by far the most important and challenging part. The reason is that although our end purpose is to help people keep healthier by reducing the fear of surprise bills and actually making healthcare more affordable, we are aware that any wrong suggestions or otherwise violations of the user's privacy have significant consequences. Giving the user as much information as possible while keeping away from making clinical suggestions and false/hallucinated information was the most challenging part in our work.

## Challenges we ran into
Finding actionable data from the hospitals was one of the most challenging parts as each hospital has their own format and assumptions and it was not straightforward at all how to integrate them all into a single database. Another challenge was making various APIs and third parties work together in time.

## Accomplishments that we're proud of
Solving a relevant social issue. Everyone we talked to has experienced the problem of not knowing the costs they're facing for different procedures at hospitals and if their insurance covers it. While it is an anxious process for everyone, this fact might prevent and delay a number of people from going to hospitals and getting the care that they urgently need. This might result in health conditions that could have had a better outcome if treated earlier.

## What we learned
How to work with convex, fetch.api and together.api. 

## What's next for Healthiator
Getting more extensive user feedback and buidling a UI.

## Detected evidence (automated analysis)

Indexed codebase: 2 recognized source files, 7 KB.
- Python (language) — detected in the code
- JavaScript (language) — claimed on Devpost, not found in the code
- React (technology) — claimed on Devpost, not found in the code

## Codebase structure (from repository index)

### Files (2 of 2)

```
agent.py
README.md
```

### Dependencies

No dependency index available.

### Recent commits (newest first)

- add read me text
- add agent
- Initial commit

## Key source files (fetched from GitHub, selected and truncated for size)

### agent.py

```python

# Here we demonstrate how an agent can respond to plain text questions with data from an AI model and convert it into a machine readable format.
# Note: the AI model used here is not actually able to verify its information and is not guaranteed to be correct. The purpose of this example is to show how to interact with such a model.
#
# In this example we will use:
# - 'agent': this is your instance of the 'Agent' class that we will give an 'on_interval' task
# - 'ctx': this is the agent's 'Context', which gives you access to all the agent's important functions
# - 'requests': this is a module that allows you to make HTTP requests
#
# To use this example, you will need to provide an API key for OPEN AI: https://platform.openai.com/account/api-keys
# You can define your OPENAI_API_KEY value in the .env file
#if OPENAI_API_KEY == "YOUR_OPENAI_API_KEY":
#    raise Exception("You need to provide an API key for OPEN AI to use this example")

# Configuration for making requests to OPEN AI 

from pydantic import Field
from ai_engine import UAgentResponse, UAgentResponseType

OPENAI_URL = "https://api.together.xyz/v1/chat/completions"
MODEL_ENGINE = "meta-llama/Llama-2-70b-chat-hf"
HEADERS = {
    "Authorization": f"Bearer 4fbc78f4cae052bc8b2b358646e3ffad231f7241da976fa649b06168141e15b3"
}


class Request(Model):
    text: str


class Error(Model):
    text: str


class Data(Model):
    name: str
    explanation: str
    CDM: str
    HCPCS: str

class ListModel(Model):
    procs_list: List[Data]

class Response(Model):
    text: str

medical_condition_protocol = Protocol("Medical_Condition")

# Send a prompt and context to the AI model and return the content of the completion
def get_completion(context: str, prompt: str):
    data = 'data'

    try:
        response = requests.post('https://api.together.xyz/v1/chat/completions', json={
    "model": "meta-llama/Llama-2-70b-chat-hf",
    "messages": [
        {
            "role": "system",
            "content": context
        },
        {
            "role": "user",
            "content": prompt
        }
    ],
    "temperature": 0.1,
    "top_p": 0.7,
    "top_k": 50,
    "repetition_penalty": 1,
    "stop": [
        "[/INST]",
        "</s>"
    ],
    "repetitive_penalty": 1
}, headers={
    "Authorization": "Bearer 4fbc78f4cae052bc8b2b358646e3ffad231f7241da976fa649b06168141e15b3",
})

        messages = response.json()['choices']

        message = messages[0]['message']['content']

    except Exception as ex:
        return None

    #print("Got response from AI model: " + message)
    return message


# Instruct the AI model to retrieve data and context for the data and return it in machine readable JSON format
def get_data(ctx: Context, request: str):
    context = """A patient is describing their symptoms. Based on that, give the best prediction of the medical condition in up to 3 words. Don't say anything more than that. Only give your best guess and no other explanation. Keep it at 3 words or less."""

    response = get_completion(context, request)

    try:
        print(response)
        return Response(text=response)
    except Exception as ex:
        ctx.logger.exception(f"An error occurred retrieving data from the AI model: {ex}")
        return Error(text="Sorry, I wasn't able to answer your request this time. Feel free to try again.")

# Message handler for data requests sent to this agent
#@agent.on_message(model=Request)
#async def handle_request(ctx: Context, sender: str, request: Request):
#    ctx.logger.info(f"Got request from {sender}: {request.text}")
#    response = get_data(ctx, request.text)
#    print("After data, about to send")
#    await ctx.send(sender, response)
#    print("After sent")
    

@medical_condition_protocol.on_message(model=Request, replies={UAgentResponse})
async def send_llm_request(ctx: Context, sender: str, msg: Request):
    condition = await get_data(ctx, msg.text)
    print("Condition is found:")
    print(condition)
    await ctx.send(
        sender, UAgentResponse(message=condition.text, type=UAgentResponseType.FINAL)
    )
agent.include(medical_condition_protocol, publish_manifest=True)
```