Wrapper de LangChain para Phi-4 con soporte nativo de Tool Calling y MCP
Project description
PhiChat
Wrapper de LangChain para Phi-4 (14B) y la familia Phi de Microsoft vía Ollama, con soporte robusto y nativo de tool calling.
Phi-4 genera y reconoce tool calls y responses mediante etiquetas propietarias (<|tool_call|> y <|tool_response|>). PhiChat normaliza este protocolo automáticamente para que cualquier flujo LCEL, agente o grafo funcione de forma transparente.
Instalación
Requiere Ollama corriendo localmente.
ollama pull phi4
Vía Pip
pip install phichat
[!NOTE] Aunque está optimizado para Phi-4, este wrapper es compatible con otros modelos de la familia Phi (ej.
phi4-mini,phi3.5-mini) simplemente cambiando el parámetromodelal inicializar.
Con uv (Recomendado)
uv add phichat
Inicio rápido
from PhiChat import ChatPhi
from langchain_core.tools import tool
@tool
def get_weather(city: str) -> str:
"""Obtiene el clima de una ciudad."""
return f"Soleado en {city}, 25 grados."
llm = ChatPhi()
chain = llm.bind_tools([get_weather])
response = chain.invoke("¿Cómo está el clima en Madrid?")
print(response.content)
print(response.tool_calls)
[!TIP] Para una guía detallada sobre cómo integrar PhiChat con LangGraph, MCP y mejores prácticas de ingeniería, consulta nuestra Guía de Integración Completa.
Modelos recomendados
| Modelo | Tamaño | Características |
|---|---|---|
| phi4 (default) | 10 GB | Estado del arte, excelente razonamiento y herramientas |
| phi4-mini | 4 GB | Más rápido, ideal para tareas simples |
| phi3.5-mini | 4 GB | Muy rápido, pero propenso a errores en herramientas |
Para cambiar de modelo:
llm = ChatPhi(model="phi4-mini:latest")
Características principales
- Bypass de Ollama 400: Soluciona el error de "Native Tooling" mediante inyección manual de esquemas.
- Normalización de Tool Calls: Extrae y convierte el JSON de Phi-4 al formato estándar
tool_calls. - Memoria Agéntica: Re-inyección automática del historial para evitar bucles infinitos.
- Salida Estructurada: Soporte nativo para
with_structured_outputen modo JSON. - Streaming: Filtrado de tokens de control (
<|tool_call|>) para streams limpios.
Integración con LangGraph
from langgraph.prebuilt import create_react_agent
from langgraph.checkpoint.memory import MemorySaver
from PhiChat import ChatPhi
llm = ChatPhi(model="phi4", temperature=0)
agent = create_react_agent(
model=llm,
tools=[get_weather],
checkpointer=MemorySaver()
)
config = {"configurable": {"thread_id": "1"}}
result = agent.invoke(
{"messages": [{"role": "user", "content": "¿Clima en Berlín?"}]},
config=config
)
Ingeniería y Mejores Prácticas
El proyecto PhiChat sigue estándares estrictos de ingeniería de software:
- Estándares Python: Adherencia a PEP 8, PEP 484 (tipado estático) y PEP 257 (documentación).
- Validación Continua: Suite de pruebas completa para asegurar la integridad del protocolo de etiquetas.
- Tipado Estricto: Uso de Type Hints en todas las funciones y clases.
- Resiliencia: Manejo de excepciones específicas para modelos locales.
Testing
Garantiza la integridad de los protocolos de comunicación y la ejecución agéntica.
# Ejecutar todos los tests
uv run pytest
# Ejecutar un test específico (ej. los parsers)
uv run pytest test/test_parsers.py
Desarrollo con Skills (Phi Protocol)
Este proyecto utiliza un sistema de Skills para estandarizar la ingeniería de software. Puedes encontrar la guía completa de operación en skills/SKILL.md.
Mandato de Calidad
Cualquier contribución debe cumplir con el Protocolo Phi:
- Verificación Total:
uv run pytest - Estándares: Adherencia estricta a PEP 8, 484 y 257.
Desarrollado para optimizar el uso de modelos Microsoft Phi en entornos de producción con LangChain.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file phichat-0.3.0.tar.gz.
File metadata
- Download URL: phichat-0.3.0.tar.gz
- Upload date:
- Size: 24.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ce1d09bf104f663564ca06a82a9446b818d1903cc13a108c7ab9d5df6076319d
|
|
| MD5 |
e87e7f93920ec05c8cb3fe3479d51ab3
|
|
| BLAKE2b-256 |
ac08a3cdc3c2d958b8e9c001d17caee4b6905d2d9689ee5820837266b705425a
|
Provenance
The following attestation bundles were made for phichat-0.3.0.tar.gz:
Publisher:
publish.yml on CarlosMaroRuiz/PhiChat
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
phichat-0.3.0.tar.gz -
Subject digest:
ce1d09bf104f663564ca06a82a9446b818d1903cc13a108c7ab9d5df6076319d - Sigstore transparency entry: 1487257155
- Sigstore integration time:
-
Permalink:
CarlosMaroRuiz/PhiChat@bee8d53887326d4588b766dccefc31a93e5f669d -
Branch / Tag:
refs/tags/v0.3.0 - Owner: https://github.com/CarlosMaroRuiz
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@bee8d53887326d4588b766dccefc31a93e5f669d -
Trigger Event:
push
-
Statement type:
File details
Details for the file phichat-0.3.0-py3-none-any.whl.
File metadata
- Download URL: phichat-0.3.0-py3-none-any.whl
- Upload date:
- Size: 13.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7db490f1a968b8a4db932fb39322d09eb3ee796de3b4933f8e3d4dcec84fce85
|
|
| MD5 |
6bc372fa2f98afdcc5c7fbf711a0fcb6
|
|
| BLAKE2b-256 |
720e3842122f52fbca76e51db9f247db7290b15120f0638c51845439228565e5
|
Provenance
The following attestation bundles were made for phichat-0.3.0-py3-none-any.whl:
Publisher:
publish.yml on CarlosMaroRuiz/PhiChat
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
phichat-0.3.0-py3-none-any.whl -
Subject digest:
7db490f1a968b8a4db932fb39322d09eb3ee796de3b4933f8e3d4dcec84fce85 - Sigstore transparency entry: 1487257158
- Sigstore integration time:
-
Permalink:
CarlosMaroRuiz/PhiChat@bee8d53887326d4588b766dccefc31a93e5f669d -
Branch / Tag:
refs/tags/v0.3.0 - Owner: https://github.com/CarlosMaroRuiz
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@bee8d53887326d4588b766dccefc31a93e5f669d -
Trigger Event:
push
-
Statement type: