json-schema-pydantic-example.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # Usage:
  2. #! ./llama-server -m some-model.gguf &
  3. #! pip install pydantic
  4. #! python json-schema-pydantic-example.py
  5. from pydantic import BaseModel, TypeAdapter
  6. from annotated_types import MinLen
  7. from typing import Annotated, List, Optional
  8. import json, requests
  9. if True:
  10. def create_completion(*, response_model=None, endpoint="http://localhost:8080/v1/chat/completions", messages, **kwargs):
  11. '''
  12. Creates a chat completion using an OpenAI-compatible endpoint w/ JSON schema support
  13. (llama.cpp server, llama-cpp-python, Anyscale / Together...)
  14. The response_model param takes a type (+ supports Pydantic) and behaves just as w/ Instructor (see below)
  15. '''
  16. if response_model:
  17. type_adapter = TypeAdapter(response_model)
  18. schema = type_adapter.json_schema()
  19. messages = [{
  20. "role": "system",
  21. "content": f"You respond in JSON format with the following schema: {json.dumps(schema, indent=2)}"
  22. }] + messages
  23. response_format={"type": "json_object", "schema": schema}
  24. data = requests.post(endpoint, headers={"Content-Type": "application/json"},
  25. json=dict(messages=messages, response_format=response_format, **kwargs)).json()
  26. if 'error' in data:
  27. raise Exception(data['error']['message'])
  28. content = data["choices"][0]["message"]["content"]
  29. return type_adapter.validate_json(content) if type_adapter else content
  30. else:
  31. # This alternative branch uses Instructor + OpenAI client lib.
  32. # Instructor support streamed iterable responses, retry & more.
  33. # (see https://python.useinstructor.com/)
  34. #! pip install instructor openai
  35. import instructor, openai
  36. client = instructor.patch(
  37. openai.OpenAI(api_key="123", base_url="http://localhost:8080"),
  38. mode=instructor.Mode.JSON_SCHEMA)
  39. create_completion = client.chat.completions.create
  40. if __name__ == '__main__':
  41. class QAPair(BaseModel):
  42. question: str
  43. concise_answer: str
  44. justification: str
  45. stars: Annotated[int, Field(ge=1, le=5)]
  46. class PyramidalSummary(BaseModel):
  47. title: str
  48. summary: str
  49. question_answers: Annotated[List[QAPair], MinLen(2)]
  50. sub_sections: Optional[Annotated[List['PyramidalSummary'], MinLen(2)]]
  51. print("# Summary\n", create_completion(
  52. model="...",
  53. response_model=PyramidalSummary,
  54. messages=[{
  55. "role": "user",
  56. "content": f"""
  57. You are a highly efficient corporate document summarizer.
  58. Create a pyramidal summary of an imaginary internal document about our company processes
  59. (starting high-level, going down to each sub sections).
  60. Keep questions short, and answers even shorter (trivia / quizz style).
  61. """
  62. }]))