Spaces:
				
			
			
	
			
			
		Sleeping
		
	
	
	
			
			
	
	
	
	
		
		
		Sleeping
		
	Commit 
							
							·
						
						fa01d80
	
0
								Parent(s):
							
							
add basic inference proxy
Browse files- .gitignore +175 -0
- README.md +48 -0
- bun.lockb +0 -0
- example.ts +28 -0
- index.ts +501 -0
- package.json +18 -0
- tsconfig.json +27 -0
    	
        .gitignore
    ADDED
    
    | @@ -0,0 +1,175 @@ | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | 
|  | |
| 1 | 
            +
            # Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore
         | 
| 2 | 
            +
             | 
| 3 | 
            +
            # Logs
         | 
| 4 | 
            +
             | 
| 5 | 
            +
            logs
         | 
| 6 | 
            +
            _.log
         | 
| 7 | 
            +
            npm-debug.log_
         | 
| 8 | 
            +
            yarn-debug.log*
         | 
| 9 | 
            +
            yarn-error.log*
         | 
| 10 | 
            +
            lerna-debug.log*
         | 
| 11 | 
            +
            .pnpm-debug.log*
         | 
| 12 | 
            +
             | 
| 13 | 
            +
            # Caches
         | 
| 14 | 
            +
             | 
| 15 | 
            +
            .cache
         | 
| 16 | 
            +
             | 
| 17 | 
            +
            # Diagnostic reports (https://nodejs.org/api/report.html)
         | 
| 18 | 
            +
             | 
| 19 | 
            +
            report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
         | 
| 20 | 
            +
             | 
| 21 | 
            +
            # Runtime data
         | 
| 22 | 
            +
             | 
| 23 | 
            +
            pids
         | 
| 24 | 
            +
            _.pid
         | 
| 25 | 
            +
            _.seed
         | 
| 26 | 
            +
            *.pid.lock
         | 
| 27 | 
            +
             | 
| 28 | 
            +
            # Directory for instrumented libs generated by jscoverage/JSCover
         | 
| 29 | 
            +
             | 
| 30 | 
            +
            lib-cov
         | 
| 31 | 
            +
             | 
| 32 | 
            +
            # Coverage directory used by tools like istanbul
         | 
| 33 | 
            +
             | 
| 34 | 
            +
            coverage
         | 
| 35 | 
            +
            *.lcov
         | 
| 36 | 
            +
             | 
| 37 | 
            +
            # nyc test coverage
         | 
| 38 | 
            +
             | 
| 39 | 
            +
            .nyc_output
         | 
| 40 | 
            +
             | 
| 41 | 
            +
            # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
         | 
| 42 | 
            +
             | 
| 43 | 
            +
            .grunt
         | 
| 44 | 
            +
             | 
| 45 | 
            +
            # Bower dependency directory (https://bower.io/)
         | 
| 46 | 
            +
             | 
| 47 | 
            +
            bower_components
         | 
| 48 | 
            +
             | 
| 49 | 
            +
            # node-waf configuration
         | 
| 50 | 
            +
             | 
| 51 | 
            +
            .lock-wscript
         | 
| 52 | 
            +
             | 
| 53 | 
            +
            # Compiled binary addons (https://nodejs.org/api/addons.html)
         | 
| 54 | 
            +
             | 
| 55 | 
            +
            build/Release
         | 
| 56 | 
            +
             | 
| 57 | 
            +
            # Dependency directories
         | 
| 58 | 
            +
             | 
| 59 | 
            +
            node_modules/
         | 
| 60 | 
            +
            jspm_packages/
         | 
| 61 | 
            +
             | 
| 62 | 
            +
            # Snowpack dependency directory (https://snowpack.dev/)
         | 
| 63 | 
            +
             | 
| 64 | 
            +
            web_modules/
         | 
| 65 | 
            +
             | 
| 66 | 
            +
            # TypeScript cache
         | 
| 67 | 
            +
             | 
| 68 | 
            +
            *.tsbuildinfo
         | 
| 69 | 
            +
             | 
| 70 | 
            +
            # Optional npm cache directory
         | 
| 71 | 
            +
             | 
| 72 | 
            +
            .npm
         | 
| 73 | 
            +
             | 
| 74 | 
            +
            # Optional eslint cache
         | 
| 75 | 
            +
             | 
| 76 | 
            +
            .eslintcache
         | 
| 77 | 
            +
             | 
| 78 | 
            +
            # Optional stylelint cache
         | 
| 79 | 
            +
             | 
| 80 | 
            +
            .stylelintcache
         | 
| 81 | 
            +
             | 
| 82 | 
            +
            # Microbundle cache
         | 
| 83 | 
            +
             | 
| 84 | 
            +
            .rpt2_cache/
         | 
| 85 | 
            +
            .rts2_cache_cjs/
         | 
| 86 | 
            +
            .rts2_cache_es/
         | 
| 87 | 
            +
            .rts2_cache_umd/
         | 
| 88 | 
            +
             | 
| 89 | 
            +
            # Optional REPL history
         | 
| 90 | 
            +
             | 
| 91 | 
            +
            .node_repl_history
         | 
| 92 | 
            +
             | 
| 93 | 
            +
            # Output of 'npm pack'
         | 
| 94 | 
            +
             | 
| 95 | 
            +
            *.tgz
         | 
| 96 | 
            +
             | 
| 97 | 
            +
            # Yarn Integrity file
         | 
| 98 | 
            +
             | 
| 99 | 
            +
            .yarn-integrity
         | 
| 100 | 
            +
             | 
| 101 | 
            +
            # dotenv environment variable files
         | 
| 102 | 
            +
             | 
| 103 | 
            +
            .env
         | 
| 104 | 
            +
            .env.development.local
         | 
| 105 | 
            +
            .env.test.local
         | 
| 106 | 
            +
            .env.production.local
         | 
| 107 | 
            +
            .env.local
         | 
| 108 | 
            +
             | 
| 109 | 
            +
            # parcel-bundler cache (https://parceljs.org/)
         | 
| 110 | 
            +
             | 
| 111 | 
            +
            .parcel-cache
         | 
| 112 | 
            +
             | 
| 113 | 
            +
            # Next.js build output
         | 
| 114 | 
            +
             | 
| 115 | 
            +
            .next
         | 
| 116 | 
            +
            out
         | 
| 117 | 
            +
             | 
| 118 | 
            +
            # Nuxt.js build / generate output
         | 
| 119 | 
            +
             | 
| 120 | 
            +
            .nuxt
         | 
| 121 | 
            +
            dist
         | 
| 122 | 
            +
             | 
| 123 | 
            +
            # Gatsby files
         | 
| 124 | 
            +
             | 
| 125 | 
            +
            # Comment in the public line in if your project uses Gatsby and not Next.js
         | 
| 126 | 
            +
             | 
| 127 | 
            +
            # https://nextjs.org/blog/next-9-1#public-directory-support
         | 
| 128 | 
            +
             | 
| 129 | 
            +
            # public
         | 
| 130 | 
            +
             | 
| 131 | 
            +
            # vuepress build output
         | 
| 132 | 
            +
             | 
| 133 | 
            +
            .vuepress/dist
         | 
| 134 | 
            +
             | 
| 135 | 
            +
            # vuepress v2.x temp and cache directory
         | 
| 136 | 
            +
             | 
| 137 | 
            +
            .temp
         | 
| 138 | 
            +
             | 
| 139 | 
            +
            # Docusaurus cache and generated files
         | 
| 140 | 
            +
             | 
| 141 | 
            +
            .docusaurus
         | 
| 142 | 
            +
             | 
| 143 | 
            +
            # Serverless directories
         | 
| 144 | 
            +
             | 
| 145 | 
            +
            .serverless/
         | 
| 146 | 
            +
             | 
| 147 | 
            +
            # FuseBox cache
         | 
| 148 | 
            +
             | 
| 149 | 
            +
            .fusebox/
         | 
| 150 | 
            +
             | 
| 151 | 
            +
            # DynamoDB Local files
         | 
| 152 | 
            +
             | 
| 153 | 
            +
            .dynamodb/
         | 
| 154 | 
            +
             | 
| 155 | 
            +
            # TernJS port file
         | 
| 156 | 
            +
             | 
| 157 | 
            +
            .tern-port
         | 
| 158 | 
            +
             | 
| 159 | 
            +
            # Stores VSCode versions used for testing VSCode extensions
         | 
| 160 | 
            +
             | 
| 161 | 
            +
            .vscode-test
         | 
| 162 | 
            +
             | 
| 163 | 
            +
            # yarn v2
         | 
| 164 | 
            +
             | 
| 165 | 
            +
            .yarn/cache
         | 
| 166 | 
            +
            .yarn/unplugged
         | 
| 167 | 
            +
            .yarn/build-state.yml
         | 
| 168 | 
            +
            .yarn/install-state.gz
         | 
| 169 | 
            +
            .pnp.*
         | 
| 170 | 
            +
             | 
| 171 | 
            +
            # IntelliJ based IDEs
         | 
| 172 | 
            +
            .idea
         | 
| 173 | 
            +
             | 
| 174 | 
            +
            # Finder (MacOS) folder config
         | 
| 175 | 
            +
            .DS_Store
         | 
    	
        README.md
    ADDED
    
    | @@ -0,0 +1,48 @@ | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | 
|  | |
| 1 | 
            +
            # inference-proxy
         | 
| 2 | 
            +
             | 
| 3 | 
            +
            Lightweight proxy to store LLM traces in a Hugging Face Dataset.
         | 
| 4 | 
            +
             | 
| 5 | 
            +
            ### How it works
         | 
| 6 | 
            +
             | 
| 7 | 
            +
            This API acts as a proxy for OpenAPI endpoints. You can specify a couple of variables:
         | 
| 8 | 
            +
             | 
| 9 | 
            +
            - `BATCH_SIZE_LIMIT` - the maximum batch size before pushing to dataset
         | 
| 10 | 
            +
            - `BATCH_TIME_LIMIT` - the amount of time before pushing to dataset
         | 
| 11 | 
            +
             | 
| 12 | 
            +
            ### Required Environment Variables
         | 
| 13 | 
            +
             | 
| 14 | 
            +
            - `HF_ACCESS_TOKEN` - HF Access Token
         | 
| 15 | 
            +
            - `USER_NAME` - Used to ensure we only process requests from the user
         | 
| 16 | 
            +
             | 
| 17 | 
            +
            ### Example
         | 
| 18 | 
            +
             | 
| 19 | 
            +
            ```js
         | 
| 20 | 
            +
            import { OpenAI } from "openai";
         | 
| 21 | 
            +
             | 
| 22 | 
            +
            const client = new OpenAI({
         | 
| 23 | 
            +
            	baseURL: "http://localhost:4040/fireworks-ai/inference/v1", 
         | 
| 24 | 
            +
            	apiKey: process.env.HF_API_KEY,
         | 
| 25 | 
            +
            });
         | 
| 26 | 
            +
             | 
| 27 | 
            +
            let out = "";
         | 
| 28 | 
            +
             | 
| 29 | 
            +
            const stream = await client.chat.completions.create({
         | 
| 30 | 
            +
                model: "accounts/fireworks/models/deepseek-v3",
         | 
| 31 | 
            +
                messages: [
         | 
| 32 | 
            +
                    {
         | 
| 33 | 
            +
                        role: "user",
         | 
| 34 | 
            +
                        content: "What is the capital of France?",
         | 
| 35 | 
            +
                    },
         | 
| 36 | 
            +
                ],
         | 
| 37 | 
            +
                stream: true,
         | 
| 38 | 
            +
                max_tokens: 500,
         | 
| 39 | 
            +
            });
         | 
| 40 | 
            +
             | 
| 41 | 
            +
            for await (const chunk of stream) {
         | 
| 42 | 
            +
            	if (chunk.choices && chunk.choices.length > 0) {
         | 
| 43 | 
            +
            		const newContent = chunk.choices[0].delta.content;
         | 
| 44 | 
            +
            		out += newContent;
         | 
| 45 | 
            +
            		console.log(newContent);
         | 
| 46 | 
            +
            	}  
         | 
| 47 | 
            +
            }
         | 
| 48 | 
            +
            ```
         | 
    	
        bun.lockb
    ADDED
    
    | Binary file (19.4 kB). View file | 
|  | 
    	
        example.ts
    ADDED
    
    | @@ -0,0 +1,28 @@ | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | 
|  | |
| 1 | 
            +
            import { OpenAI } from "openai";
         | 
| 2 | 
            +
             | 
| 3 | 
            +
            const client = new OpenAI({
         | 
| 4 | 
            +
            	baseURL: "http://localhost:4040/fireworks-ai/inference/v1",
         | 
| 5 | 
            +
            	apiKey: process.env.HF_API_KEY,
         | 
| 6 | 
            +
            });
         | 
| 7 | 
            +
             | 
| 8 | 
            +
            let out = "";
         | 
| 9 | 
            +
             | 
| 10 | 
            +
            const stream = await client.chat.completions.create({
         | 
| 11 | 
            +
                model: "accounts/fireworks/models/deepseek-v3",
         | 
| 12 | 
            +
                messages: [
         | 
| 13 | 
            +
                    {
         | 
| 14 | 
            +
                        role: "user",
         | 
| 15 | 
            +
                        content: "What is the capital of France?",
         | 
| 16 | 
            +
                    },
         | 
| 17 | 
            +
                ],
         | 
| 18 | 
            +
                stream: true,
         | 
| 19 | 
            +
                max_tokens: 500,
         | 
| 20 | 
            +
            });
         | 
| 21 | 
            +
             | 
| 22 | 
            +
            for await (const chunk of stream) {
         | 
| 23 | 
            +
            	if (chunk.choices && chunk.choices.length > 0) {
         | 
| 24 | 
            +
            		const newContent = chunk.choices[0].delta.content;
         | 
| 25 | 
            +
            		out += newContent;
         | 
| 26 | 
            +
            		console.log(newContent);
         | 
| 27 | 
            +
            	}  
         | 
| 28 | 
            +
            }
         | 
    	
        index.ts
    ADDED
    
    | @@ -0,0 +1,501 @@ | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | 
|  | |
| 1 | 
            +
            import { Hono } from 'hono';
         | 
| 2 | 
            +
            import { stream } from 'hono/streaming';
         | 
| 3 | 
            +
            import type { StatusCode } from 'hono/utils/http-status';
         | 
| 4 | 
            +
            import { existsSync, mkdirSync, writeFileSync, readFileSync, unlinkSync } from 'fs';
         | 
| 5 | 
            +
            import { join, basename, resolve } from 'path';
         | 
| 6 | 
            +
            import { uploadFiles, checkRepoAccess, createRepo,whoAmI } from '@huggingface/hub';
         | 
| 7 | 
            +
            import type { RepoDesignation } from '@huggingface/hub';
         | 
| 8 | 
            +
             | 
| 9 | 
            +
            const app = new Hono();
         | 
| 10 | 
            +
             | 
| 11 | 
            +
            const TARGET_BASE_URL = process.env.TARGET_BASE_URL || "https://router.huggingface.co";
         | 
| 12 | 
            +
            const PORT = parseInt(process.env.PORT || '4040', 10);
         | 
| 13 | 
            +
            const LOGS_DIR = process.env.LOGS_DIR || './logs';
         | 
| 14 | 
            +
             | 
| 15 | 
            +
            const HF_ACCESS_TOKEN = process.env.HF_API_KEY || '';
         | 
| 16 | 
            +
            const DATASET_PRIVATE = (process.env.DATASET_PRIVATE || 'false').toLowerCase() === 'false';
         | 
| 17 | 
            +
             | 
| 18 | 
            +
            /* 
         | 
| 19 | 
            +
                USER_NAME - the name of the user to use for the dataset
         | 
| 20 | 
            +
                This will be used to invalidate requests that are not from the user
         | 
| 21 | 
            +
            */
         | 
| 22 | 
            +
            const USER_NAME = process.env.USER_NAME || 'cfahlgren1';
         | 
| 23 | 
            +
             | 
| 24 | 
            +
            if (!HF_ACCESS_TOKEN) {
         | 
| 25 | 
            +
              console.error('Please set HF_API_KEY in environment variable');
         | 
| 26 | 
            +
              process.exit(1);
         | 
| 27 | 
            +
            }
         | 
| 28 | 
            +
             | 
| 29 | 
            +
            if (!USER_NAME) {
         | 
| 30 | 
            +
              console.error('Please set USER_NAME in environment variable');
         | 
| 31 | 
            +
              process.exit(1);
         | 
| 32 | 
            +
            }
         | 
| 33 | 
            +
             | 
| 34 | 
            +
             | 
| 35 | 
            +
            /*
         | 
| 36 | 
            +
                BATCH_SIZE_LIMIT - the maximum batch size before pushing to dataset
         | 
| 37 | 
            +
                BATCH_TIME_LIMIT - the amount of time before pushing to dataset
         | 
| 38 | 
            +
             | 
| 39 | 
            +
                We will push to dataset for whatever is reached first.
         | 
| 40 | 
            +
            */
         | 
| 41 | 
            +
            const BATCH_SIZE_LIMIT = parseInt(process.env.BATCH_SIZE_LIMIT || '100', 10);
         | 
| 42 | 
            +
            const BATCH_TIME_LIMIT = parseInt(process.env.BATCH_TIME_LIMIT || '1', 10); // 1 minute default
         | 
| 43 | 
            +
             | 
| 44 | 
            +
            if (!existsSync(LOGS_DIR)) {
         | 
| 45 | 
            +
              mkdirSync(LOGS_DIR, { recursive: true });
         | 
| 46 | 
            +
            }
         | 
| 47 | 
            +
             | 
| 48 | 
            +
            async function checkUserAccess(username: string): Promise<boolean> {
         | 
| 49 | 
            +
              const response = await whoAmI({ accessToken: HF_ACCESS_TOKEN });
         | 
| 50 | 
            +
              return response.name === username;
         | 
| 51 | 
            +
            }
         | 
| 52 | 
            +
             | 
| 53 | 
            +
            const requestTraces: {
         | 
| 54 | 
            +
              model?: string;
         | 
| 55 | 
            +
              timestamp_start: string;
         | 
| 56 | 
            +
              timestamp_end?: string;
         | 
| 57 | 
            +
              messages?: any[];
         | 
| 58 | 
            +
              prompt_tokens?: number;
         | 
| 59 | 
            +
              completion_tokens?: number;
         | 
| 60 | 
            +
              response?: string;
         | 
| 61 | 
            +
              arguments?: any;
         | 
| 62 | 
            +
              provider?: string;
         | 
| 63 | 
            +
              duration_ms?: number;
         | 
| 64 | 
            +
            }[] = [];
         | 
| 65 | 
            +
             | 
| 66 | 
            +
            let lastTraceBatchTime = Date.now();
         | 
| 67 | 
            +
             | 
| 68 | 
            +
            async function checkDatasetExists(datasetName: string): Promise<boolean> {
         | 
| 69 | 
            +
              try {
         | 
| 70 | 
            +
                if (!HF_ACCESS_TOKEN) {
         | 
| 71 | 
            +
                  console.warn('HF_ACCESS_TOKEN not set, skipping dataset check');
         | 
| 72 | 
            +
                  return false;
         | 
| 73 | 
            +
                }
         | 
| 74 | 
            +
                
         | 
| 75 | 
            +
                const repo: RepoDesignation = { type: 'dataset', name: datasetName };
         | 
| 76 | 
            +
                await checkRepoAccess({ repo, accessToken: HF_ACCESS_TOKEN });
         | 
| 77 | 
            +
                return true;
         | 
| 78 | 
            +
              } catch (error) {
         | 
| 79 | 
            +
                return false;
         | 
| 80 | 
            +
              }
         | 
| 81 | 
            +
            }
         | 
| 82 | 
            +
             | 
| 83 | 
            +
            async function createDataset(datasetName: string): Promise<boolean> {
         | 
| 84 | 
            +
              try {
         | 
| 85 | 
            +
                if (!HF_ACCESS_TOKEN) {
         | 
| 86 | 
            +
                  console.warn('HF_ACCESS_TOKEN not set, skipping dataset creation');
         | 
| 87 | 
            +
                  return false;
         | 
| 88 | 
            +
                }
         | 
| 89 | 
            +
                
         | 
| 90 | 
            +
                const repo: RepoDesignation = { type: 'dataset', name: datasetName };
         | 
| 91 | 
            +
                await createRepo({ 
         | 
| 92 | 
            +
                  repo, 
         | 
| 93 | 
            +
                  accessToken: HF_ACCESS_TOKEN, 
         | 
| 94 | 
            +
                  private: DATASET_PRIVATE,
         | 
| 95 | 
            +
                  files: [
         | 
| 96 | 
            +
                    {
         | 
| 97 | 
            +
                      path: 'README.md',
         | 
| 98 | 
            +
                      content: new Blob([`---
         | 
| 99 | 
            +
            tags:
         | 
| 100 | 
            +
            - inference-proxy
         | 
| 101 | 
            +
            ---`]),
         | 
| 102 | 
            +
                    }
         | 
| 103 | 
            +
                  ]
         | 
| 104 | 
            +
                });
         | 
| 105 | 
            +
                return true;
         | 
| 106 | 
            +
              } catch (error) {
         | 
| 107 | 
            +
                console.error('Error creating dataset:', error);
         | 
| 108 | 
            +
                return false;
         | 
| 109 | 
            +
              }
         | 
| 110 | 
            +
            }
         | 
| 111 | 
            +
             | 
| 112 | 
            +
            function writeTraceToFile(trace: typeof requestTraces[0]): string {
         | 
| 113 | 
            +
              try {
         | 
| 114 | 
            +
                const timestamp = new Date(trace.timestamp_start).getTime();
         | 
| 115 | 
            +
                const model = trace.model || 'unknown';
         | 
| 116 | 
            +
                const filename = `${timestamp}_${model.replace(/\//g, '_')}.json`;
         | 
| 117 | 
            +
                const filePath = join(LOGS_DIR, filename);
         | 
| 118 | 
            +
                
         | 
| 119 | 
            +
                writeFileSync(filePath, JSON.stringify(trace, null, 2));
         | 
| 120 | 
            +
                return filePath;
         | 
| 121 | 
            +
              } catch (error) {
         | 
| 122 | 
            +
                console.error('Error writing trace to file:', error);
         | 
| 123 | 
            +
                return '';
         | 
| 124 | 
            +
              }
         | 
| 125 | 
            +
            }
         | 
| 126 | 
            +
             | 
| 127 | 
            +
            async function uploadTraceFile(filePath: string, datasetName: string): Promise<boolean> {
         | 
| 128 | 
            +
              try {
         | 
| 129 | 
            +
                if (!HF_ACCESS_TOKEN) {
         | 
| 130 | 
            +
                  console.warn('HF_ACCESS_TOKEN not set, skipping file upload');
         | 
| 131 | 
            +
                  return false;
         | 
| 132 | 
            +
                }
         | 
| 133 | 
            +
                
         | 
| 134 | 
            +
                const repo: RepoDesignation = { type: 'dataset', name: datasetName };
         | 
| 135 | 
            +
                const fileName = basename(filePath);
         | 
| 136 | 
            +
                const uploadPath = `traces/${fileName}`;
         | 
| 137 | 
            +
                
         | 
| 138 | 
            +
                await uploadFiles({
         | 
| 139 | 
            +
                  repo,
         | 
| 140 | 
            +
                  accessToken: HF_ACCESS_TOKEN,
         | 
| 141 | 
            +
                  files: [
         | 
| 142 | 
            +
                    {
         | 
| 143 | 
            +
                      path: uploadPath,
         | 
| 144 | 
            +
                      content: new Blob([readFileSync(filePath)]),
         | 
| 145 | 
            +
                    },
         | 
| 146 | 
            +
                  ],
         | 
| 147 | 
            +
                });
         | 
| 148 | 
            +
                
         | 
| 149 | 
            +
                return true;
         | 
| 150 | 
            +
              } catch (error) {
         | 
| 151 | 
            +
                console.error('Error uploading trace file:', error);
         | 
| 152 | 
            +
                return false;
         | 
| 153 | 
            +
              }
         | 
| 154 | 
            +
            }
         | 
| 155 | 
            +
             | 
| 156 | 
            +
            async function writeBatchedTraces() {
         | 
| 157 | 
            +
              if (requestTraces.length === 0) {
         | 
| 158 | 
            +
                return;
         | 
| 159 | 
            +
              }
         | 
| 160 | 
            +
              
         | 
| 161 | 
            +
              const tracesToWrite = [...requestTraces];
         | 
| 162 | 
            +
              const batchSize = tracesToWrite.length;
         | 
| 163 | 
            +
              
         | 
| 164 | 
            +
              requestTraces.length = 0;
         | 
| 165 | 
            +
              lastTraceBatchTime = Date.now();
         | 
| 166 | 
            +
              
         | 
| 167 | 
            +
              console.log(`Processing batch of ${batchSize} traces...`);
         | 
| 168 | 
            +
              
         | 
| 169 | 
            +
              // write traces to local files first
         | 
| 170 | 
            +
              const filePaths: string[] = [];
         | 
| 171 | 
            +
              for (const trace of tracesToWrite) {
         | 
| 172 | 
            +
                const filePath = writeTraceToFile(trace);
         | 
| 173 | 
            +
                if (filePath) {
         | 
| 174 | 
            +
                  filePaths.push(filePath);
         | 
| 175 | 
            +
                }
         | 
| 176 | 
            +
              }
         | 
| 177 | 
            +
              
         | 
| 178 | 
            +
              if (HF_ACCESS_TOKEN) {
         | 
| 179 | 
            +
                const response = await whoAmI({ accessToken: HF_ACCESS_TOKEN });
         | 
| 180 | 
            +
                const datasetName = `${response.name}/traces`;
         | 
| 181 | 
            +
                
         | 
| 182 | 
            +
                // Check if dataset exists, create if not
         | 
| 183 | 
            +
                const exists = await checkDatasetExists(datasetName);
         | 
| 184 | 
            +
                if (!exists) {
         | 
| 185 | 
            +
                  console.log(`Dataset ${datasetName} does not exist, creating...`);
         | 
| 186 | 
            +
                  const created = await createDataset(datasetName);
         | 
| 187 | 
            +
                  if (!created) {
         | 
| 188 | 
            +
                    console.error(`Failed to create dataset ${datasetName}`);
         | 
| 189 | 
            +
                  } else {
         | 
| 190 | 
            +
                    console.log(`Successfully created dataset ${datasetName}`);
         | 
| 191 | 
            +
                  }
         | 
| 192 | 
            +
                }
         | 
| 193 | 
            +
                
         | 
| 194 | 
            +
                // Upload files to dataset
         | 
| 195 | 
            +
                for (const filePath of filePaths) {
         | 
| 196 | 
            +
                  const uploaded = await uploadTraceFile(filePath, datasetName);
         | 
| 197 | 
            +
                  
         | 
| 198 | 
            +
                  // Clean up local file if uploaded successfully
         | 
| 199 | 
            +
                  if (uploaded && existsSync(filePath)) {
         | 
| 200 | 
            +
                    unlinkSync(filePath);
         | 
| 201 | 
            +
                    console.log(`Deleted local file ${filePath} after successful upload`);
         | 
| 202 | 
            +
                  }
         | 
| 203 | 
            +
                }
         | 
| 204 | 
            +
              } else {
         | 
| 205 | 
            +
                console.log(`HF_ACCESS_TOKEN or HF_DATASET_OWNER not set, keeping ${filePaths.length} local files`);
         | 
| 206 | 
            +
              }
         | 
| 207 | 
            +
              
         | 
| 208 | 
            +
              console.log(`Successfully processed ${batchSize} traces.`);
         | 
| 209 | 
            +
            }
         | 
| 210 | 
            +
             | 
| 211 | 
            +
            setInterval(() => {
         | 
| 212 | 
            +
              const timeSinceLastBatch = Date.now() - lastTraceBatchTime;
         | 
| 213 | 
            +
              if (timeSinceLastBatch >= BATCH_TIME_LIMIT * 60 * 1000 && requestTraces.length > 0) {
         | 
| 214 | 
            +
                console.log(`Time limit reached (${BATCH_TIME_LIMIT} minutes). Flushing ${requestTraces.length} traces.`);
         | 
| 215 | 
            +
                writeBatchedTraces().catch(err => {
         | 
| 216 | 
            +
                  console.error('Error flushing traces:', err);
         | 
| 217 | 
            +
                });
         | 
| 218 | 
            +
              }
         | 
| 219 | 
            +
            }, Math.min(BATCH_TIME_LIMIT * 60 * 1000, 10000)); // Check at least every 10 seconds
         | 
| 220 | 
            +
             | 
| 221 | 
            +
            function checkAndFlushTraces() {
         | 
| 222 | 
            +
              if (requestTraces.length >= BATCH_SIZE_LIMIT) {
         | 
| 223 | 
            +
                console.log(`Batch size limit reached (${BATCH_SIZE_LIMIT}). Flushing traces.`);
         | 
| 224 | 
            +
                writeBatchedTraces().catch(err => {
         | 
| 225 | 
            +
                  console.error('Error flushing traces:', err);
         | 
| 226 | 
            +
                });
         | 
| 227 | 
            +
                return true;
         | 
| 228 | 
            +
              }
         | 
| 229 | 
            +
              return false;
         | 
| 230 | 
            +
            }
         | 
| 231 | 
            +
             | 
| 232 | 
            +
            app.get('/', (c) => {
         | 
| 233 | 
            +
              return c.text('Hono forwarding proxy running!');
         | 
| 234 | 
            +
            });
         | 
| 235 | 
            +
             | 
| 236 | 
            +
            async function storeStreamedResponse(streamToLog: ReadableStream<Uint8Array>, contentType: string | null, targetUrl: string, traceIndex: number) {
         | 
| 237 | 
            +
                const reader = streamToLog.getReader();
         | 
| 238 | 
            +
                const chunks: Uint8Array[] = [];
         | 
| 239 | 
            +
                
         | 
| 240 | 
            +
                try {
         | 
| 241 | 
            +
                    while (true) {
         | 
| 242 | 
            +
                        const { done, value } = await reader.read();
         | 
| 243 | 
            +
                        if (done) break;
         | 
| 244 | 
            +
                        if (value) chunks.push(value);
         | 
| 245 | 
            +
                    }
         | 
| 246 | 
            +
             | 
| 247 | 
            +
                    const blob = new Blob(chunks);
         | 
| 248 | 
            +
                    const bodyText = await blob.text();
         | 
| 249 | 
            +
                    
         | 
| 250 | 
            +
                    contentType = contentType?.toLowerCase() || '';
         | 
| 251 | 
            +
             | 
| 252 | 
            +
                    // Handle event streams (streaming responses)
         | 
| 253 | 
            +
                    if (contentType.includes('text/event-stream')) {
         | 
| 254 | 
            +
                        const lines = bodyText.split('\n');
         | 
| 255 | 
            +
                        let accumulatedContent = '';
         | 
| 256 | 
            +
                        
         | 
| 257 | 
            +
                        for (const line of lines) {
         | 
| 258 | 
            +
                            if (line.startsWith('data: ')) {
         | 
| 259 | 
            +
                                const jsonData = line.substring(5).trim();
         | 
| 260 | 
            +
                                if (jsonData && jsonData !== '[DONE]') {
         | 
| 261 | 
            +
                                    try {
         | 
| 262 | 
            +
                                        const parsed = JSON.parse(jsonData);
         | 
| 263 | 
            +
                                        if (parsed.choices && parsed.choices[0]?.delta?.content) {
         | 
| 264 | 
            +
                                            accumulatedContent += parsed.choices[0].delta.content;
         | 
| 265 | 
            +
                                        }
         | 
| 266 | 
            +
                                    } catch (parseError) {
         | 
| 267 | 
            +
                                        // Continue processing other lines
         | 
| 268 | 
            +
                                    }
         | 
| 269 | 
            +
                                }
         | 
| 270 | 
            +
                            }
         | 
| 271 | 
            +
                        }
         | 
| 272 | 
            +
                        
         | 
| 273 | 
            +
                        if (accumulatedContent) {
         | 
| 274 | 
            +
                            requestTraces[traceIndex].response = accumulatedContent;
         | 
| 275 | 
            +
                            requestTraces[traceIndex].completion_tokens = accumulatedContent.length;
         | 
| 276 | 
            +
                        } 
         | 
| 277 | 
            +
                    } 
         | 
| 278 | 
            +
                    else {
         | 
| 279 | 
            +
                        try {
         | 
| 280 | 
            +
                            const jsonResponse = JSON.parse(bodyText);
         | 
| 281 | 
            +
             | 
| 282 | 
            +
                            // Get response content from standard LLM response formats
         | 
| 283 | 
            +
                            requestTraces[traceIndex].response = jsonResponse.choices?.[0]?.message?.content ||
         | 
| 284 | 
            +
                                                                 jsonResponse.generated_text || 
         | 
| 285 | 
            +
                                                                 bodyText;
         | 
| 286 | 
            +
             | 
| 287 | 
            +
                            // Get token counts if available
         | 
| 288 | 
            +
                            if (jsonResponse.usage) {
         | 
| 289 | 
            +
                                if (jsonResponse.usage.completion_tokens !== undefined) {
         | 
| 290 | 
            +
                                    requestTraces[traceIndex].completion_tokens = jsonResponse.usage.completion_tokens;
         | 
| 291 | 
            +
                                }
         | 
| 292 | 
            +
                                if (jsonResponse.usage.prompt_tokens !== undefined) {
         | 
| 293 | 
            +
                                    requestTraces[traceIndex].prompt_tokens = jsonResponse.usage.prompt_tokens;
         | 
| 294 | 
            +
                                }
         | 
| 295 | 
            +
                            }
         | 
| 296 | 
            +
                        } catch (e) {
         | 
| 297 | 
            +
                            // If not JSON, use bodyText as is
         | 
| 298 | 
            +
                            requestTraces[traceIndex].response = bodyText;
         | 
| 299 | 
            +
                            requestTraces[traceIndex].completion_tokens = bodyText.length;
         | 
| 300 | 
            +
                        }
         | 
| 301 | 
            +
                    }
         | 
| 302 | 
            +
             | 
| 303 | 
            +
                    // Set the end timestamp after processing
         | 
| 304 | 
            +
                    requestTraces[traceIndex].timestamp_end = new Date().toISOString();
         | 
| 305 | 
            +
                    
         | 
| 306 | 
            +
                    // Calculate duration if we have both timestamps
         | 
| 307 | 
            +
                    if (requestTraces[traceIndex].timestamp_start && requestTraces[traceIndex].timestamp_end) {
         | 
| 308 | 
            +
                      const startTime = new Date(requestTraces[traceIndex].timestamp_start).getTime();
         | 
| 309 | 
            +
                      const endTime = new Date(requestTraces[traceIndex].timestamp_end).getTime();
         | 
| 310 | 
            +
                      requestTraces[traceIndex].duration_ms = endTime - startTime;
         | 
| 311 | 
            +
                    }
         | 
| 312 | 
            +
                    
         | 
| 313 | 
            +
                    checkAndFlushTraces();
         | 
| 314 | 
            +
                } catch (error) {
         | 
| 315 | 
            +
                    requestTraces[traceIndex].timestamp_end = new Date().toISOString();
         | 
| 316 | 
            +
                    
         | 
| 317 | 
            +
                    // Calculate duration if we have both timestamps
         | 
| 318 | 
            +
                    if (requestTraces[traceIndex].timestamp_start && requestTraces[traceIndex].timestamp_end) {
         | 
| 319 | 
            +
                      const startTime = new Date(requestTraces[traceIndex].timestamp_start).getTime();
         | 
| 320 | 
            +
                      const endTime = new Date(requestTraces[traceIndex].timestamp_end).getTime();
         | 
| 321 | 
            +
                      requestTraces[traceIndex].duration_ms = endTime - startTime;
         | 
| 322 | 
            +
                    }
         | 
| 323 | 
            +
                    
         | 
| 324 | 
            +
                    checkAndFlushTraces();
         | 
| 325 | 
            +
                } finally {
         | 
| 326 | 
            +
                    try {
         | 
| 327 | 
            +
                        reader.releaseLock();
         | 
| 328 | 
            +
                    } catch {
         | 
| 329 | 
            +
                        // Ignore release errors
         | 
| 330 | 
            +
                    }
         | 
| 331 | 
            +
                }
         | 
| 332 | 
            +
            }
         | 
| 333 | 
            +
             | 
| 334 | 
            +
            app.all('*', async (c) => {
         | 
| 335 | 
            +
              try {
         | 
| 336 | 
            +
                // check if the user is authorized to access the dataset
         | 
| 337 | 
            +
                if (USER_NAME && !await checkUserAccess(USER_NAME)) {
         | 
| 338 | 
            +
                  return c.text('Unauthorized', 401);
         | 
| 339 | 
            +
                }
         | 
| 340 | 
            +
             | 
| 341 | 
            +
                const url = new URL(c.req.url);
         | 
| 342 | 
            +
                const targetPath = url.pathname;
         | 
| 343 | 
            +
                const targetUrl = `${TARGET_BASE_URL}${targetPath}${url.search}`;
         | 
| 344 | 
            +
             | 
| 345 | 
            +
                // Extract provider from the URL path
         | 
| 346 | 
            +
                const pathParts = targetPath.split('/');
         | 
| 347 | 
            +
                const provider = pathParts.length > 1 ? pathParts[1] : 'unknown';
         | 
| 348 | 
            +
             | 
| 349 | 
            +
                console.log(`Forwarding request for ${url.pathname} to ${targetUrl}`);
         | 
| 350 | 
            +
             | 
| 351 | 
            +
                const headers = new Headers(c.req.header());
         | 
| 352 | 
            +
                headers.delete('host'); 
         | 
| 353 | 
            +
                headers.set('host', new URL(TARGET_BASE_URL).host);
         | 
| 354 | 
            +
                headers.delete('content-length');
         | 
| 355 | 
            +
                headers.delete('transfer-encoding'); 
         | 
| 356 | 
            +
             | 
| 357 | 
            +
                let requestBody: BodyInit | null = null;
         | 
| 358 | 
            +
                let parsedRequestBody: any = null;
         | 
| 359 | 
            +
                const incomingContentType = c.req.header('content-type') || '';
         | 
| 360 | 
            +
                const methodNeedsBody = !['GET', 'HEAD'].includes(c.req.method);
         | 
| 361 | 
            +
             | 
| 362 | 
            +
                if (methodNeedsBody && c.req.raw.body) {
         | 
| 363 | 
            +
                  if (incomingContentType.includes('application/json')) {
         | 
| 364 | 
            +
                    try {
         | 
| 365 | 
            +
                      const rawBodyText = await c.req.text();
         | 
| 366 | 
            +
                      parsedRequestBody = JSON.parse(rawBodyText);
         | 
| 367 | 
            +
                      requestBody = rawBodyText;
         | 
| 368 | 
            +
                    } catch (e) {
         | 
| 369 | 
            +
                      console.warn("Failed to parse incoming JSON body, forwarding raw body:", e);
         | 
| 370 | 
            +
                       try {
         | 
| 371 | 
            +
                           requestBody = await c.req.blob();
         | 
| 372 | 
            +
                       } catch (blobError) {
         | 
| 373 | 
            +
                            console.error("Could not retrieve request body after JSON parse failure:", blobError);
         | 
| 374 | 
            +
                            requestBody = null;
         | 
| 375 | 
            +
                       }
         | 
| 376 | 
            +
                    }
         | 
| 377 | 
            +
                  } else {
         | 
| 378 | 
            +
                    requestBody = c.req.raw.body;
         | 
| 379 | 
            +
                  }
         | 
| 380 | 
            +
                }
         | 
| 381 | 
            +
             | 
| 382 | 
            +
                const traceIndex = requestTraces.length;
         | 
| 383 | 
            +
                const traceEntry: typeof requestTraces[0] = {
         | 
| 384 | 
            +
                  timestamp_start: new Date().toISOString(),
         | 
| 385 | 
            +
                  provider
         | 
| 386 | 
            +
                };
         | 
| 387 | 
            +
                
         | 
| 388 | 
            +
                if (parsedRequestBody) {
         | 
| 389 | 
            +
                  if (parsedRequestBody.model) {
         | 
| 390 | 
            +
                    traceEntry.model = parsedRequestBody.model;
         | 
| 391 | 
            +
                  } else if (targetPath.includes('/models/') || targetPath.includes('/model/')) {
         | 
| 392 | 
            +
                    const pathParts = targetPath.split('/');
         | 
| 393 | 
            +
                    const modelIndex = pathParts.findIndex(part => part === 'models' || part === 'model');
         | 
| 394 | 
            +
                    if (modelIndex >= 0 && pathParts.length > modelIndex + 1) {
         | 
| 395 | 
            +
                      traceEntry.model = pathParts[modelIndex + 1];
         | 
| 396 | 
            +
                    }
         | 
| 397 | 
            +
                  }
         | 
| 398 | 
            +
                  
         | 
| 399 | 
            +
                  if (parsedRequestBody.messages) {
         | 
| 400 | 
            +
                    traceEntry.messages = parsedRequestBody.messages;
         | 
| 401 | 
            +
                    
         | 
| 402 | 
            +
                    let promptText = '';
         | 
| 403 | 
            +
                    for (const message of parsedRequestBody.messages) {
         | 
| 404 | 
            +
                      if (message.content) {
         | 
| 405 | 
            +
                        promptText += message.content;
         | 
| 406 | 
            +
                      }
         | 
| 407 | 
            +
                    }
         | 
| 408 | 
            +
                    traceEntry.prompt_tokens = promptText.length;
         | 
| 409 | 
            +
                  }
         | 
| 410 | 
            +
                  
         | 
| 411 | 
            +
                  if (parsedRequestBody.arguments) {
         | 
| 412 | 
            +
                    traceEntry.arguments = parsedRequestBody.arguments;
         | 
| 413 | 
            +
                  } else if (parsedRequestBody.parameters) {
         | 
| 414 | 
            +
                    traceEntry.arguments = parsedRequestBody.parameters;
         | 
| 415 | 
            +
                  }
         | 
| 416 | 
            +
                }
         | 
| 417 | 
            +
                
         | 
| 418 | 
            +
                requestTraces.push(traceEntry);
         | 
| 419 | 
            +
                // Check if we need to flush based on batch size
         | 
| 420 | 
            +
                checkAndFlushTraces();
         | 
| 421 | 
            +
             | 
| 422 | 
            +
                const response = await fetch(targetUrl, {
         | 
| 423 | 
            +
                  method: c.req.method,
         | 
| 424 | 
            +
                  headers: headers,
         | 
| 425 | 
            +
                  body: requestBody,
         | 
| 426 | 
            +
                });
         | 
| 427 | 
            +
             | 
| 428 | 
            +
                console.log(`Received response status ${response.status} from ${targetUrl}`);
         | 
| 429 | 
            +
             | 
| 430 | 
            +
                c.status(response.status as StatusCode);
         | 
| 431 | 
            +
                response.headers.forEach((value, key) => {
         | 
| 432 | 
            +
                    if (key.toLowerCase() !== 'content-encoding' && key.toLowerCase() !== 'transfer-encoding') {
         | 
| 433 | 
            +
                         c.header(key, value);
         | 
| 434 | 
            +
                    }
         | 
| 435 | 
            +
                });
         | 
| 436 | 
            +
                if (!response.headers.has('content-type')) {
         | 
| 437 | 
            +
                     c.header('content-type', 'application/octet-stream');
         | 
| 438 | 
            +
                }
         | 
| 439 | 
            +
             | 
| 440 | 
            +
                if (response.body) {
         | 
| 441 | 
            +
                    const [streamForClient, streamForStorage] = response.body.tee();
         | 
| 442 | 
            +
                    const contentType = response.headers.get('content-type');
         | 
| 443 | 
            +
             | 
| 444 | 
            +
                    storeStreamedResponse(streamForStorage, contentType, targetUrl, traceIndex).catch(err => {
         | 
| 445 | 
            +
                         console.error("Error in background stream storage:", err);
         | 
| 446 | 
            +
                    });
         | 
| 447 | 
            +
             | 
| 448 | 
            +
                    return stream(c, async (streamInstance) => {
         | 
| 449 | 
            +
                        await streamInstance.pipe(streamForClient);
         | 
| 450 | 
            +
                    });
         | 
| 451 | 
            +
                } else {
         | 
| 452 | 
            +
                    console.log(`Received response with no body from ${targetUrl}.`);
         | 
| 453 | 
            +
                    requestTraces[traceIndex].timestamp_end = new Date().toISOString();
         | 
| 454 | 
            +
                    
         | 
| 455 | 
            +
                    // Calculate duration if we have both timestamps
         | 
| 456 | 
            +
                    if (requestTraces[traceIndex].timestamp_start && requestTraces[traceIndex].timestamp_end) {
         | 
| 457 | 
            +
                      const startTime = new Date(requestTraces[traceIndex].timestamp_start).getTime();
         | 
| 458 | 
            +
                      const endTime = new Date(requestTraces[traceIndex].timestamp_end).getTime();
         | 
| 459 | 
            +
                      requestTraces[traceIndex].duration_ms = endTime - startTime;
         | 
| 460 | 
            +
                    }
         | 
| 461 | 
            +
                    
         | 
| 462 | 
            +
                    // Check if we need to flush based on batch size
         | 
| 463 | 
            +
                    checkAndFlushTraces();
         | 
| 464 | 
            +
                    return c.body(null);
         | 
| 465 | 
            +
                }
         | 
| 466 | 
            +
              } catch (error) {
         | 
| 467 | 
            +
                console.error('Error during proxy request:', error);
         | 
| 468 | 
            +
                return c.text('Internal Server Error', 500);
         | 
| 469 | 
            +
              }
         | 
| 470 | 
            +
            });
         | 
| 471 | 
            +
             | 
| 472 | 
            +
            // Ensure we flush any remaining traces when the process is terminating
         | 
| 473 | 
            +
            process.on('SIGINT', () => {
         | 
| 474 | 
            +
              console.log('Process terminating, flushing remaining traces...');
         | 
| 475 | 
            +
              writeBatchedTraces().then(() => {
         | 
| 476 | 
            +
                process.exit();
         | 
| 477 | 
            +
              }).catch(err => {
         | 
| 478 | 
            +
                console.error('Error flushing traces on shutdown:', err);
         | 
| 479 | 
            +
                process.exit(1);
         | 
| 480 | 
            +
              });
         | 
| 481 | 
            +
            });
         | 
| 482 | 
            +
             | 
| 483 | 
            +
            process.on('SIGTERM', () => {
         | 
| 484 | 
            +
              console.log('Process terminating, flushing remaining traces...');
         | 
| 485 | 
            +
              writeBatchedTraces().then(() => {
         | 
| 486 | 
            +
                process.exit();
         | 
| 487 | 
            +
              }).catch(err => {
         | 
| 488 | 
            +
                console.error('Error flushing traces on shutdown:', err);
         | 
| 489 | 
            +
                process.exit(1);
         | 
| 490 | 
            +
              });
         | 
| 491 | 
            +
            });
         | 
| 492 | 
            +
             | 
| 493 | 
            +
            console.log(`Inference Proxy running on port ${PORT}`);
         | 
| 494 | 
            +
            console.log(`Forwarding to: ${TARGET_BASE_URL}`);
         | 
| 495 | 
            +
            console.log(`Logs directory: ${resolve(LOGS_DIR)}`);
         | 
| 496 | 
            +
            console.log(`Batching: max ${BATCH_SIZE_LIMIT} traces or ${BATCH_TIME_LIMIT} minutes`);
         | 
| 497 | 
            +
             | 
| 498 | 
            +
            export default {
         | 
| 499 | 
            +
              port: PORT,
         | 
| 500 | 
            +
              fetch: app.fetch,
         | 
| 501 | 
            +
            };
         | 
    	
        package.json
    ADDED
    
    | @@ -0,0 +1,18 @@ | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | 
|  | |
| 1 | 
            +
            {
         | 
| 2 | 
            +
              "name": "inference-proxy",
         | 
| 3 | 
            +
              "module": "index.ts",
         | 
| 4 | 
            +
              "type": "module",
         | 
| 5 | 
            +
              "devDependencies": {
         | 
| 6 | 
            +
                "@types/bun": "latest"
         | 
| 7 | 
            +
              },
         | 
| 8 | 
            +
              "peerDependencies": {
         | 
| 9 | 
            +
                "typescript": "^5.0.0"
         | 
| 10 | 
            +
              },
         | 
| 11 | 
            +
              "dependencies": {
         | 
| 12 | 
            +
                "@huggingface/hub": "^1.1.2",
         | 
| 13 | 
            +
                "@huggingface/inference": "^3.7.0",
         | 
| 14 | 
            +
                "hono": "^4.7.5",
         | 
| 15 | 
            +
                "openai": "^4.92.0",
         | 
| 16 | 
            +
                "uuid": "^11.1.0"
         | 
| 17 | 
            +
              }
         | 
| 18 | 
            +
            }
         | 
    	
        tsconfig.json
    ADDED
    
    | @@ -0,0 +1,27 @@ | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | 
|  | |
| 1 | 
            +
            {
         | 
| 2 | 
            +
              "compilerOptions": {
         | 
| 3 | 
            +
                // Enable latest features
         | 
| 4 | 
            +
                "lib": ["ESNext", "DOM"],
         | 
| 5 | 
            +
                "target": "ESNext",
         | 
| 6 | 
            +
                "module": "ESNext",
         | 
| 7 | 
            +
                "moduleDetection": "force",
         | 
| 8 | 
            +
                "jsx": "react-jsx",
         | 
| 9 | 
            +
                "allowJs": true,
         | 
| 10 | 
            +
             | 
| 11 | 
            +
                // Bundler mode
         | 
| 12 | 
            +
                "moduleResolution": "bundler",
         | 
| 13 | 
            +
                "allowImportingTsExtensions": true,
         | 
| 14 | 
            +
                "verbatimModuleSyntax": true,
         | 
| 15 | 
            +
                "noEmit": true,
         | 
| 16 | 
            +
             | 
| 17 | 
            +
                // Best practices
         | 
| 18 | 
            +
                "strict": true,
         | 
| 19 | 
            +
                "skipLibCheck": true,
         | 
| 20 | 
            +
                "noFallthroughCasesInSwitch": true,
         | 
| 21 | 
            +
             | 
| 22 | 
            +
                // Some stricter flags (disabled by default)
         | 
| 23 | 
            +
                "noUnusedLocals": false,
         | 
| 24 | 
            +
                "noUnusedParameters": false,
         | 
| 25 | 
            +
                "noPropertyAccessFromIndexSignature": false
         | 
| 26 | 
            +
              }
         | 
| 27 | 
            +
            }
         | 
