File size: 7,841 Bytes
d07aba7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
tools=[{
    "name": "analyze_symptoms_from_text_ai",
    "description": "Analyzes text to extract medical symptoms and returns them in CSV format.",
    "api": {
        "name": "analyze_symptoms_from_text_ai",
        "parameters": {
            "type": "object",
            "properties": {
                "text_input": {
                    "type": "string",
                    "description": "Raw text description of health condition"
                }
            },
            "required": ["text_input"]
        }
    }
},

{
            "name": "full_treatment_answer_ai",
            "description": "Generates complete plant-based treatment plans for given symptoms, including dosage, preparation methods, and safety information.",
            "api": {
                "name": "full_treatment_answer_ai",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "user_input": {
                            "type": "string",
                            "description": "User's description of symptoms or health condition"
                        }
                    },
                    "required": ["user_input"]
                }
            }
        }
]

import os
from typing import List, Dict, Any
from openai import OpenAI

def analyze_symptoms_from_text_ai(text_input: str) -> str:
    """

    Analyze user-provided text to extract medical symptoms in CSV format.

    

    Args:

        text_input: Raw text description of health condition

        

    Returns:

        str: Comma-separated list of symptoms in CSV format

        

    Example:

        >>> analyze_symptoms_from_text_ai("I have headache and nausea")

        'headache,nausea'

    """
    client = OpenAI(
        base_url="https://api.studio.nebius.com/v1/",
        api_key=os.environ.get("NEBIUS_API_KEY")
    )
    
    try:
        response = client.chat.completions.create(
            model="google/gemma-2-2b-it",
            max_tokens=512,
            temperature=0.5,
            top_p=0.9,
            extra_body={"top_k": 50},
            messages=[
                {
                    "role": "system",
                    "content": """You are a medical symptom extractor. 

                    Analyze the text and return ONLY a comma-separated list of symptoms in CSV format.

                    Example input: "I have headache and feel nauseous"

                    Example output: headache,nausea"""
                },
                {
                    "role": "user",
                    "content": f"Analyze this text for symptoms and list them in CSV format: {text_input}"
                }
            ]
        )
        
        # Extract and clean the response
        symptoms_csv = response.choices.message.content.strip()
        return symptoms_csv
        
    except Exception as e:
        print(f"Error analyzing symptoms: {str(e)}")
        return ""



#usage:
#symptoms = analyze_symptoms_from_text_ai("I've been experiencing insomnia and occasional dizziness")


#///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#///////////////////////////////////////////////////////////////////////////////////////////////////////////////////


import os
from typing import List, Dict, Any
from openai import OpenAI

def full_treatment_answer_ai(user_input: str) -> str:
    """

    Searches for plant treatments based on user symptoms using Nebius API.

    

    Args:

        user_input: User's symptom description

        

    Returns:

        str: Complete treatment plan with plant recommendations and details

    """
    # Initialize Nebius client
    client = OpenAI(
        base_url="https://api.studio.nebius.com/v1/",
        api_key=os.environ.get("NEBIUS_API_KEY")
    )
    
    # Step 1: Extract symptoms from user input
    text_symptoms = analyze_symptoms_from_text_ai(user_input)
    symptoms_list = text_symptoms.split(",")
    symptoms = get_unique_symptoms(symptoms_list)
    
    if not symptoms:
        return "Could not identify any specific symptoms. Please describe your condition in more detail."
    
    # Step 2: Find relevant plants for each symptom
    all_related_plants = []
    for symptom in symptoms:
        related_plants = lookup_symptom_and_plants(symptom)
        all_related_plants.extend(related_plants)
    
    # Step 3: Prepare the prompt for Nebius API
    plants_info = ""
    if all_related_plants:
        plants_info = "Here are some plants that might be relevant:\n"
        for plant in all_related_plants[:6]:  # Limit to top 6 plants
            plants_info += f"""\nPlant: {plant['name']}

{plant['description']}

Cures: {plant['treatable_conditions']}

Dosage: {plant['dosage']}\n"""
    else:
        plants_info = "I dont know specific plants for these symptoms. please get useful plants from anywhere or any other sources"
    
    prompt = f"""I have these symptoms: {", ".join(symptoms)}.



{plants_info}



Please analyze my symptoms and recommend the most appropriate plant remedy. 

Consider the symptoms, when to use each plant, dosage, and how to use it.

Provide your recommendation in this format:



**Recommended Plant**: [plant name]

**Reason**: [why this plant is good for these symptoms]

**Dosage**: [recommended dosage]

**Instructions**: [how to use it]

**Image**: [mention if image is available]



If multiple plants could work well, you may recommend up to 3 options."""

    # Step 4: Call Nebius API for treatment recommendation
    try:
        response = client.chat.completions.create(
            model="deepseek-ai/DeepSeek-V3-0324-fast",
            max_tokens=1024,  # Increased for detailed responses
            temperature=0.3,
            top_p=0.95,
            messages=[
                {
                    "role": "system",
                    "content": """You are a professional botanist assistant specializing in medicinal plants. 

                    Provide accurate, science-backed recommendations for plant-based treatments. 

                    Include dosage, preparation methods, and safety considerations."""
                },
                {
                    "role": "user",
                    "content": prompt
                }
            ]
        )
        
        final_result = response.choices.message.content
        
        # Step 5: Append detailed plant information if available
        if all_related_plants:
            final_result += "\n---\nMore Details for Recommended Plants:\n"
            for plant in all_related_plants[:3]:  # Show details for top 3 plants
                final_result += f"""

**Plant Name**: {plant['name']}

**Scientific Name**: {plant['scientific_name']}

**Other Names**: {plant['alternate_names']}

**Description**: {plant['description']}

**Treatable Conditions**: {plant['treatable_conditions']}

**Preparation**: {plant['preparation_methods']}

**Dosage**: {plant['dosage']}

**Side Effects**: {plant['side_effects']}

**Contraindications**: {plant['contraindications']}

**Sources**: {plant['sources']}

"""
        
        return final_result
        
    except Exception as e:
        print(f"Error generating treatment plan: {str(e)}")
        return "Sorry, I couldn't generate a treatment plan at this time. Please try again later."
        

#usage:
#treatment = full_treatment_answer_ai("I have headaches and occasional nausea") #todo remove the dependancy on the other function
#print(treatment)