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)

[!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_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

# 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:

  1. Verificación Total: uv run pytest
  2. 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


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.2.4.tar.gz (23.7 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.2.4-py3-none-any.whl (13.3 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for phichat-0.2.4.tar.gz
Algorithm Hash digest
SHA256 554f60e5c12a3cebf5284ba17a2694dc673b4239dc6beaba776584ea7166152a
MD5 acf1c1e99d590837349a4c896e075b37
BLAKE2b-256 18627bcd3ce0ac0b86381d8b75c07921b2537ba8c4dd6b49bf633ba807719c0f

See more details on using hashes here.

Provenance

The following attestation bundles were made for phichat-0.2.4.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.2.4-py3-none-any.whl.

File metadata

  • Download URL: phichat-0.2.4-py3-none-any.whl
  • Upload date:
  • Size: 13.3 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.2.4-py3-none-any.whl
Algorithm Hash digest
SHA256 8061960c15eeda3225d8463dcf869f97d44015ead1731426a81ee61f3597bb5f
MD5 dcaecdefac21e4671818dd54b645058e
BLAKE2b-256 21b8e7c2a60ccc6c3c10c66ce4e6c54232e964573fa04a95dba0823a0b69f9ec

See more details on using hashes here.

Provenance

The following attestation bundles were made for phichat-0.2.4-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