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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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
from langchain_community.agent_toolkits import create_sql_agent
from langchain_openai import ChatOpenAI
from langchain_groq import ChatGroq
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.pydantic_v1 import BaseModel, Field
import pandas as pd
from pydantic import BaseModel, Field

from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import Chroma
from langchain.embeddings import HuggingFaceEmbeddings
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser



gpt = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
#agent_gpt_executor = create_sql_agent(gpt, db=db, agent_type="tool-calling", verbose=True)

## make database
from langchain_community.utilities import SQLDatabase
from sqlalchemy import create_engine

from langchain.prompts import ChatPromptTemplate
from langchain.schema import SystemMessage
from langchain_core.prompts import MessagesPlaceholder
#agent_groq_executor = create_sql_agent(llm, db=db, agent_type="tool-calling", verbose=True)

from OpenAITools.FetchTools import fetch_clinical_trials, fetch_clinical_trials_jp



## Cancer Name の抽出
class ExtractTumorName(BaseModel):
    """Extract tumor name from the user's question."""
    tumor_name: str = Field(description="Extracted tumor name from the question, or 'None' if no tumor found")

class TumorNameExtractor:
    def __init__(self, llm):
        self.llm = llm

        # LLMの出力を構造化するための設定
        self.structured_llm_extractor = self.llm.with_structured_output(ExtractTumorName)

        # システムプロンプトを設定
        self.system_prompt = """あなたは、ユーザーの質問に基づいて腫瘍名を英語で抽出するシステムです。\n
                                質問文に腫瘍の種類や名前が含まれている場合、それを英語で返してください。\n
                                質問文に腫瘍名がない場合は 'None' と返答してください。"""

        # プロンプトテンプレート
        self.grade_prompt = ChatPromptTemplate.from_messages(
            [
                ("system", self.system_prompt),
                ("human", "ユーザーの質問: {question}"),
            ]
        )

    def extract_tumor_name(self, question: str) -> str:
        """
        腫瘍名を抽出するメソッド。
        :param question: 質問文
        :return: 抽出された腫瘍名
        """
        # 質問から腫瘍名を抽出する処理
        tumor_extractor = self.grade_prompt | self.structured_llm_extractor
        result = tumor_extractor.invoke({"question": question})
        return result.tumor_name
    
### 質問変更システム

# ModifyQuestionの出力形式を定義
class ModifyQuestion(BaseModel):
    """Class for modifying a question by inserting NCTID."""
    modified_question: str = Field(description="The modified question with the inserted NCTID.")

class QuestionModifier:
    def __init__(self, llm):
        self.llm = llm

        # LLMの出力を構造化するための設定
        self.structured_llm_modifier = self.llm.with_structured_output(ModifyQuestion)

        # システムプロンプトを設定
        self.system_prompt = """あなたは、ユーザーの質問に対して適切なNCTIDを挿入して質問を変更するシステムです。\n
                                質問文にNCTIDを挿入し、形式に基づいて新しい質問を生成してください。\n
                                例えば16歳男性の神経膠腫の患者さんが参加できる臨床治験を教えて下さいという質問に対しては\n
                                16歳男性の神経膠腫の患者さんは{nct_id}に参加できますか?と変更して下さい\n
                                NCTIDは {nct_id} を使用してください。"""

        # プロンプトテンプレート
        self.modify_prompt = ChatPromptTemplate.from_messages(
            [
                ("system", self.system_prompt),
                ("human", "ユーザーの質問: {question}"),
            ]
        )

    def modify_question(self, question: str, nct_id: str) -> str:
        """
        質問を変更するメソッド。
        :param question: 質問文
        :param nct_id: NCTID
        :return: NCTIDを挿入した新しい質問
        """
        # 質問を変更するプロセス
        question_modifier = self.modify_prompt | self.structured_llm_modifier
        result = question_modifier.invoke({"question": question, "nct_id": nct_id})
        modify_question = result.modified_question
        return modify_question

class QuestionModifierSecond:
    def __init__(self, llm):
        self.llm = llm

        # LLMの出力を構造化するための設定
        self.structured_llm_modifier = self.llm.with_structured_output(ModifyQuestion)

        # システムプロンプトを設定
        self.system_prompt = """あなたは、ユーザーの質問を変更するシステムです。\n
                                形式に基づいて新しい質問を生成してください。\n
                                例えば16歳男性の神経膠腫の患者さんが参加できる臨床治験を教えて下さいという質問に対しては\n
                                16歳男性の神経膠腫の患者さんはlこの治験に参加できますか?と変更して下さい\n
                             """

        # プロンプトテンプレート
        self.modify_prompt = ChatPromptTemplate.from_messages(
            [
                ("system", self.system_prompt),
                ("human", "ユーザーの質問: {question}"),
            ]
        )

    def modify_question(self, question: str) -> str:
        """
        質問を変更するメソッド。
        :param question: 質問文
        :param nct_id: NCTID
        :return: NCTIDを挿入した新しい質問
        """
        # 質問を変更するプロセス
        question_modifier = self.modify_prompt | self.structured_llm_modifier
        result = question_modifier.invoke({"question": question})
        modify_question = result.modified_question
        return modify_question
    
class QuestionModifierEnglish:
    def __init__(self, llm):
        self.llm = llm

        # LLMの出力を構造化するための設定
        self.structured_llm_modifier = self.llm.with_structured_output(ModifyQuestion)

        # システムプロンプトを設定
        self.system_prompt = """あなたは、ユーザーの質問を変更し英語に翻訳するシステムです。\n
                                形式に基づいて新しい質問を生成してください。\n
                                例えば16歳男性の神経膠腫の患者さんが参加できる臨床治験を教えて下さいという質問に対しては\n
                                Can a 16 year old male patient with glioma participate in this clinical trial?と変更して下さい\n
                             """

        # プロンプトテンプレート
        self.modify_prompt = ChatPromptTemplate.from_messages(
            [
                ("system", self.system_prompt),
                ("human", "ユーザーの質問: {question}"),
            ]
        )

    def modify_question(self, question: str) -> str:
        """
        質問を変更するメソッド。
        :param question: 質問文
        :param nct_id: NCTID
        :return: NCTIDを挿入した新しい質問
        """
        # 質問を変更するプロセス
        question_modifier = self.modify_prompt | self.structured_llm_modifier
        result = question_modifier.invoke({"question": question})
        modify_question = result.modified_question
        return modify_question
    

### Make  criteria check Agent

class ClinicalTrialAgent:
    def __init__(self, llm, db):
        self.llm = llm
        self.db = db

        # システムプロンプトの定義
        self.system_prompt = """
        あなたは患者さんに適した治験を探すエージェントです。
        データベースのEligibility Criteriaをチェックして患者さんがその治験を受けることが可能かどうか答えて下さい
        """

        # プロンプトテンプレートを作成
        self.prompt = ChatPromptTemplate.from_messages(
            [("system", self.system_prompt), 
             ("human", "{input}"), 
             MessagesPlaceholder("agent_scratchpad")]
        )

        # SQL Agentの設定
        self.agent_executor = self.create_sql_agent(self.llm, self.db, self.prompt)

    def create_sql_agent(self, llm, db, prompt):
        """SQLエージェントを作成するメソッド"""
        agent_executor = create_sql_agent(
            llm, 
            db=db, 
            prompt=prompt, 
            agent_type="tool-calling", 
            verbose=True
        )
        return agent_executor

    def get_agent_judgment(self, modify_question: str) -> str:
        """
        Modifyされた質問を元に、患者さんが治験に参加可能かどうかのエージェント判断を取得。
        :param modify_question: NCTIDが挿入された質問
        :return: エージェントの判断 (AgentJudgment)
        """
        # LLMに質問を投げて、判断を得る
        result = self.agent_executor.invoke({"input": modify_question})
        return result
    

class SimpleClinicalTrialAgent:
    def __init__(self, llm):
        self.llm = llm

    def evaluate_eligibility(self, TargetCriteria: str, question: str) -> str:
        """
        臨床試験の参加適格性を評価するメソッド。
        :param TargetCriteria: 試験基準 (Inclusion/Exclusion criteria)
        :param question: 患者の条件に関する質問
        :return: 臨床試験に参加可能かどうかのLLMからの応答
        """

        # プロンプトの定義
        prompt_template = """
        You are an agent looking for a suitable clinical trial for a patient.
        Please answer whether the patient is eligible for this clinical trial based on the following criteria. If you do not know the answer, say you do not know. Your answer should be brief, no more than 3 sentences.
        Question: {question} 
        Criteria:
        """ + TargetCriteria

        # プロンプトテンプレートの作成
        criteria_prompt = ChatPromptTemplate.from_messages(
            [
                (
                    "human",
                    prompt_template
                )
            ]
        )

        # RAGチェーンの作成
        rag_chain = (
            {"question": RunnablePassthrough()}
            | criteria_prompt
            | self.llm
            | StrOutputParser()
        )

        # 質問をチェーンに渡して、応答を得る
        response = rag_chain.invoke(question)
        return response
    

### output 評価システム
class TrialEligibilityGrader(BaseModel):
    """3値評価: yes, no, unclear"""
    score: str = Field(
        description="The eligibility of the patient for the clinical trial based on the document. Options are: 'yes', 'no', or 'unclear'."
    )

class GraderAgent:
    def __init__(self, llm):
        self.llm = llm

        # LLMの出力を構造化するための設定
        self.structured_llm_grader = self.llm.with_structured_output(TrialEligibilityGrader)

        # Graderの入力プロンプト
        self.system_prompt = """
        あなたは治験に参加する患者の適合性を評価するGraderです。
        以下のドキュメントを読み、患者が治験に参加可能かどうかを判断してください。
        'yes'(参加可能)、'no'(参加不可能)、'unclear'(判断できない)の3値で答えてください。
        """

        # 評価のためのプロンプトを作成
        self.grade_prompt = ChatPromptTemplate.from_messages(
            [
                ("system", self.system_prompt),
                (
                    "human",
                    "取得したドキュメント: \n\n {document} ",
                ),
            ]
        )

    def evaluate_eligibility(self, AgentJudgment_output: str) -> str:
        """
        AgentJudgment['output']を基に患者が治験に参加可能かどうかを評価し、スコア(AgentGrade)を返す。
        :param AgentJudgment_output: エージェント判断の 'output' の値
        :return: 評価されたスコア (AgentGrade)
        """
        GraderAgent = self.grade_prompt | self.structured_llm_grader
        result = GraderAgent.invoke({"document": AgentJudgment_output})
        AgentGrade = result.score
        return AgentGrade

import re

class LLMTranslator:
    def __init__(self, llm):
        self.llm = llm
        self.structured_llm_modifier = self.llm.with_structured_output(ModifyQuestion)

        self.system_prompt = """あなたは、優秀な翻訳者です。\n
                                日本語を英語に翻訳して下さい。\n
                             """
        self.system_prompt2 = """あなたは、優秀な翻訳者です。\n
                                日本語を英語に以下のフォーマットに従って翻訳して下さい。\n
                                MainQuestion:
                                Known gene mutation:
                                Measurable tumour:
                                Biopsiable tumour:
                             """

        self.modify_prompt = ChatPromptTemplate.from_messages(
            [
                ("system", self.system_prompt),
                ("human", "ユーザーの質問: {question}"),
            ]
        )

        self.modify_prompt2 = ChatPromptTemplate.from_messages(
            [
                ("system", self.system_prompt2),
                ("human", "ユーザーの質問: {question}"),
            ]
        )

    def is_english(self, text: str) -> bool:
        """
        簡易的にテキストが英語かどうかを判定する関数
        :param text: 判定するテキスト
        :return: 英語の場合True、日本語の場合False
        """
        # 英語のアルファベットが多く含まれているかを確認
        return bool(re.match(r'^[A-Za-z0-9\s.,?!]+$', text))

    def translate(self, question: str) -> str:
        """
        質問を翻訳するメソッド。英語の質問はそのまま返す。
        :param question: 質問文
        :return: 翻訳済みの質問文、または元の質問文(英語の場合)
        """
        # 質問が英語の場合、そのまま返す
        if self.is_english(question):
            return question
        
        # 日本語の質問は翻訳プロセスにかける
        question_modifier = self.modify_prompt | self.structured_llm_modifier
        result = question_modifier.invoke({"question": question})
        modify_question = result.modified_question
        return modify_question
    
    def translateQuestion(self, question: str) -> str:
        """
        フォーマット付きで質問を翻訳するメソッド。
        :param question: 質問文
        :return: フォーマットに従った翻訳済みの質問
        """
        question_modifier = self.modify_prompt2 | self.structured_llm_modifier
        result = question_modifier.invoke({"question": question})
        modify_question = result.modified_question
        return modify_question

def generate_ex_question(age, sex, tumor_type, GeneMutation, Meseable, Biopsiable):
    # GeneMutationが空の場合はUnknownに設定
    gene_mutation_text = GeneMutation if GeneMutation else "Unknown"
    
    # MeseableとBiopsiableの値をYes, No, Unknownに変換
    meseable_text = (
        "Yes" if Meseable == "有り" else "No" if Meseable == "無し" else "Unknown"
    )
    biopsiable_text = (
        "Yes" if Biopsiable == "有り" else "No" if Biopsiable == "無し" else "Unknown"
    )
    
    # 質問文の生成
    ex_question = f"""{age}{sex}{tumor_type}患者さんはこの治験に参加することができますか?
判明している遺伝子変異: {gene_mutation_text}
Meseable tumor: {meseable_text}
Biopsiable tumor: {biopsiable_text}
です。
"""
    return ex_question

def generate_ex_question_English(age, sex, tumor_type, GeneMutation, Meseable, Biopsiable):
    # GeneMutationが空の場合は"Unknown"に設定
    gene_mutation_text = GeneMutation if GeneMutation else "Unknown"
    
    # sexの値を male または female に変換
    sex_text = "male" if sex == "男性" else "female" if sex == "女性" else "Unknown"
    
    # MeseableとBiopsiableの値を "Yes", "No", "Unknown" に変換
    meseable_text = (
        "Yes" if Meseable == "有り" else "No" if Meseable == "無し" else "Unknown"
    )
    biopsiable_text = (
        "Yes" if Biopsiable == "有り" else "No" if Biopsiable == "無し" else "Unknown"
    )
    
    # 英語での質問文を生成
    ex_question = f"""Can a {age}-year-old {sex_text} patient with {tumor_type} participate in this clinical trial?
Known gene mutation: {gene_mutation_text}
Measurable tumor: {meseable_text}
Biopsiable tumor: {biopsiable_text}
"""
    return ex_question