structured-outputs.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import ollama from 'ollama';
  2. import { z } from 'zod';
  3. import { zodToJsonSchema } from 'zod-to-json-schema';
  4. /*
  5. Ollama structured outputs capabilities
  6. It parses the response from the model into a structured JSON object using Zod
  7. */
  8. // Define the schema for friend info
  9. const FriendInfoSchema = z.object({
  10. name: z.string().describe('The name of the friend'),
  11. age: z.number().int().describe('The age of the friend'),
  12. is_available: z.boolean().describe('Whether the friend is available')
  13. });
  14. // Define the schema for friend list
  15. const FriendListSchema = z.object({
  16. friends: z.array(FriendInfoSchema).describe('An array of friends')
  17. });
  18. async function run(model: string) {
  19. // Convert the Zod schema to JSON Schema format
  20. const jsonSchema = zodToJsonSchema(FriendListSchema);
  21. /* Can use manually defined schema directly
  22. const schema = {
  23. 'type': 'object',
  24. 'properties': {
  25. 'friends': {
  26. 'type': 'array',
  27. 'items': {
  28. 'type': 'object',
  29. 'properties': {
  30. 'name': { 'type': 'string' },
  31. 'age': { 'type': 'integer' },
  32. 'is_available': { 'type': 'boolean' }
  33. },
  34. 'required': ['name', 'age', 'is_available']
  35. }
  36. }
  37. },
  38. 'required': ['friends']
  39. }
  40. */
  41. const messages = [{
  42. role: 'user',
  43. content: 'I have two friends. The first is Ollama 22 years old busy saving the world, and the second is Alonso 23 years old and wants to hang out. Return a list of friends in JSON format'
  44. }];
  45. const response = await ollama.chat({
  46. model: model,
  47. messages: messages,
  48. format: jsonSchema, // or format: schema
  49. options: {
  50. temperature: 0 // Make responses more deterministic
  51. }
  52. });
  53. // Parse and validate the response
  54. try {
  55. const friendsResponse = FriendListSchema.parse(JSON.parse(response.message.content));
  56. console.log(friendsResponse);
  57. } catch (error) {
  58. console.error("Generated invalid response:", error);
  59. }
  60. }
  61. run('llama3.1:8b').catch(console.error);