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.3.tar.gz (19.0 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.3-py3-none-any.whl (12.1 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: phichat-0.1.3.tar.gz
  • Upload date:
  • Size: 19.0 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.3.tar.gz
Algorithm Hash digest
SHA256 d649730685546938a4d9ebad4c7cfd71427216937483eaa7cdeffbab3af80446
MD5 3b5e6961c58b9d1914fdb71dc00a4b23
BLAKE2b-256 2a6c4f883b5f9775794e53d452df1c855aaffef6193726343f6f371187038036

See more details on using hashes here.

Provenance

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

File metadata

  • Download URL: phichat-0.1.3-py3-none-any.whl
  • Upload date:
  • Size: 12.1 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.3-py3-none-any.whl
Algorithm Hash digest
SHA256 c3edd9caa40ad3a89d709d1d7122fd69a7ac06df4ac67749814e4d3fdbc029cd
MD5 f60cddaa54e4dd9fc2f6c3170d3cfbd2
BLAKE2b-256 835bcf6cdbf57ba76a82e5ac058146092b99039e2b0ae452a0b7a23e27541979

See more details on using hashes here.

Provenance

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