Spaces:
Sleeping
Sleeping
| import os | |
| import torch | |
| import gradio as gr | |
| from transformers import pipeline, AutoTokenizer | |
| from langchain_community.llms import HuggingFacePipeline | |
| from langchain.agents import AgentExecutor, create_react_agent | |
| from langchain.tools import BaseTool | |
| from langchain_core.prompts import PromptTemplate | |
| from langchain import hub | |
| # 1. Configuraci贸n del Modelo DeepSeek | |
| model_id = 'deepseek-ai/deepseek-coder-6.7b-instruct' | |
| tokenizer = AutoTokenizer.from_pretrained(model_id) | |
| llm_pipeline = pipeline( | |
| 'text-generation', | |
| model=model_id, | |
| tokenizer=tokenizer, | |
| torch_dtype=torch.bfloat16, | |
| device_map='auto', | |
| max_new_tokens=512 | |
| ) | |
| llm = HuggingFacePipeline(pipeline=llm_pipeline) | |
| # 2. Definici贸n de Herramientas (Tools) | |
| class CalculatorTool(BaseTool): | |
| name = 'calculator' | |
| description = 'Useful for math. Provide only the expression.' | |
| def _run(self, expression: str) -> str: | |
| try: | |
| return str(eval(expression)) | |
| except: | |
| return 'Error.' | |
| tools = [CalculatorTool()] | |
| # 3. Descarga del Prompt con Plan B Robusto Integrado | |
| try: | |
| # Intenta traer la plantilla oficial de la comunidad para agentes ReAct | |
| prompt = hub.pull('hwchase17/react') | |
| except Exception: | |
| print("鈿狅笍 No se pudo conectar al Hub de LangChain. Usando plantilla ReAct local de respaldo...") | |
| # Estructura estricta exigida por create_react_agent para no lanzar ValueError | |
| template = """Answer the following questions as best you can. You have access to the following tools: | |
| {tools} | |
| Use the following format: | |
| Question: the input question you must answer | |
| Thought: you should always think about what to do | |
| Action: the action to take, should be one of [{tool_names}] | |
| Action Input: the input to the action | |
| Observation: the result of the action | |
| (this Thought/Action/Action Input/Observation can repeat N times) | |
| Thought: I now know the final answer | |
| Final Answer: the final answer to the original input question | |
| Begin! | |
| Question: {input} | |
| Thought: {agent_scratchpad}""" | |
| prompt = PromptTemplate( | |
| template=template, | |
| input_variables=["input", "tools", "tool_names", "agent_scratchpad"] | |
| ) | |
| # 4. Inicializaci贸n del Agente y su Ejecutor | |
| agent = create_react_agent(llm, tools, prompt) | |
| agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True, handle_parsing_errors=True) | |
| # 5. Funci贸n de Predicci贸n para la Interfaz | |
| def predict(message, history): | |
| res = agent_executor.invoke({'input': message}) | |
| return res['output'] | |
| # 6. Interfaz Gr谩fica con Gradio 6.x (Par谩metro theme movido a launch) | |
| with gr.Blocks() as demo: | |
| gr.Markdown('# 馃 DeepSeek Agent Terminal') | |
| gr.Markdown('Agente inteligente basado en arquitectura ReAct para resoluci贸n de problemas l贸gicos y matem谩ticos.') | |
| gr.ChatInterface(fn=predict) | |
| if __name__ == '__main__': | |
| # Lanzamiento nativo optimizado para Hugging Face Spaces | |
| demo.launch( | |
| server_name='0.0.0.0', | |
| server_port=7860, | |
| theme=gr.themes.Soft(primary_hue='green'), | |
| show_error=True | |
| ) |