structured-outputs.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { Ollama } from '../../src/index.js';
  2. import { z } from 'zod';
  3. import { zodToJsonSchema } from 'zod-to-json-schema';
  4. const ollama = new Ollama();
  5. // Define the schema for friend info
  6. const FriendInfoSchema = z.object({
  7. name: z.string(),
  8. age: z.number().int(),
  9. is_available: z.boolean()
  10. });
  11. // Define the schema for friend list
  12. const FriendListSchema = z.object({
  13. friends: z.array(FriendInfoSchema)
  14. });
  15. async function run() {
  16. // Convert the Zod schema to JSON Schema format
  17. const jsonSchema = zodToJsonSchema(FriendListSchema);
  18. // Can use manually defined schema directly
  19. // const schema = { 'type': 'object', 'properties': { 'friends': { 'type': 'array', 'items': { 'type': 'object', 'properties': { 'name': { 'type': 'string' }, 'age': { 'type': 'integer' }, 'is_available': { 'type': 'boolean' } }, 'required': ['name', 'age', 'is_available'] } } }, 'required': ['friends'] }
  20. const messages = [{
  21. role: 'user',
  22. 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'
  23. }];
  24. const response = await ollama.chat({
  25. model: 'llama3.1:8b',
  26. messages: messages,
  27. format: jsonSchema, // or format: schema
  28. options: {
  29. temperature: 0 // Make responses more deterministic
  30. }
  31. });
  32. // Parse and validate the response
  33. try {
  34. console.log('\n', response.message.content, '\n');
  35. const friendsResponse = FriendListSchema.parse(JSON.parse(response.message.content));
  36. console.log('\n', friendsResponse, '\n');
  37. } catch (error) {
  38. console.error("Generated invalid response:", error);
  39. }
  40. }
  41. run().catch(console.error);