Spaces:
Build error
Build error
| import os | |
| import gradio as gr | |
| from llama_index.llms.openrouter import OpenRouter | |
| from llama_index.core.llms import ChatMessage | |
| from llama_index.embeddings.huggingface import HuggingFaceEmbedding | |
| from llama_index.core import Settings, StorageContext, load_index_from_storage | |
| import nest_asyncio | |
| nest_asyncio.apply() | |
| # === Глобальная инициализация === | |
| embed_model = HuggingFaceEmbedding(model_name='intfloat/multilingual-e5-large-instruct') | |
| Settings.embed_model = embed_model | |
| Settings.llm = OpenRouter( | |
| api_key=os.environ["OPENROUTER_API_KEY"], | |
| model="qwen/qwen3-4b:free", | |
| max_tokens=10000, | |
| context_window=20000, | |
| ) | |
| # === Функция получения ответа === | |
| def get_facts(system_prompt: str, user_question: str) -> str: | |
| try: | |
| if not user_question.strip(): | |
| return "Ошибка: пожалуйста, введите ваш запрос." | |
| storage_context = StorageContext.from_defaults(persist_dir="./storage") | |
| index = load_index_from_storage(storage_context) | |
| retriever = index.as_retriever(similarity_top_k=4) | |
| nodes = retriever.retrieve(user_question) | |
| context = "\n\n".join([node.get_content() for node in nodes]) if nodes else "Не найдено релевантных документов." | |
| full_system_prompt = system_prompt + f"\n\nКонтекст:\n{context}" | |
| messages = [ | |
| ChatMessage(role="system", content=full_system_prompt), | |
| ChatMessage(role="user", content="Пользовательский запрос: " + user_question) | |
| ] | |
| response = Settings.llm.chat(messages) | |
| return response.message.content | |
| except Exception as e: | |
| return f"❌ Ошибка:\n{str(e)}" | |
| response = Settings.llm.chat(messages) | |
| return response.message.content | |
| with gr.Blocks(theme=gr.themes.Soft()) as demo: | |
| gr.Markdown("# Информационная система для помощи в адаптации к климатическим рискам") | |
| system_input = gr.Textbox( | |
| label="Системный промпт", | |
| lines=5, | |
| max_lines = 5, | |
| placeholder="Введите системный промпт" | |
| ) | |
| user_input = gr.Textbox( | |
| label="Ваш запрос", | |
| lines=4, | |
| max_lines = 4, | |
| placeholder="Введите свой запрос" | |
| ) | |
| answer_output = gr.Textbox(label="Ответ", lines=8, interactive=False) | |
| send_button = gr.Button("Получить ответ") | |
| send_button.click( | |
| fn=get_facts, | |
| inputs=[system_input, user_input], | |
| outputs=answer_output | |
| ) | |
| demo.launch() |