Skip to main content

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ámetro model al 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)

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_output en 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

Desarrollado para optimizar el uso de modelos Microsoft Phi en entornos de producción con LangChain.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

phichat-0.1.2.tar.gz (18.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

phichat-0.1.2-py3-none-any.whl (11.8 kB view details)

Uploaded Python 3

File details

Details for the file phichat-0.1.2.tar.gz.

File metadata

  • Download URL: phichat-0.1.2.tar.gz
  • Upload date:
  • Size: 18.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for phichat-0.1.2.tar.gz
Algorithm Hash digest
SHA256 55714344198e94eff58761d0a2bec673990917216952b2147a0352a14f161c51
MD5 b635b813b14fe6dff881d0796e7cfff6
BLAKE2b-256 276463ad9b8f20a5fba426900ea6eec3db122b33e2dc4265f10ee5498f4f4102

See more details on using hashes here.

Provenance

The following attestation bundles were made for phichat-0.1.2.tar.gz:

Publisher: publish.yml on CarlosMaroRuiz/PhiChat

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file phichat-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: phichat-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 11.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for phichat-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 d5b0331b53b8892518b68dfefa78f9c943944854e1d82a048a6919453d6d2d6f
MD5 478cefa1ef54717c29fb5fc2476d185d
BLAKE2b-256 86725f76a6610794dd8777bce79a54575d218e12395f7f01d49675edc9746e5b

See more details on using hashes here.

Provenance

The following attestation bundles were made for phichat-0.1.2-py3-none-any.whl:

Publisher: publish.yml on CarlosMaroRuiz/PhiChat

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page