Spaces:
Configuration error
Configuration error
Download agent.py from douglasribeiro/simpy: direct link, hf CLI and curl.
- Browser
- Download file 5.49 kB
-
https://huggingface.co/spaces/douglasribeiro/simpy/resolve/main/agent.py
- Command line
-
hf download hf://spaces/douglasribeiro/simpy/agent.py
-
curl -L -o agent.py https://huggingface.co/spaces/douglasribeiro/simpy/resolve/main/agent.py
5.49 kB
| import os | |
| from dotenv import load_dotenv | |
| from typing import List, Dict, Any | |
| from langchain.tools import Tool | |
| from langchain.agents import AgentExecutor, create_react_agent | |
| from langchain.prompts import PromptTemplate | |
| from langchain_community.vectorstores import FAISS | |
| from langchain_community.embeddings import HuggingFaceEmbeddings | |
| from langchain_huggingface import HuggingFaceEndpoint | |
| from langchain.docstore.document import Document | |
| from tools.simpy_tools import simulate_mm1, simulate_assembly_line | |
| load_dotenv() | |
| DB_DIR = os.getenv("DB_DIR", "db") | |
| EMBEDDINGS_MODEL = os.getenv("EMBEDDINGS_MODEL", "sentence-transformers/all-MiniLM-L6-v2") | |
| HF_MODEL_ID = os.getenv("HF_MODEL_ID", "google/gemma-2-9b-it") | |
| HF_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN") | |
| # --- Retriever (FAISS) --- | |
| def get_retriever(): | |
| embeddings = HuggingFaceEmbeddings(model_name=EMBEDDINGS_MODEL) | |
| vectordb = FAISS.load_local(os.path.join(DB_DIR, "faiss_index"), embeddings, allow_dangerous_deserialization=True) | |
| return vectordb.as_retriever(search_kwargs={"k": 4}) | |
| def search_docs(query: str) -> str: | |
| retriever = get_retriever() | |
| docs: List[Document] = retriever.get_relevant_documents(query) | |
| chunks = "\n\n".join([f"[Fonte: {d.metadata.get('source','?')}]\n{d.page_content}" for d in docs]) | |
| return chunks or "Sem resultados nos materiais locais." | |
| # --- LLM --- | |
| def get_llm(): | |
| llm = HuggingFaceEndpoint( | |
| repo_id=HF_MODEL_ID, | |
| task="text-generation", | |
| temperature=0.2, | |
| max_new_tokens=512, | |
| huggingfacehub_api_token=HF_TOKEN, | |
| ) | |
| return llm | |
| # --- Ferramentas didáticas --- | |
| def mm1_tool_run(q: str) -> str: | |
| """ | |
| Extrai parâmetros simples do texto do usuário (heurística) e roda a M/M/1. | |
| Ex.: "simule mm1 com lambda=1.1 mu=1.5 tempo=2000" | |
| """ | |
| import re | |
| lam = float(re.search(r"lambda\s*=\s*([\d\.]+)", q or "")[1]) if re.search(r"lambda\s*=\s*([\d\.]+)", q or "") else 1.0 | |
| mu = float(re.search(r"mu\s*=\s*([\d\.]+)", q or "")[1]) if re.search(r"mu\s*=\s*([\d\.]+)", q or "") else 1.2 | |
| T = float(re.search(r"(tempo|time)\s*=\s*([\d\.]+)", q or "")[2]) if re.search(r"(tempo|time)\s*=\s*([\d\.]+)", q or "") else 1000 | |
| res = simulate_mm1(arrival_rate=lam, service_rate=mu, sim_time=T) | |
| return f"Resultados M/M/1 (λ={lam}, μ={mu}, T={T}):\n" + "\n".join([f"- {k}: {v:.4f}" if isinstance(v, float) else f"- {k}: {v}" for k,v in res.items()]) | |
| def assembly_tool_run(q: str) -> str: | |
| """ | |
| Ex.: "linha com 3 estacoes inter=1.0 tempos=1.0,1.2,1.5 T=2000" | |
| """ | |
| import re | |
| st = int(re.search(r"(\d+)\s*estac", q or "").group(1)) if re.search(r"(\d+)\s*estac", q or "") else 3 | |
| inter = float(re.search(r"(inter|interarrival)\s*=\s*([\d\.]+)", q or "").group(2)) if re.search(r"(inter|interarrival)\s*=\s*([\d\.]+)", q or "") else 1.1 | |
| T = float(re.search(r"(T|tempo|time)\s*=\s*([\d\.]+)", q or "").group(2)) if re.search(r"(T|tempo|time)\s*=\s*([\d\.]+)", q or "") else 1000 | |
| times_match = re.search(r"tempos\s*=\s*([\d\.,\s]+)", q or "") | |
| times = tuple([float(x.strip()) for x in times_match.group(1).split(",")]) if times_match else (1.0, 1.2, 1.5) | |
| res = simulate_assembly_line(stations=st, mean_service_times=times, inter_arrival=inter, sim_time=T) | |
| return f"Linha de produção (stations={st}, inter={inter}, T={T}, tempos={times}):\n" + "\n".join([f"- {k}: {v:.4f}" if isinstance(v, float) else f"- {k}: {v}" for k,v in res.items()]) | |
| def build_agent(): | |
| tools = [ | |
| Tool( | |
| name="PesquisarMateriais", | |
| func=search_docs, | |
| description="Busca trechos relevantes nos materiais locais do curso (ementa, notas, apostilas). Use quando a pergunta for sobre conteúdo das aulas." | |
| ), | |
| Tool( | |
| name="SimularMM1", | |
| func=mm1_tool_run, | |
| description="Roda uma simulação M/M/1. Parâmetros no texto: lambda, mu, tempo. Ex: 'simule mm1 com lambda=1.1 mu=1.5 tempo=2000'" | |
| ), | |
| Tool( | |
| name="SimularLinhaProducao", | |
| func=assembly_tool_run, | |
| description="Roda simulação de linha de produção em série. Parâmetros: N estações, inter, tempos, T. Ex: 'linha com 3 estacoes inter=1.0 tempos=1.2,1.3,1.1 T=2000'" | |
| ), | |
| ] | |
| system = """Você é um tutor de Python e SimPy para Engenharia de Produção. | |
| - Responda de forma objetiva e didática, em PT-BR. | |
| - Quando a pergunta for de conteúdo das aulas, consulte 'PesquisarMateriais' para fundamentar. | |
| - Quando pedirem simulação, use as ferramentas adequadas e cite os parâmetros adotados. | |
| - Inclua pequenos exemplos de código quando fizer sentido. | |
| - Se não souber, admita e sugira um caminho. | |
| """ | |
| prompt = PromptTemplate.from_template("""{system} | |
| Pergunta do aluno: {input} | |
| Pense passo a passo. Se precisar, use as Ferramentas. | |
| {agent_scratchpad} | |
| """).partial(system=system) | |
| llm = get_llm() | |
| agent = create_react_agent(llm=llm, tools=tools, prompt=prompt) | |
| executor = AgentExecutor(agent=agent, tools=tools, handle_parsing_errors=True, verbose=False, max_iterations=4) | |
| return executor | |
| # Pronto para uso programático | |
| executor_singleton = None | |
| def get_executor(): | |
| global executor_singleton | |
| if executor_singleton is None: | |
| executor_singleton = build_agent() | |
| return executor_singleton | |
| if __name__ == "__main__": | |
| ex = get_executor() | |
| resp = ex.invoke({"input": "Como funcionam eventos e env.process no SimPy?"}) | |
| print(resp["output"]) | |