|
| 1 | +""" |
| 2 | +Example demonstrating how to use structured outputs with a pipe. |
| 3 | +""" |
| 4 | + |
| 5 | +import json |
| 6 | +import os |
| 7 | +from typing import List |
| 8 | + |
| 9 | +from dotenv import load_dotenv |
| 10 | +from pydantic import BaseModel, Field |
| 11 | + |
| 12 | +from langbase import Langbase |
| 13 | + |
| 14 | + |
| 15 | +# Define the Strucutred Output JSON schema with Pydantic |
| 16 | +class Step(BaseModel): |
| 17 | + explanation: str |
| 18 | + output: str |
| 19 | + |
| 20 | + |
| 21 | +class MathReasoning(BaseModel): |
| 22 | + steps: List[Step] |
| 23 | + final_answer: str = Field(alias="final_answer") |
| 24 | + |
| 25 | + |
| 26 | +def create_math_tutor_pipe(langbase: Langbase): |
| 27 | + json_schema = MathReasoning.model_json_schema() |
| 28 | + |
| 29 | + pipe = langbase.pipes.create( |
| 30 | + name="math-tutor", |
| 31 | + model="openai:gpt-4o", |
| 32 | + upsert=True, |
| 33 | + messages=[ |
| 34 | + { |
| 35 | + "role": "system", |
| 36 | + "content": "You are a helpful math tutor. Guide the user through the solution step by step.", |
| 37 | + }, |
| 38 | + ], |
| 39 | + json=True, |
| 40 | + response_format={ |
| 41 | + "type": "json_schema", |
| 42 | + "json_schema": { |
| 43 | + "name": "math_reasoning", |
| 44 | + "schema": json_schema, |
| 45 | + }, |
| 46 | + }, |
| 47 | + ) |
| 48 | + |
| 49 | + print("✅ Math Tutor pipe created:", json.dumps(pipe, indent=2)) |
| 50 | + |
| 51 | + |
| 52 | +def run_math_tutor_pipe(langbase: Langbase, question: str): |
| 53 | + response = langbase.pipes.run( |
| 54 | + name="math-tutor", |
| 55 | + messages=[{"role": "user", "content": question}], |
| 56 | + stream=False, |
| 57 | + ) |
| 58 | + |
| 59 | + # Parse and validate the response using Pydantic |
| 60 | + solution = MathReasoning.model_validate_json(response["completion"]) |
| 61 | + |
| 62 | + print("✅ Structured Output Response:") |
| 63 | + print("=" * 50) |
| 64 | + |
| 65 | + for i, step in enumerate(solution.steps, 1): |
| 66 | + print(f"Step {i}:") |
| 67 | + print(f" Explanation: {step.explanation}") |
| 68 | + print(f" Output: {step.output}") |
| 69 | + print() |
| 70 | + |
| 71 | + print(f"Final Answer: {solution.final_answer}") |
| 72 | + print("=" * 50) |
| 73 | + |
| 74 | + |
| 75 | +def main(): |
| 76 | + load_dotenv() |
| 77 | + |
| 78 | + if not os.getenv("LANGBASE_API_KEY"): |
| 79 | + print("❌ Missing LANGBASE_API_KEY in environment variables.") |
| 80 | + exit(1) |
| 81 | + |
| 82 | + langbase = Langbase(api_key=os.getenv("LANGBASE_API_KEY")) |
| 83 | + |
| 84 | + # Run this only once to create the pipe. Uncomment if it's your first time setting it up. |
| 85 | + create_math_tutor_pipe(langbase) |
| 86 | + run_math_tutor_pipe(langbase, "How can I solve 8x + 22 = -23?") |
| 87 | + |
| 88 | + |
| 89 | +if __name__ == "__main__": |
| 90 | + main() |
0 commit comments