Skip to content
liamspeer82-dotcomPublic

About

First Aid

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 

Repository files navigation

import os
import zipfile

# Project structure
project_name = "ai-doctor-chat"
base_path = f"/mnt/data/{project_name}"
os.makedirs(base_path, exist_ok=True)

# File contents
files = {
    "package.json": """{
  "name": "ai-doctor-chat",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@vitejs/plugin-react": "^4.0.0",
    "vite": "^4.0.0"
  }
}""",

    "vite.config.js": """import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
})""",

    "netlify.toml": """[build]
  command = "npm run build"
  publish = "dist"

[functions]
  directory = "netlify/functions"
""",

    "public/index.html": """<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>AI Doctor Chat</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/index.jsx"></script>
  </body>
</html>
""",

    "src/index.jsx": """import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
)
""",

    "src/App.jsx": """import React, { useState, useEffect, useRef } from 'react'

export default function App() {
  const [messages, setMessages] = useState([
    { id: 1, role: 'assistant', text: 'Hello! I am your AI health assistant. Describe your symptoms and I will provide general health info. If this is an emergency, call 000/911 immediately.' }
  ])
  const [input, setInput] = useState('')
  const [loading, setLoading] = useState(false)
  const messagesEndRef = useRef(null)

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }, [messages])

  async function handleSend(e) {
    e.preventDefault()
    if (!input.trim()) return

    const newMessage = { id: Date.now(), role: 'user', text: input }
    setMessages(prev => [...prev, newMessage])
    setInput('')
    setLoading(true)

    try {
      const res = await fetch('/.netlify/functions/ai-doctor', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ question: newMessage.text, history: messages })
      })
      const data = await res.json()
      setMessages(prev => [...prev, { id: Date.now()+1, role: 'assistant', text: data.reply }])
    } catch (err) {
      setMessages(prev => [...prev, { id: Date.now()+2, role: 'assistant', text: 'Error contacting assistant service.' }])
    } finally {
      setLoading(false)
    }
  }

  return (
    <div style={{ maxWidth: 600, margin: '0 auto', padding: 20, fontFamily: 'sans-serif' }}>
      <h1>AI Doctor Chat</h1>
      <div style={{ border: '1px solid #ccc', padding: 10, borderRadius: 8, height: 400, overflowY: 'auto', marginBottom: 10 }}>
        {messages.map(m => (
          <div key={m.id} style={{ textAlign: m.role === 'user' ? 'right' : 'left', margin: '5px 0' }}>
            <div style={{ display: 'inline-block', padding: '8px 12px', borderRadius: 12, background: m.role === 'user' ? '#007bff' : '#f1f1f1', color: m.role === 'user' ? '#fff' : '#000' }}>
              {m.text}
            </div>
          </div>
        ))}
        <div ref={messagesEndRef} />
      </div>
      <form onSubmit={handleSend} style={{ display: 'flex', gap: 8 }}>
        <input value={input} onChange={e => setInput(e.target.value)} placeholder=\"Describe your symptoms...\" style={{ flex: 1, padding: 10, borderRadius: 8, border: '1px solid #ccc' }} disabled={loading} />
        <button type=\"submit\" disabled={loading} style={{ padding: '10px 20px', borderRadius: 8, background: '#007bff', color: '#fff', border: 'none' }}>{loading ? '...' : 'Send'}</button>\n      </form>\n      <p style={{ fontSize: 12, marginTop: 10, color: '#555' }}>Disclaimer: This is for general informational purposes only, not medical advice. For emergencies, call your local emergency number.</p>\n    </div>\n  )\n}\n""",

    "netlify/functions/ai-doctor.js": """import fetch from 'node-fetch'

export async function handler(event) {
  try {
    const { question, history } = JSON.parse(event.body)

    const systemPrompt = `You are a safe medical assistant. Provide general info only, ask clarifying questions, and suggest when to see a doctor. Never diagnose or prescribe.`

    const messages = [
      { role: 'system', content: systemPrompt }
    ]

    if (history && Array.isArray(history)) {
      history.slice(-6).forEach(h => {
        messages.push({ role: h.role === 'assistant' ? 'assistant' : 'user', content: h.text })
      })
    }

    messages.push({ role: 'user', content: question })

    const resp = await fetch('https://api.openai.com/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`
      },
      body: JSON.stringify({
        model: 'gpt-4o-mini',
        messages,
        max_tokens: 500,
        temperature: 0.2
      })
    })

    if (!resp.ok) {
      const text = await resp.text()
      return { statusCode: 500, body: text }
    }

    const data = await resp.json()
    const reply = data.choices?.[0]?.message?.content || 'Sorry, no reply.'
    const safeReply = reply + '\\n\\n[Disclaimer: This is not medical advice. For emergencies call your local emergency number.]'

    return { statusCode: 200, body: JSON.stringify({ reply: safeReply }) }
  } catch (err) {
    console.error(err)
    return { statusCode: 500, body: 'Server error' }
  }
}
"""
}

# Write files to directory
for path, content in files.items():
    full_path = os.path.join(base_path, path)
    os.makedirs(os.path.dirname(full_path), exist_ok=True)
    with open(full_path, "w") as f:
        f.write(content)

# Zip project
zip_path = f"/mnt/data/{project_name}.zip"
with zipfile.ZipFile(zip_path, "w") as z:
    for root, _, filenames in os.walk(base_path):
        for filename in filenames:
            file_path = os.path.join(root, filename)
            z.write(file_path, os.path.relpath(file_path, base_path))

zip_path

About

First Aid

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors