json-schema-pydantic-example.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. class PyramidalSummary(BaseModel):
  46. title: str
  47. summary: str
  48. question_answers: Annotated[List[QAPair], MinLen(2)]
  49. sub_sections: Optional[Annotated[List['PyramidalSummary'], MinLen(2)]]
  50. print("# Summary\n", create_completion(
  51. model="...",
  52. response_model=PyramidalSummary,
  53. messages=[{
  54. "role": "user",
  55. "content": f"""
  56. You are a highly efficient corporate document summarizer.
  57. Create a pyramidal summary of an imaginary internal document about our company processes
  58. (starting high-level, going down to each sub sections).
  59. Keep questions short, and answers even shorter (trivia / quizz style).
  60. """
  61. }]))