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.1.6.tar.gz (19.4 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.6-py3-none-any.whl (12.6 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: phichat-0.1.6.tar.gz
  • Upload date:
  • Size: 19.4 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.6.tar.gz
Algorithm Hash digest
SHA256 0e2e98947189b8ae8a876737c405fd51ed321ab3a12e539b3434d4a4a06c114f
MD5 0869ee85312a7a16474f373171c67c04
BLAKE2b-256 8f5983d5decec2e80d07fa8b522386a701b76f30acf08a0dc60dcb46657cc15a

See more details on using hashes here.

Provenance

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

File metadata

  • Download URL: phichat-0.1.6-py3-none-any.whl
  • Upload date:
  • Size: 12.6 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.6-py3-none-any.whl
Algorithm Hash digest
SHA256 b689e5a56c2418dc942f443f83e10587587c42bf4b32fd66310083a88b50a404
MD5 3629fab22a5194236348e55f05dcd53b
BLAKE2b-256 40130fb6ebca8637e94dd5db03a96d20eb6185589a2ec83a91ec4a972f5e5b33

See more details on using hashes here.

Provenance

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