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

Uploaded Python 3

File details

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

File metadata

  • Download URL: phichat-0.1.7.tar.gz
  • Upload date:
  • Size: 19.6 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.7.tar.gz
Algorithm Hash digest
SHA256 fabd330717704a59e5571546dace916d11dfb64357cf73d6554eabd30ba082fd
MD5 383e96803dd942eb3ddaca1419539515
BLAKE2b-256 fada3f9d0be14ced2a9eec7dca3c4391f7935de43aea308a8971b147c75c30a2

See more details on using hashes here.

Provenance

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

File metadata

  • Download URL: phichat-0.1.7-py3-none-any.whl
  • Upload date:
  • Size: 12.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.7-py3-none-any.whl
Algorithm Hash digest
SHA256 9d49c767b7095a491355f2b6e4ac89f4877721c67e146b7514d6f615ad675b83
MD5 759b4b224149e8a8d620269d4da236c0
BLAKE2b-256 3d0a4cd72b7dff9ec4f1c4f302037b37683c80b6249f0e27c3440375bbc478df

See more details on using hashes here.

Provenance

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