You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Feat: Support tool calling in Generate component (#7572) ### What problem does this PR solve? Hello, our use case requires LLM agent to invoke some tools, so I made a simple implementation here. This PR does two things: 1. A simple plugin mechanism based on `pluginlib`: This mechanism lives in the `plugin` directory. It will only load plugins from `plugin/embedded_plugins` for now. A sample plugin `bad_calculator.py` is placed in `plugin/embedded_plugins/llm_tools`, it accepts two numbers `a` and `b`, then give a wrong result `a + b + 100`. In the future, it can load plugins from external location with little code change. Plugins are divided into different types. The only plugin type supported in this PR is `llm_tools`, which must implement the `LLMToolPlugin` class in the `plugin/llm_tool_plugin.py`. More plugin types can be added in the future. 2. A tool selector in the `Generate` component: Added a tool selector to select one or more tools for LLM: ![image](https://github.com/user-attachments/assets/74a21fdf-9333-4175-991b-43df6524c5dc) And with the `bad_calculator` tool, it results this with the `qwen-max` model: ![image](https://github.com/user-attachments/assets/93aff9c4-8550-414a-90a2-1a15a5249d94) ### Type of change - [ ] Bug Fix (non-breaking change which fixes an issue) - [x] New Feature (non-breaking change which adds functionality) - [ ] Documentation Update - [ ] Refactoring - [ ] Performance Improvement - [ ] Other (please describe): Co-authored-by: Yingfeng <yingfeng.zhang@gmail.com>
5 kuukautta sitten
Feat: Support tool calling in Generate component (#7572) ### What problem does this PR solve? Hello, our use case requires LLM agent to invoke some tools, so I made a simple implementation here. This PR does two things: 1. A simple plugin mechanism based on `pluginlib`: This mechanism lives in the `plugin` directory. It will only load plugins from `plugin/embedded_plugins` for now. A sample plugin `bad_calculator.py` is placed in `plugin/embedded_plugins/llm_tools`, it accepts two numbers `a` and `b`, then give a wrong result `a + b + 100`. In the future, it can load plugins from external location with little code change. Plugins are divided into different types. The only plugin type supported in this PR is `llm_tools`, which must implement the `LLMToolPlugin` class in the `plugin/llm_tool_plugin.py`. More plugin types can be added in the future. 2. A tool selector in the `Generate` component: Added a tool selector to select one or more tools for LLM: ![image](https://github.com/user-attachments/assets/74a21fdf-9333-4175-991b-43df6524c5dc) And with the `bad_calculator` tool, it results this with the `qwen-max` model: ![image](https://github.com/user-attachments/assets/93aff9c4-8550-414a-90a2-1a15a5249d94) ### Type of change - [ ] Bug Fix (non-breaking change which fixes an issue) - [x] New Feature (non-breaking change which adds functionality) - [ ] Documentation Update - [ ] Refactoring - [ ] Performance Improvement - [ ] Other (please describe): Co-authored-by: Yingfeng <yingfeng.zhang@gmail.com>
5 kuukautta sitten
Feat: Support tool calling in Generate component (#7572) ### What problem does this PR solve? Hello, our use case requires LLM agent to invoke some tools, so I made a simple implementation here. This PR does two things: 1. A simple plugin mechanism based on `pluginlib`: This mechanism lives in the `plugin` directory. It will only load plugins from `plugin/embedded_plugins` for now. A sample plugin `bad_calculator.py` is placed in `plugin/embedded_plugins/llm_tools`, it accepts two numbers `a` and `b`, then give a wrong result `a + b + 100`. In the future, it can load plugins from external location with little code change. Plugins are divided into different types. The only plugin type supported in this PR is `llm_tools`, which must implement the `LLMToolPlugin` class in the `plugin/llm_tool_plugin.py`. More plugin types can be added in the future. 2. A tool selector in the `Generate` component: Added a tool selector to select one or more tools for LLM: ![image](https://github.com/user-attachments/assets/74a21fdf-9333-4175-991b-43df6524c5dc) And with the `bad_calculator` tool, it results this with the `qwen-max` model: ![image](https://github.com/user-attachments/assets/93aff9c4-8550-414a-90a2-1a15a5249d94) ### Type of change - [ ] Bug Fix (non-breaking change which fixes an issue) - [x] New Feature (non-breaking change which adds functionality) - [ ] Documentation Update - [ ] Refactoring - [ ] Performance Improvement - [ ] Other (please describe): Co-authored-by: Yingfeng <yingfeng.zhang@gmail.com>
5 kuukautta sitten
Dynamic Context Window Size for Ollama Chat (#6582) # Dynamic Context Window Size for Ollama Chat ## Problem Statement Previously, the Ollama chat implementation used a fixed context window size of 32768 tokens. This caused two main issues: 1. Performance degradation due to unnecessarily large context windows for small conversations 2. Potential business logic failures when using smaller fixed sizes (e.g., 2048 tokens) ## Solution Implemented a dynamic context window size calculation that: 1. Uses a base context size of 8192 tokens 2. Applies a 1.2x buffer ratio to the total token count 3. Adds multiples of 8192 tokens based on the buffered token count 4. Implements a smart context size update strategy ## Implementation Details ### Token Counting Logic ```python def count_tokens(text): """Calculate token count for text""" # Simple calculation: 1 token per ASCII character # 2 tokens for non-ASCII characters (Chinese, Japanese, Korean, etc.) total = 0 for char in text: if ord(char) < 128: # ASCII characters total += 1 else: # Non-ASCII characters total += 2 return total ``` ### Dynamic Context Calculation ```python def _calculate_dynamic_ctx(self, history): """Calculate dynamic context window size""" # Calculate total tokens for all messages total_tokens = 0 for message in history: content = message.get("content", "") content_tokens = count_tokens(content) role_tokens = 4 # Role marker token overhead total_tokens += content_tokens + role_tokens # Apply 1.2x buffer ratio total_tokens_with_buffer = int(total_tokens * 1.2) # Calculate context size in multiples of 8192 if total_tokens_with_buffer <= 8192: ctx_size = 8192 else: ctx_multiplier = (total_tokens_with_buffer // 8192) + 1 ctx_size = ctx_multiplier * 8192 return ctx_size ``` ### Integration in Chat Method ```python def chat(self, system, history, gen_conf): if system: history.insert(0, {"role": "system", "content": system}) if "max_tokens" in gen_conf: del gen_conf["max_tokens"] try: # Calculate new context size new_ctx_size = self._calculate_dynamic_ctx(history) # Prepare options with context size options = { "num_ctx": new_ctx_size } # Add other generation options if "temperature" in gen_conf: options["temperature"] = gen_conf["temperature"] if "max_tokens" in gen_conf: options["num_predict"] = gen_conf["max_tokens"] if "top_p" in gen_conf: options["top_p"] = gen_conf["top_p"] if "presence_penalty" in gen_conf: options["presence_penalty"] = gen_conf["presence_penalty"] if "frequency_penalty" in gen_conf: options["frequency_penalty"] = gen_conf["frequency_penalty"] # Make API call with dynamic context size response = self.client.chat( model=self.model_name, messages=history, options=options, keep_alive=60 ) return response["message"]["content"].strip(), response.get("eval_count", 0) + response.get("prompt_eval_count", 0) except Exception as e: return "**ERROR**: " + str(e), 0 ``` ## Benefits 1. **Improved Performance**: Uses appropriate context windows based on conversation length 2. **Better Resource Utilization**: Context window size scales with content 3. **Maintained Compatibility**: Works with existing business logic 4. **Predictable Scaling**: Context growth in 8192-token increments 5. **Smart Updates**: Context size updates are optimized to reduce unnecessary model reloads ## Future Considerations 1. Fine-tune buffer ratio based on usage patterns 2. Add monitoring for context window utilization 3. Consider language-specific token counting optimizations 4. Implement adaptive threshold based on conversation patterns 5. Add metrics for context size update frequency --------- Co-authored-by: Kevin Hu <kevinhu.sh@gmail.com>
7 kuukautta sitten
Dynamic Context Window Size for Ollama Chat (#6582) # Dynamic Context Window Size for Ollama Chat ## Problem Statement Previously, the Ollama chat implementation used a fixed context window size of 32768 tokens. This caused two main issues: 1. Performance degradation due to unnecessarily large context windows for small conversations 2. Potential business logic failures when using smaller fixed sizes (e.g., 2048 tokens) ## Solution Implemented a dynamic context window size calculation that: 1. Uses a base context size of 8192 tokens 2. Applies a 1.2x buffer ratio to the total token count 3. Adds multiples of 8192 tokens based on the buffered token count 4. Implements a smart context size update strategy ## Implementation Details ### Token Counting Logic ```python def count_tokens(text): """Calculate token count for text""" # Simple calculation: 1 token per ASCII character # 2 tokens for non-ASCII characters (Chinese, Japanese, Korean, etc.) total = 0 for char in text: if ord(char) < 128: # ASCII characters total += 1 else: # Non-ASCII characters total += 2 return total ``` ### Dynamic Context Calculation ```python def _calculate_dynamic_ctx(self, history): """Calculate dynamic context window size""" # Calculate total tokens for all messages total_tokens = 0 for message in history: content = message.get("content", "") content_tokens = count_tokens(content) role_tokens = 4 # Role marker token overhead total_tokens += content_tokens + role_tokens # Apply 1.2x buffer ratio total_tokens_with_buffer = int(total_tokens * 1.2) # Calculate context size in multiples of 8192 if total_tokens_with_buffer <= 8192: ctx_size = 8192 else: ctx_multiplier = (total_tokens_with_buffer // 8192) + 1 ctx_size = ctx_multiplier * 8192 return ctx_size ``` ### Integration in Chat Method ```python def chat(self, system, history, gen_conf): if system: history.insert(0, {"role": "system", "content": system}) if "max_tokens" in gen_conf: del gen_conf["max_tokens"] try: # Calculate new context size new_ctx_size = self._calculate_dynamic_ctx(history) # Prepare options with context size options = { "num_ctx": new_ctx_size } # Add other generation options if "temperature" in gen_conf: options["temperature"] = gen_conf["temperature"] if "max_tokens" in gen_conf: options["num_predict"] = gen_conf["max_tokens"] if "top_p" in gen_conf: options["top_p"] = gen_conf["top_p"] if "presence_penalty" in gen_conf: options["presence_penalty"] = gen_conf["presence_penalty"] if "frequency_penalty" in gen_conf: options["frequency_penalty"] = gen_conf["frequency_penalty"] # Make API call with dynamic context size response = self.client.chat( model=self.model_name, messages=history, options=options, keep_alive=60 ) return response["message"]["content"].strip(), response.get("eval_count", 0) + response.get("prompt_eval_count", 0) except Exception as e: return "**ERROR**: " + str(e), 0 ``` ## Benefits 1. **Improved Performance**: Uses appropriate context windows based on conversation length 2. **Better Resource Utilization**: Context window size scales with content 3. **Maintained Compatibility**: Works with existing business logic 4. **Predictable Scaling**: Context growth in 8192-token increments 5. **Smart Updates**: Context size updates are optimized to reduce unnecessary model reloads ## Future Considerations 1. Fine-tune buffer ratio based on usage patterns 2. Add monitoring for context window utilization 3. Consider language-specific token counting optimizations 4. Implement adaptive threshold based on conversation patterns 5. Add metrics for context size update frequency --------- Co-authored-by: Kevin Hu <kevinhu.sh@gmail.com>
7 kuukautta sitten
Dynamic Context Window Size for Ollama Chat (#6582) # Dynamic Context Window Size for Ollama Chat ## Problem Statement Previously, the Ollama chat implementation used a fixed context window size of 32768 tokens. This caused two main issues: 1. Performance degradation due to unnecessarily large context windows for small conversations 2. Potential business logic failures when using smaller fixed sizes (e.g., 2048 tokens) ## Solution Implemented a dynamic context window size calculation that: 1. Uses a base context size of 8192 tokens 2. Applies a 1.2x buffer ratio to the total token count 3. Adds multiples of 8192 tokens based on the buffered token count 4. Implements a smart context size update strategy ## Implementation Details ### Token Counting Logic ```python def count_tokens(text): """Calculate token count for text""" # Simple calculation: 1 token per ASCII character # 2 tokens for non-ASCII characters (Chinese, Japanese, Korean, etc.) total = 0 for char in text: if ord(char) < 128: # ASCII characters total += 1 else: # Non-ASCII characters total += 2 return total ``` ### Dynamic Context Calculation ```python def _calculate_dynamic_ctx(self, history): """Calculate dynamic context window size""" # Calculate total tokens for all messages total_tokens = 0 for message in history: content = message.get("content", "") content_tokens = count_tokens(content) role_tokens = 4 # Role marker token overhead total_tokens += content_tokens + role_tokens # Apply 1.2x buffer ratio total_tokens_with_buffer = int(total_tokens * 1.2) # Calculate context size in multiples of 8192 if total_tokens_with_buffer <= 8192: ctx_size = 8192 else: ctx_multiplier = (total_tokens_with_buffer // 8192) + 1 ctx_size = ctx_multiplier * 8192 return ctx_size ``` ### Integration in Chat Method ```python def chat(self, system, history, gen_conf): if system: history.insert(0, {"role": "system", "content": system}) if "max_tokens" in gen_conf: del gen_conf["max_tokens"] try: # Calculate new context size new_ctx_size = self._calculate_dynamic_ctx(history) # Prepare options with context size options = { "num_ctx": new_ctx_size } # Add other generation options if "temperature" in gen_conf: options["temperature"] = gen_conf["temperature"] if "max_tokens" in gen_conf: options["num_predict"] = gen_conf["max_tokens"] if "top_p" in gen_conf: options["top_p"] = gen_conf["top_p"] if "presence_penalty" in gen_conf: options["presence_penalty"] = gen_conf["presence_penalty"] if "frequency_penalty" in gen_conf: options["frequency_penalty"] = gen_conf["frequency_penalty"] # Make API call with dynamic context size response = self.client.chat( model=self.model_name, messages=history, options=options, keep_alive=60 ) return response["message"]["content"].strip(), response.get("eval_count", 0) + response.get("prompt_eval_count", 0) except Exception as e: return "**ERROR**: " + str(e), 0 ``` ## Benefits 1. **Improved Performance**: Uses appropriate context windows based on conversation length 2. **Better Resource Utilization**: Context window size scales with content 3. **Maintained Compatibility**: Works with existing business logic 4. **Predictable Scaling**: Context growth in 8192-token increments 5. **Smart Updates**: Context size updates are optimized to reduce unnecessary model reloads ## Future Considerations 1. Fine-tune buffer ratio based on usage patterns 2. Add monitoring for context window utilization 3. Consider language-specific token counting optimizations 4. Implement adaptive threshold based on conversation patterns 5. Add metrics for context size update frequency --------- Co-authored-by: Kevin Hu <kevinhu.sh@gmail.com>
7 kuukautta sitten
Dynamic Context Window Size for Ollama Chat (#6582) # Dynamic Context Window Size for Ollama Chat ## Problem Statement Previously, the Ollama chat implementation used a fixed context window size of 32768 tokens. This caused two main issues: 1. Performance degradation due to unnecessarily large context windows for small conversations 2. Potential business logic failures when using smaller fixed sizes (e.g., 2048 tokens) ## Solution Implemented a dynamic context window size calculation that: 1. Uses a base context size of 8192 tokens 2. Applies a 1.2x buffer ratio to the total token count 3. Adds multiples of 8192 tokens based on the buffered token count 4. Implements a smart context size update strategy ## Implementation Details ### Token Counting Logic ```python def count_tokens(text): """Calculate token count for text""" # Simple calculation: 1 token per ASCII character # 2 tokens for non-ASCII characters (Chinese, Japanese, Korean, etc.) total = 0 for char in text: if ord(char) < 128: # ASCII characters total += 1 else: # Non-ASCII characters total += 2 return total ``` ### Dynamic Context Calculation ```python def _calculate_dynamic_ctx(self, history): """Calculate dynamic context window size""" # Calculate total tokens for all messages total_tokens = 0 for message in history: content = message.get("content", "") content_tokens = count_tokens(content) role_tokens = 4 # Role marker token overhead total_tokens += content_tokens + role_tokens # Apply 1.2x buffer ratio total_tokens_with_buffer = int(total_tokens * 1.2) # Calculate context size in multiples of 8192 if total_tokens_with_buffer <= 8192: ctx_size = 8192 else: ctx_multiplier = (total_tokens_with_buffer // 8192) + 1 ctx_size = ctx_multiplier * 8192 return ctx_size ``` ### Integration in Chat Method ```python def chat(self, system, history, gen_conf): if system: history.insert(0, {"role": "system", "content": system}) if "max_tokens" in gen_conf: del gen_conf["max_tokens"] try: # Calculate new context size new_ctx_size = self._calculate_dynamic_ctx(history) # Prepare options with context size options = { "num_ctx": new_ctx_size } # Add other generation options if "temperature" in gen_conf: options["temperature"] = gen_conf["temperature"] if "max_tokens" in gen_conf: options["num_predict"] = gen_conf["max_tokens"] if "top_p" in gen_conf: options["top_p"] = gen_conf["top_p"] if "presence_penalty" in gen_conf: options["presence_penalty"] = gen_conf["presence_penalty"] if "frequency_penalty" in gen_conf: options["frequency_penalty"] = gen_conf["frequency_penalty"] # Make API call with dynamic context size response = self.client.chat( model=self.model_name, messages=history, options=options, keep_alive=60 ) return response["message"]["content"].strip(), response.get("eval_count", 0) + response.get("prompt_eval_count", 0) except Exception as e: return "**ERROR**: " + str(e), 0 ``` ## Benefits 1. **Improved Performance**: Uses appropriate context windows based on conversation length 2. **Better Resource Utilization**: Context window size scales with content 3. **Maintained Compatibility**: Works with existing business logic 4. **Predictable Scaling**: Context growth in 8192-token increments 5. **Smart Updates**: Context size updates are optimized to reduce unnecessary model reloads ## Future Considerations 1. Fine-tune buffer ratio based on usage patterns 2. Add monitoring for context window utilization 3. Consider language-specific token counting optimizations 4. Implement adaptive threshold based on conversation patterns 5. Add metrics for context size update frequency --------- Co-authored-by: Kevin Hu <kevinhu.sh@gmail.com>
7 kuukautta sitten
Feat: Support tool calling in Generate component (#7572) ### What problem does this PR solve? Hello, our use case requires LLM agent to invoke some tools, so I made a simple implementation here. This PR does two things: 1. A simple plugin mechanism based on `pluginlib`: This mechanism lives in the `plugin` directory. It will only load plugins from `plugin/embedded_plugins` for now. A sample plugin `bad_calculator.py` is placed in `plugin/embedded_plugins/llm_tools`, it accepts two numbers `a` and `b`, then give a wrong result `a + b + 100`. In the future, it can load plugins from external location with little code change. Plugins are divided into different types. The only plugin type supported in this PR is `llm_tools`, which must implement the `LLMToolPlugin` class in the `plugin/llm_tool_plugin.py`. More plugin types can be added in the future. 2. A tool selector in the `Generate` component: Added a tool selector to select one or more tools for LLM: ![image](https://github.com/user-attachments/assets/74a21fdf-9333-4175-991b-43df6524c5dc) And with the `bad_calculator` tool, it results this with the `qwen-max` model: ![image](https://github.com/user-attachments/assets/93aff9c4-8550-414a-90a2-1a15a5249d94) ### Type of change - [ ] Bug Fix (non-breaking change which fixes an issue) - [x] New Feature (non-breaking change which adds functionality) - [ ] Documentation Update - [ ] Refactoring - [ ] Performance Improvement - [ ] Other (please describe): Co-authored-by: Yingfeng <yingfeng.zhang@gmail.com>
5 kuukautta sitten
Feat: Support tool calling in Generate component (#7572) ### What problem does this PR solve? Hello, our use case requires LLM agent to invoke some tools, so I made a simple implementation here. This PR does two things: 1. A simple plugin mechanism based on `pluginlib`: This mechanism lives in the `plugin` directory. It will only load plugins from `plugin/embedded_plugins` for now. A sample plugin `bad_calculator.py` is placed in `plugin/embedded_plugins/llm_tools`, it accepts two numbers `a` and `b`, then give a wrong result `a + b + 100`. In the future, it can load plugins from external location with little code change. Plugins are divided into different types. The only plugin type supported in this PR is `llm_tools`, which must implement the `LLMToolPlugin` class in the `plugin/llm_tool_plugin.py`. More plugin types can be added in the future. 2. A tool selector in the `Generate` component: Added a tool selector to select one or more tools for LLM: ![image](https://github.com/user-attachments/assets/74a21fdf-9333-4175-991b-43df6524c5dc) And with the `bad_calculator` tool, it results this with the `qwen-max` model: ![image](https://github.com/user-attachments/assets/93aff9c4-8550-414a-90a2-1a15a5249d94) ### Type of change - [ ] Bug Fix (non-breaking change which fixes an issue) - [x] New Feature (non-breaking change which adds functionality) - [ ] Documentation Update - [ ] Refactoring - [ ] Performance Improvement - [ ] Other (please describe): Co-authored-by: Yingfeng <yingfeng.zhang@gmail.com>
5 kuukautta sitten
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849
  1. #
  2. # Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import asyncio
  17. import json
  18. import logging
  19. import os
  20. import random
  21. import re
  22. import time
  23. from abc import ABC
  24. from copy import deepcopy
  25. from typing import Any, Protocol
  26. from urllib.parse import urljoin
  27. import json_repair
  28. import litellm
  29. import openai
  30. import requests
  31. from openai import OpenAI
  32. from openai.lib.azure import AzureOpenAI
  33. from strenum import StrEnum
  34. from zhipuai import ZhipuAI
  35. from rag.llm import FACTORY_DEFAULT_BASE_URL, LITELLM_PROVIDER_PREFIX, SupportedLiteLLMProvider
  36. from rag.nlp import is_chinese, is_english
  37. from rag.utils import num_tokens_from_string
  38. # Error message constants
  39. class LLMErrorCode(StrEnum):
  40. ERROR_RATE_LIMIT = "RATE_LIMIT_EXCEEDED"
  41. ERROR_AUTHENTICATION = "AUTH_ERROR"
  42. ERROR_INVALID_REQUEST = "INVALID_REQUEST"
  43. ERROR_SERVER = "SERVER_ERROR"
  44. ERROR_TIMEOUT = "TIMEOUT"
  45. ERROR_CONNECTION = "CONNECTION_ERROR"
  46. ERROR_MODEL = "MODEL_ERROR"
  47. ERROR_MAX_ROUNDS = "ERROR_MAX_ROUNDS"
  48. ERROR_CONTENT_FILTER = "CONTENT_FILTERED"
  49. ERROR_QUOTA = "QUOTA_EXCEEDED"
  50. ERROR_MAX_RETRIES = "MAX_RETRIES_EXCEEDED"
  51. ERROR_GENERIC = "GENERIC_ERROR"
  52. class ReActMode(StrEnum):
  53. FUNCTION_CALL = "function_call"
  54. REACT = "react"
  55. ERROR_PREFIX = "**ERROR**"
  56. LENGTH_NOTIFICATION_CN = "······\n由于大模型的上下文窗口大小限制,回答已经被大模型截断。"
  57. LENGTH_NOTIFICATION_EN = "...\nThe answer is truncated by your chosen LLM due to its limitation on context length."
  58. class ToolCallSession(Protocol):
  59. def tool_call(self, name: str, arguments: dict[str, Any]) -> str: ...
  60. class Base(ABC):
  61. def __init__(self, key, model_name, base_url, **kwargs):
  62. timeout = int(os.environ.get("LM_TIMEOUT_SECONDS", 600))
  63. self.client = OpenAI(api_key=key, base_url=base_url, timeout=timeout)
  64. self.model_name = model_name
  65. # Configure retry parameters
  66. self.max_retries = kwargs.get("max_retries", int(os.environ.get("LLM_MAX_RETRIES", 5)))
  67. self.base_delay = kwargs.get("retry_interval", float(os.environ.get("LLM_BASE_DELAY", 2.0)))
  68. self.max_rounds = kwargs.get("max_rounds", 5)
  69. self.is_tools = False
  70. self.tools = []
  71. self.toolcall_sessions = {}
  72. def _get_delay(self):
  73. """Calculate retry delay time"""
  74. return self.base_delay * random.uniform(10, 150)
  75. def _classify_error(self, error):
  76. """Classify error based on error message content"""
  77. error_str = str(error).lower()
  78. keywords_mapping = [
  79. (["quota", "capacity", "credit", "billing", "balance", "欠费"], LLMErrorCode.ERROR_QUOTA),
  80. (["rate limit", "429", "tpm limit", "too many requests", "requests per minute"], LLMErrorCode.ERROR_RATE_LIMIT),
  81. (["auth", "key", "apikey", "401", "forbidden", "permission"], LLMErrorCode.ERROR_AUTHENTICATION),
  82. (["invalid", "bad request", "400", "format", "malformed", "parameter"], LLMErrorCode.ERROR_INVALID_REQUEST),
  83. (["server", "503", "502", "504", "500", "unavailable"], LLMErrorCode.ERROR_SERVER),
  84. (["timeout", "timed out"], LLMErrorCode.ERROR_TIMEOUT),
  85. (["connect", "network", "unreachable", "dns"], LLMErrorCode.ERROR_CONNECTION),
  86. (["filter", "content", "policy", "blocked", "safety", "inappropriate"], LLMErrorCode.ERROR_CONTENT_FILTER),
  87. (["model", "not found", "does not exist", "not available"], LLMErrorCode.ERROR_MODEL),
  88. (["max rounds"], LLMErrorCode.ERROR_MODEL),
  89. ]
  90. for words, code in keywords_mapping:
  91. if re.search("({})".format("|".join(words)), error_str):
  92. return code
  93. return LLMErrorCode.ERROR_GENERIC
  94. def _clean_conf(self, gen_conf):
  95. if "max_tokens" in gen_conf:
  96. del gen_conf["max_tokens"]
  97. allowed_conf = {
  98. "temperature",
  99. "max_completion_tokens",
  100. "top_p",
  101. "stream",
  102. "stream_options",
  103. "stop",
  104. "n",
  105. "presence_penalty",
  106. "frequency_penalty",
  107. "functions",
  108. "function_call",
  109. "logit_bias",
  110. "user",
  111. "response_format",
  112. "seed",
  113. "tools",
  114. "tool_choice",
  115. "logprobs",
  116. "top_logprobs",
  117. "extra_headers",
  118. }
  119. gen_conf = {k: v for k, v in gen_conf.items() if k in allowed_conf}
  120. return gen_conf
  121. def _chat(self, history, gen_conf, **kwargs):
  122. logging.info("[HISTORY]" + json.dumps(history, ensure_ascii=False, indent=2))
  123. if self.model_name.lower().find("qwen3") >= 0:
  124. kwargs["extra_body"] = {"enable_thinking": False}
  125. response = self.client.chat.completions.create(model=self.model_name, messages=history, **gen_conf, **kwargs)
  126. if any([not response.choices, not response.choices[0].message, not response.choices[0].message.content]):
  127. return "", 0
  128. ans = response.choices[0].message.content.strip()
  129. if response.choices[0].finish_reason == "length":
  130. ans = self._length_stop(ans)
  131. return ans, self.total_token_count(response)
  132. def _chat_streamly(self, history, gen_conf, **kwargs):
  133. logging.info("[HISTORY STREAMLY]" + json.dumps(history, ensure_ascii=False, indent=4))
  134. reasoning_start = False
  135. response = self.client.chat.completions.create(model=self.model_name, messages=history, stream=True, **gen_conf, stop=kwargs.get("stop"))
  136. for resp in response:
  137. if not resp.choices:
  138. continue
  139. if not resp.choices[0].delta.content:
  140. resp.choices[0].delta.content = ""
  141. if kwargs.get("with_reasoning", True) and hasattr(resp.choices[0].delta, "reasoning_content") and resp.choices[0].delta.reasoning_content:
  142. ans = ""
  143. if not reasoning_start:
  144. reasoning_start = True
  145. ans = "<think>"
  146. ans += resp.choices[0].delta.reasoning_content + "</think>"
  147. else:
  148. reasoning_start = False
  149. ans = resp.choices[0].delta.content
  150. tol = self.total_token_count(resp)
  151. if not tol:
  152. tol = num_tokens_from_string(resp.choices[0].delta.content)
  153. if resp.choices[0].finish_reason == "length":
  154. if is_chinese(ans):
  155. ans += LENGTH_NOTIFICATION_CN
  156. else:
  157. ans += LENGTH_NOTIFICATION_EN
  158. yield ans, tol
  159. def _length_stop(self, ans):
  160. if is_chinese([ans]):
  161. return ans + LENGTH_NOTIFICATION_CN
  162. return ans + LENGTH_NOTIFICATION_EN
  163. def _exceptions(self, e, attempt):
  164. logging.exception("OpenAI chat_with_tools")
  165. # Classify the error
  166. error_code = self._classify_error(e)
  167. if attempt == self.max_retries:
  168. error_code = LLMErrorCode.ERROR_MAX_RETRIES
  169. # Check if it's a rate limit error or server error and not the last attempt
  170. should_retry = error_code == LLMErrorCode.ERROR_RATE_LIMIT or error_code == LLMErrorCode.ERROR_SERVER
  171. if not should_retry:
  172. return f"{ERROR_PREFIX}: {error_code} - {str(e)}"
  173. delay = self._get_delay()
  174. logging.warning(f"Error: {error_code}. Retrying in {delay:.2f} seconds... (Attempt {attempt + 1}/{self.max_retries})")
  175. time.sleep(delay)
  176. def _verbose_tool_use(self, name, args, res):
  177. return "<tool_call>" + json.dumps({"name": name, "args": args, "result": res}, ensure_ascii=False, indent=2) + "</tool_call>"
  178. def _append_history(self, hist, tool_call, tool_res):
  179. hist.append(
  180. {
  181. "role": "assistant",
  182. "tool_calls": [
  183. {
  184. "index": tool_call.index,
  185. "id": tool_call.id,
  186. "function": {
  187. "name": tool_call.function.name,
  188. "arguments": tool_call.function.arguments,
  189. },
  190. "type": "function",
  191. },
  192. ],
  193. }
  194. )
  195. try:
  196. if isinstance(tool_res, dict):
  197. tool_res = json.dumps(tool_res, ensure_ascii=False)
  198. finally:
  199. hist.append({"role": "tool", "tool_call_id": tool_call.id, "content": str(tool_res)})
  200. return hist
  201. def bind_tools(self, toolcall_session, tools):
  202. if not (toolcall_session and tools):
  203. return
  204. self.is_tools = True
  205. self.toolcall_session = toolcall_session
  206. self.tools = tools
  207. def chat_with_tools(self, system: str, history: list, gen_conf: dict = {}):
  208. gen_conf = self._clean_conf(gen_conf)
  209. if system:
  210. history.insert(0, {"role": "system", "content": system})
  211. ans = ""
  212. tk_count = 0
  213. hist = deepcopy(history)
  214. # Implement exponential backoff retry strategy
  215. for attempt in range(self.max_retries + 1):
  216. history = hist
  217. try:
  218. for _ in range(self.max_rounds + 1):
  219. logging.info(f"{self.tools=}")
  220. response = self.client.chat.completions.create(model=self.model_name, messages=history, tools=self.tools, tool_choice="auto", **gen_conf)
  221. tk_count += self.total_token_count(response)
  222. if any([not response.choices, not response.choices[0].message]):
  223. raise Exception(f"500 response structure error. Response: {response}")
  224. if not hasattr(response.choices[0].message, "tool_calls") or not response.choices[0].message.tool_calls:
  225. if hasattr(response.choices[0].message, "reasoning_content") and response.choices[0].message.reasoning_content:
  226. ans += "<think>" + response.choices[0].message.reasoning_content + "</think>"
  227. ans += response.choices[0].message.content
  228. if response.choices[0].finish_reason == "length":
  229. ans = self._length_stop(ans)
  230. return ans, tk_count
  231. for tool_call in response.choices[0].message.tool_calls:
  232. logging.info(f"Response {tool_call=}")
  233. name = tool_call.function.name
  234. try:
  235. args = json_repair.loads(tool_call.function.arguments)
  236. tool_response = self.toolcall_session.tool_call(name, args)
  237. history = self._append_history(history, tool_call, tool_response)
  238. ans += self._verbose_tool_use(name, args, tool_response)
  239. except Exception as e:
  240. logging.exception(msg=f"Wrong JSON argument format in LLM tool call response: {tool_call}")
  241. history.append({"role": "tool", "tool_call_id": tool_call.id, "content": f"Tool call error: \n{tool_call}\nException:\n" + str(e)})
  242. ans += self._verbose_tool_use(name, {}, str(e))
  243. logging.warning(f"Exceed max rounds: {self.max_rounds}")
  244. history.append({"role": "user", "content": f"Exceed max rounds: {self.max_rounds}"})
  245. response, token_count = self._chat(history, gen_conf)
  246. ans += response
  247. tk_count += token_count
  248. return ans, tk_count
  249. except Exception as e:
  250. e = self._exceptions(e, attempt)
  251. if e:
  252. return e, tk_count
  253. assert False, "Shouldn't be here."
  254. def chat(self, system, history, gen_conf={}, **kwargs):
  255. if system:
  256. history.insert(0, {"role": "system", "content": system})
  257. gen_conf = self._clean_conf(gen_conf)
  258. # Implement exponential backoff retry strategy
  259. for attempt in range(self.max_retries + 1):
  260. try:
  261. return self._chat(history, gen_conf, **kwargs)
  262. except Exception as e:
  263. e = self._exceptions(e, attempt)
  264. if e:
  265. return e, 0
  266. assert False, "Shouldn't be here."
  267. def _wrap_toolcall_message(self, stream):
  268. final_tool_calls = {}
  269. for chunk in stream:
  270. for tool_call in chunk.choices[0].delta.tool_calls or []:
  271. index = tool_call.index
  272. if index not in final_tool_calls:
  273. final_tool_calls[index] = tool_call
  274. final_tool_calls[index].function.arguments += tool_call.function.arguments
  275. return final_tool_calls
  276. def chat_streamly_with_tools(self, system: str, history: list, gen_conf: dict = {}):
  277. gen_conf = self._clean_conf(gen_conf)
  278. tools = self.tools
  279. if system:
  280. history.insert(0, {"role": "system", "content": system})
  281. total_tokens = 0
  282. hist = deepcopy(history)
  283. # Implement exponential backoff retry strategy
  284. for attempt in range(self.max_retries + 1):
  285. history = hist
  286. try:
  287. for _ in range(self.max_rounds + 1):
  288. reasoning_start = False
  289. logging.info(f"{tools=}")
  290. response = self.client.chat.completions.create(model=self.model_name, messages=history, stream=True, tools=tools, tool_choice="auto", **gen_conf)
  291. final_tool_calls = {}
  292. answer = ""
  293. for resp in response:
  294. if resp.choices[0].delta.tool_calls:
  295. for tool_call in resp.choices[0].delta.tool_calls or []:
  296. index = tool_call.index
  297. if index not in final_tool_calls:
  298. if not tool_call.function.arguments:
  299. tool_call.function.arguments = ""
  300. final_tool_calls[index] = tool_call
  301. else:
  302. final_tool_calls[index].function.arguments += tool_call.function.arguments if tool_call.function.arguments else ""
  303. continue
  304. if any([not resp.choices, not resp.choices[0].delta, not hasattr(resp.choices[0].delta, "content")]):
  305. raise Exception("500 response structure error.")
  306. if not resp.choices[0].delta.content:
  307. resp.choices[0].delta.content = ""
  308. if hasattr(resp.choices[0].delta, "reasoning_content") and resp.choices[0].delta.reasoning_content:
  309. ans = ""
  310. if not reasoning_start:
  311. reasoning_start = True
  312. ans = "<think>"
  313. ans += resp.choices[0].delta.reasoning_content + "</think>"
  314. yield ans
  315. else:
  316. reasoning_start = False
  317. answer += resp.choices[0].delta.content
  318. yield resp.choices[0].delta.content
  319. tol = self.total_token_count(resp)
  320. if not tol:
  321. total_tokens += num_tokens_from_string(resp.choices[0].delta.content)
  322. else:
  323. total_tokens += tol
  324. finish_reason = resp.choices[0].finish_reason if hasattr(resp.choices[0], "finish_reason") else ""
  325. if finish_reason == "length":
  326. yield self._length_stop("")
  327. if answer:
  328. yield total_tokens
  329. return
  330. for tool_call in final_tool_calls.values():
  331. name = tool_call.function.name
  332. try:
  333. args = json_repair.loads(tool_call.function.arguments)
  334. yield self._verbose_tool_use(name, args, "Begin to call...")
  335. tool_response = self.toolcall_session.tool_call(name, args)
  336. history = self._append_history(history, tool_call, tool_response)
  337. yield self._verbose_tool_use(name, args, tool_response)
  338. except Exception as e:
  339. logging.exception(msg=f"Wrong JSON argument format in LLM tool call response: {tool_call}")
  340. history.append({"role": "tool", "tool_call_id": tool_call.id, "content": f"Tool call error: \n{tool_call}\nException:\n" + str(e)})
  341. yield self._verbose_tool_use(name, {}, str(e))
  342. logging.warning(f"Exceed max rounds: {self.max_rounds}")
  343. history.append({"role": "user", "content": f"Exceed max rounds: {self.max_rounds}"})
  344. response = self.client.chat.completions.create(model=self.model_name, messages=history, stream=True, **gen_conf)
  345. for resp in response:
  346. if any([not resp.choices, not resp.choices[0].delta, not hasattr(resp.choices[0].delta, "content")]):
  347. raise Exception("500 response structure error.")
  348. if not resp.choices[0].delta.content:
  349. resp.choices[0].delta.content = ""
  350. continue
  351. tol = self.total_token_count(resp)
  352. if not tol:
  353. total_tokens += num_tokens_from_string(resp.choices[0].delta.content)
  354. else:
  355. total_tokens += tol
  356. answer += resp.choices[0].delta.content
  357. yield resp.choices[0].delta.content
  358. yield total_tokens
  359. return
  360. except Exception as e:
  361. e = self._exceptions(e, attempt)
  362. if e:
  363. yield e
  364. yield total_tokens
  365. return
  366. assert False, "Shouldn't be here."
  367. def chat_streamly(self, system, history, gen_conf: dict = {}, **kwargs):
  368. if system:
  369. history.insert(0, {"role": "system", "content": system})
  370. gen_conf = self._clean_conf(gen_conf)
  371. ans = ""
  372. total_tokens = 0
  373. try:
  374. for delta_ans, tol in self._chat_streamly(history, gen_conf, **kwargs):
  375. yield delta_ans
  376. total_tokens += tol
  377. except openai.APIError as e:
  378. yield ans + "\n**ERROR**: " + str(e)
  379. yield total_tokens
  380. def total_token_count(self, resp):
  381. try:
  382. return resp.usage.total_tokens
  383. except Exception:
  384. pass
  385. try:
  386. return resp["usage"]["total_tokens"]
  387. except Exception:
  388. pass
  389. return 0
  390. def _calculate_dynamic_ctx(self, history):
  391. """Calculate dynamic context window size"""
  392. def count_tokens(text):
  393. """Calculate token count for text"""
  394. # Simple calculation: 1 token per ASCII character
  395. # 2 tokens for non-ASCII characters (Chinese, Japanese, Korean, etc.)
  396. total = 0
  397. for char in text:
  398. if ord(char) < 128: # ASCII characters
  399. total += 1
  400. else: # Non-ASCII characters (Chinese, Japanese, Korean, etc.)
  401. total += 2
  402. return total
  403. # Calculate total tokens for all messages
  404. total_tokens = 0
  405. for message in history:
  406. content = message.get("content", "")
  407. # Calculate content tokens
  408. content_tokens = count_tokens(content)
  409. # Add role marker token overhead
  410. role_tokens = 4
  411. total_tokens += content_tokens + role_tokens
  412. # Apply 1.2x buffer ratio
  413. total_tokens_with_buffer = int(total_tokens * 1.2)
  414. if total_tokens_with_buffer <= 8192:
  415. ctx_size = 8192
  416. else:
  417. ctx_multiplier = (total_tokens_with_buffer // 8192) + 1
  418. ctx_size = ctx_multiplier * 8192
  419. return ctx_size
  420. class GptTurbo(Base):
  421. _FACTORY_NAME = "OpenAI"
  422. def __init__(self, key, model_name="gpt-3.5-turbo", base_url="https://api.openai.com/v1", **kwargs):
  423. if not base_url:
  424. base_url = "https://api.openai.com/v1"
  425. super().__init__(key, model_name, base_url, **kwargs)
  426. class XinferenceChat(Base):
  427. _FACTORY_NAME = "Xinference"
  428. def __init__(self, key=None, model_name="", base_url="", **kwargs):
  429. if not base_url:
  430. raise ValueError("Local llm url cannot be None")
  431. base_url = urljoin(base_url, "v1")
  432. super().__init__(key, model_name, base_url, **kwargs)
  433. class HuggingFaceChat(Base):
  434. _FACTORY_NAME = "HuggingFace"
  435. def __init__(self, key=None, model_name="", base_url="", **kwargs):
  436. if not base_url:
  437. raise ValueError("Local llm url cannot be None")
  438. base_url = urljoin(base_url, "v1")
  439. super().__init__(key, model_name.split("___")[0], base_url, **kwargs)
  440. class ModelScopeChat(Base):
  441. _FACTORY_NAME = "ModelScope"
  442. def __init__(self, key=None, model_name="", base_url="", **kwargs):
  443. if not base_url:
  444. raise ValueError("Local llm url cannot be None")
  445. base_url = urljoin(base_url, "v1")
  446. super().__init__(key, model_name.split("___")[0], base_url, **kwargs)
  447. class AzureChat(Base):
  448. _FACTORY_NAME = "Azure-OpenAI"
  449. def __init__(self, key, model_name, base_url, **kwargs):
  450. api_key = json.loads(key).get("api_key", "")
  451. api_version = json.loads(key).get("api_version", "2024-02-01")
  452. super().__init__(key, model_name, base_url, **kwargs)
  453. self.client = AzureOpenAI(api_key=api_key, azure_endpoint=base_url, api_version=api_version)
  454. self.model_name = model_name
  455. class BaiChuanChat(Base):
  456. _FACTORY_NAME = "BaiChuan"
  457. def __init__(self, key, model_name="Baichuan3-Turbo", base_url="https://api.baichuan-ai.com/v1", **kwargs):
  458. if not base_url:
  459. base_url = "https://api.baichuan-ai.com/v1"
  460. super().__init__(key, model_name, base_url, **kwargs)
  461. @staticmethod
  462. def _format_params(params):
  463. return {
  464. "temperature": params.get("temperature", 0.3),
  465. "top_p": params.get("top_p", 0.85),
  466. }
  467. def _clean_conf(self, gen_conf):
  468. return {
  469. "temperature": gen_conf.get("temperature", 0.3),
  470. "top_p": gen_conf.get("top_p", 0.85),
  471. }
  472. def _chat(self, history, gen_conf={}, **kwargs):
  473. response = self.client.chat.completions.create(
  474. model=self.model_name,
  475. messages=history,
  476. extra_body={"tools": [{"type": "web_search", "web_search": {"enable": True, "search_mode": "performance_first"}}]},
  477. **gen_conf,
  478. )
  479. ans = response.choices[0].message.content.strip()
  480. if response.choices[0].finish_reason == "length":
  481. if is_chinese([ans]):
  482. ans += LENGTH_NOTIFICATION_CN
  483. else:
  484. ans += LENGTH_NOTIFICATION_EN
  485. return ans, self.total_token_count(response)
  486. def chat_streamly(self, system, history, gen_conf={}, **kwargs):
  487. if system:
  488. history.insert(0, {"role": "system", "content": system})
  489. if "max_tokens" in gen_conf:
  490. del gen_conf["max_tokens"]
  491. ans = ""
  492. total_tokens = 0
  493. try:
  494. response = self.client.chat.completions.create(
  495. model=self.model_name,
  496. messages=history,
  497. extra_body={"tools": [{"type": "web_search", "web_search": {"enable": True, "search_mode": "performance_first"}}]},
  498. stream=True,
  499. **self._format_params(gen_conf),
  500. )
  501. for resp in response:
  502. if not resp.choices:
  503. continue
  504. if not resp.choices[0].delta.content:
  505. resp.choices[0].delta.content = ""
  506. ans = resp.choices[0].delta.content
  507. tol = self.total_token_count(resp)
  508. if not tol:
  509. total_tokens += num_tokens_from_string(resp.choices[0].delta.content)
  510. else:
  511. total_tokens = tol
  512. if resp.choices[0].finish_reason == "length":
  513. if is_chinese([ans]):
  514. ans += LENGTH_NOTIFICATION_CN
  515. else:
  516. ans += LENGTH_NOTIFICATION_EN
  517. yield ans
  518. except Exception as e:
  519. yield ans + "\n**ERROR**: " + str(e)
  520. yield total_tokens
  521. class ZhipuChat(Base):
  522. _FACTORY_NAME = "ZHIPU-AI"
  523. def __init__(self, key, model_name="glm-3-turbo", base_url=None, **kwargs):
  524. super().__init__(key, model_name, base_url=base_url, **kwargs)
  525. self.client = ZhipuAI(api_key=key)
  526. self.model_name = model_name
  527. def _clean_conf(self, gen_conf):
  528. if "max_tokens" in gen_conf:
  529. del gen_conf["max_tokens"]
  530. if "presence_penalty" in gen_conf:
  531. del gen_conf["presence_penalty"]
  532. if "frequency_penalty" in gen_conf:
  533. del gen_conf["frequency_penalty"]
  534. return gen_conf
  535. def chat_with_tools(self, system: str, history: list, gen_conf: dict):
  536. if "presence_penalty" in gen_conf:
  537. del gen_conf["presence_penalty"]
  538. if "frequency_penalty" in gen_conf:
  539. del gen_conf["frequency_penalty"]
  540. return super().chat_with_tools(system, history, gen_conf)
  541. def chat_streamly(self, system, history, gen_conf={}, **kwargs):
  542. if system:
  543. history.insert(0, {"role": "system", "content": system})
  544. if "max_tokens" in gen_conf:
  545. del gen_conf["max_tokens"]
  546. if "presence_penalty" in gen_conf:
  547. del gen_conf["presence_penalty"]
  548. if "frequency_penalty" in gen_conf:
  549. del gen_conf["frequency_penalty"]
  550. ans = ""
  551. tk_count = 0
  552. try:
  553. logging.info(json.dumps(history, ensure_ascii=False, indent=2))
  554. response = self.client.chat.completions.create(model=self.model_name, messages=history, stream=True, **gen_conf)
  555. for resp in response:
  556. if not resp.choices[0].delta.content:
  557. continue
  558. delta = resp.choices[0].delta.content
  559. ans = delta
  560. if resp.choices[0].finish_reason == "length":
  561. if is_chinese(ans):
  562. ans += LENGTH_NOTIFICATION_CN
  563. else:
  564. ans += LENGTH_NOTIFICATION_EN
  565. tk_count = self.total_token_count(resp)
  566. if resp.choices[0].finish_reason == "stop":
  567. tk_count = self.total_token_count(resp)
  568. yield ans
  569. except Exception as e:
  570. yield ans + "\n**ERROR**: " + str(e)
  571. yield tk_count
  572. def chat_streamly_with_tools(self, system: str, history: list, gen_conf: dict):
  573. if "presence_penalty" in gen_conf:
  574. del gen_conf["presence_penalty"]
  575. if "frequency_penalty" in gen_conf:
  576. del gen_conf["frequency_penalty"]
  577. return super().chat_streamly_with_tools(system, history, gen_conf)
  578. class LocalAIChat(Base):
  579. _FACTORY_NAME = "LocalAI"
  580. def __init__(self, key, model_name, base_url=None, **kwargs):
  581. super().__init__(key, model_name, base_url=base_url, **kwargs)
  582. if not base_url:
  583. raise ValueError("Local llm url cannot be None")
  584. base_url = urljoin(base_url, "v1")
  585. self.client = OpenAI(api_key="empty", base_url=base_url)
  586. self.model_name = model_name.split("___")[0]
  587. class LocalLLM(Base):
  588. def __init__(self, key, model_name, base_url=None, **kwargs):
  589. super().__init__(key, model_name, base_url=base_url, **kwargs)
  590. from jina import Client
  591. self.client = Client(port=12345, protocol="grpc", asyncio=True)
  592. def _prepare_prompt(self, system, history, gen_conf):
  593. from rag.svr.jina_server import Prompt
  594. if system:
  595. history.insert(0, {"role": "system", "content": system})
  596. return Prompt(message=history, gen_conf=gen_conf)
  597. def _stream_response(self, endpoint, prompt):
  598. from rag.svr.jina_server import Generation
  599. answer = ""
  600. try:
  601. res = self.client.stream_doc(on=endpoint, inputs=prompt, return_type=Generation)
  602. loop = asyncio.get_event_loop()
  603. try:
  604. while True:
  605. answer = loop.run_until_complete(res.__anext__()).text
  606. yield answer
  607. except StopAsyncIteration:
  608. pass
  609. except Exception as e:
  610. yield answer + "\n**ERROR**: " + str(e)
  611. yield num_tokens_from_string(answer)
  612. def chat(self, system, history, gen_conf={}, **kwargs):
  613. if "max_tokens" in gen_conf:
  614. del gen_conf["max_tokens"]
  615. prompt = self._prepare_prompt(system, history, gen_conf)
  616. chat_gen = self._stream_response("/chat", prompt)
  617. ans = next(chat_gen)
  618. total_tokens = next(chat_gen)
  619. return ans, total_tokens
  620. def chat_streamly(self, system, history, gen_conf={}, **kwargs):
  621. if "max_tokens" in gen_conf:
  622. del gen_conf["max_tokens"]
  623. prompt = self._prepare_prompt(system, history, gen_conf)
  624. return self._stream_response("/stream", prompt)
  625. class VolcEngineChat(Base):
  626. _FACTORY_NAME = "VolcEngine"
  627. def __init__(self, key, model_name, base_url="https://ark.cn-beijing.volces.com/api/v3", **kwargs):
  628. """
  629. Since do not want to modify the original database fields, and the VolcEngine authentication method is quite special,
  630. Assemble ark_api_key, ep_id into api_key, store it as a dictionary type, and parse it for use
  631. model_name is for display only
  632. """
  633. base_url = base_url if base_url else "https://ark.cn-beijing.volces.com/api/v3"
  634. ark_api_key = json.loads(key).get("ark_api_key", "")
  635. model_name = json.loads(key).get("ep_id", "") + json.loads(key).get("endpoint_id", "")
  636. super().__init__(ark_api_key, model_name, base_url, **kwargs)
  637. class MiniMaxChat(Base):
  638. _FACTORY_NAME = "MiniMax"
  639. def __init__(self, key, model_name, base_url="https://api.minimax.chat/v1/text/chatcompletion_v2", **kwargs):
  640. super().__init__(key, model_name, base_url=base_url, **kwargs)
  641. if not base_url:
  642. base_url = "https://api.minimax.chat/v1/text/chatcompletion_v2"
  643. self.base_url = base_url
  644. self.model_name = model_name
  645. self.api_key = key
  646. def _clean_conf(self, gen_conf):
  647. for k in list(gen_conf.keys()):
  648. if k not in ["temperature", "top_p", "max_tokens"]:
  649. del gen_conf[k]
  650. return gen_conf
  651. def _chat(self, history, gen_conf):
  652. headers = {
  653. "Authorization": f"Bearer {self.api_key}",
  654. "Content-Type": "application/json",
  655. }
  656. payload = json.dumps({"model": self.model_name, "messages": history, **gen_conf})
  657. response = requests.request("POST", url=self.base_url, headers=headers, data=payload)
  658. response = response.json()
  659. ans = response["choices"][0]["message"]["content"].strip()
  660. if response["choices"][0]["finish_reason"] == "length":
  661. if is_chinese(ans):
  662. ans += LENGTH_NOTIFICATION_CN
  663. else:
  664. ans += LENGTH_NOTIFICATION_EN
  665. return ans, self.total_token_count(response)
  666. def chat_streamly(self, system, history, gen_conf):
  667. if system:
  668. history.insert(0, {"role": "system", "content": system})
  669. for k in list(gen_conf.keys()):
  670. if k not in ["temperature", "top_p", "max_tokens"]:
  671. del gen_conf[k]
  672. ans = ""
  673. total_tokens = 0
  674. try:
  675. headers = {
  676. "Authorization": f"Bearer {self.api_key}",
  677. "Content-Type": "application/json",
  678. }
  679. payload = json.dumps(
  680. {
  681. "model": self.model_name,
  682. "messages": history,
  683. "stream": True,
  684. **gen_conf,
  685. }
  686. )
  687. response = requests.request(
  688. "POST",
  689. url=self.base_url,
  690. headers=headers,
  691. data=payload,
  692. )
  693. for resp in response.text.split("\n\n")[:-1]:
  694. resp = json.loads(resp[6:])
  695. text = ""
  696. if "choices" in resp and "delta" in resp["choices"][0]:
  697. text = resp["choices"][0]["delta"]["content"]
  698. ans = text
  699. tol = self.total_token_count(resp)
  700. if not tol:
  701. total_tokens += num_tokens_from_string(text)
  702. else:
  703. total_tokens = tol
  704. yield ans
  705. except Exception as e:
  706. yield ans + "\n**ERROR**: " + str(e)
  707. yield total_tokens
  708. class MistralChat(Base):
  709. _FACTORY_NAME = "Mistral"
  710. def __init__(self, key, model_name, base_url=None, **kwargs):
  711. super().__init__(key, model_name, base_url=base_url, **kwargs)
  712. from mistralai.client import MistralClient
  713. self.client = MistralClient(api_key=key)
  714. self.model_name = model_name
  715. def _clean_conf(self, gen_conf):
  716. for k in list(gen_conf.keys()):
  717. if k not in ["temperature", "top_p", "max_tokens"]:
  718. del gen_conf[k]
  719. return gen_conf
  720. def _chat(self, history, gen_conf={}, **kwargs):
  721. response = self.client.chat(model=self.model_name, messages=history, **gen_conf)
  722. ans = response.choices[0].message.content
  723. if response.choices[0].finish_reason == "length":
  724. if is_chinese(ans):
  725. ans += LENGTH_NOTIFICATION_CN
  726. else:
  727. ans += LENGTH_NOTIFICATION_EN
  728. return ans, self.total_token_count(response)
  729. def chat_streamly(self, system, history, gen_conf={}, **kwargs):
  730. if system:
  731. history.insert(0, {"role": "system", "content": system})
  732. for k in list(gen_conf.keys()):
  733. if k not in ["temperature", "top_p", "max_tokens"]:
  734. del gen_conf[k]
  735. ans = ""
  736. total_tokens = 0
  737. try:
  738. response = self.client.chat_stream(model=self.model_name, messages=history, **gen_conf, **kwargs)
  739. for resp in response:
  740. if not resp.choices or not resp.choices[0].delta.content:
  741. continue
  742. ans = resp.choices[0].delta.content
  743. total_tokens += 1
  744. if resp.choices[0].finish_reason == "length":
  745. if is_chinese(ans):
  746. ans += LENGTH_NOTIFICATION_CN
  747. else:
  748. ans += LENGTH_NOTIFICATION_EN
  749. yield ans
  750. except openai.APIError as e:
  751. yield ans + "\n**ERROR**: " + str(e)
  752. yield total_tokens
  753. ## openrouter
  754. class OpenRouterChat(Base):
  755. _FACTORY_NAME = "OpenRouter"
  756. def __init__(self, key, model_name, base_url="https://openrouter.ai/api/v1", **kwargs):
  757. if not base_url:
  758. base_url = "https://openrouter.ai/api/v1"
  759. super().__init__(key, model_name, base_url, **kwargs)
  760. class StepFunChat(Base):
  761. _FACTORY_NAME = "StepFun"
  762. def __init__(self, key, model_name, base_url="https://api.stepfun.com/v1", **kwargs):
  763. if not base_url:
  764. base_url = "https://api.stepfun.com/v1"
  765. super().__init__(key, model_name, base_url, **kwargs)
  766. class LmStudioChat(Base):
  767. _FACTORY_NAME = "LM-Studio"
  768. def __init__(self, key, model_name, base_url, **kwargs):
  769. if not base_url:
  770. raise ValueError("Local llm url cannot be None")
  771. base_url = urljoin(base_url, "v1")
  772. super().__init__(key, model_name, base_url, **kwargs)
  773. self.client = OpenAI(api_key="lm-studio", base_url=base_url)
  774. self.model_name = model_name
  775. class OpenAI_APIChat(Base):
  776. _FACTORY_NAME = ["VLLM", "OpenAI-API-Compatible"]
  777. def __init__(self, key, model_name, base_url, **kwargs):
  778. if not base_url:
  779. raise ValueError("url cannot be None")
  780. model_name = model_name.split("___")[0]
  781. super().__init__(key, model_name, base_url, **kwargs)
  782. class PPIOChat(Base):
  783. _FACTORY_NAME = "PPIO"
  784. def __init__(self, key, model_name, base_url="https://api.ppinfra.com/v3/openai", **kwargs):
  785. if not base_url:
  786. base_url = "https://api.ppinfra.com/v3/openai"
  787. super().__init__(key, model_name, base_url, **kwargs)
  788. class LeptonAIChat(Base):
  789. _FACTORY_NAME = "LeptonAI"
  790. def __init__(self, key, model_name, base_url=None, **kwargs):
  791. if not base_url:
  792. base_url = urljoin("https://" + model_name + ".lepton.run", "api/v1")
  793. super().__init__(key, model_name, base_url, **kwargs)
  794. class PerfXCloudChat(Base):
  795. _FACTORY_NAME = "PerfXCloud"
  796. def __init__(self, key, model_name, base_url="https://cloud.perfxlab.cn/v1", **kwargs):
  797. if not base_url:
  798. base_url = "https://cloud.perfxlab.cn/v1"
  799. super().__init__(key, model_name, base_url, **kwargs)
  800. class UpstageChat(Base):
  801. _FACTORY_NAME = "Upstage"
  802. def __init__(self, key, model_name, base_url="https://api.upstage.ai/v1/solar", **kwargs):
  803. if not base_url:
  804. base_url = "https://api.upstage.ai/v1/solar"
  805. super().__init__(key, model_name, base_url, **kwargs)
  806. class NovitaAIChat(Base):
  807. _FACTORY_NAME = "NovitaAI"
  808. def __init__(self, key, model_name, base_url="https://api.novita.ai/v3/openai", **kwargs):
  809. if not base_url:
  810. base_url = "https://api.novita.ai/v3/openai"
  811. super().__init__(key, model_name, base_url, **kwargs)
  812. class SILICONFLOWChat(Base):
  813. _FACTORY_NAME = "SILICONFLOW"
  814. def __init__(self, key, model_name, base_url="https://api.siliconflow.cn/v1", **kwargs):
  815. if not base_url:
  816. base_url = "https://api.siliconflow.cn/v1"
  817. super().__init__(key, model_name, base_url, **kwargs)
  818. class YiChat(Base):
  819. _FACTORY_NAME = "01.AI"
  820. def __init__(self, key, model_name, base_url="https://api.lingyiwanwu.com/v1", **kwargs):
  821. if not base_url:
  822. base_url = "https://api.lingyiwanwu.com/v1"
  823. super().__init__(key, model_name, base_url, **kwargs)
  824. class GiteeChat(Base):
  825. _FACTORY_NAME = "GiteeAI"
  826. def __init__(self, key, model_name, base_url="https://ai.gitee.com/v1/", **kwargs):
  827. if not base_url:
  828. base_url = "https://ai.gitee.com/v1/"
  829. super().__init__(key, model_name, base_url, **kwargs)
  830. class ReplicateChat(Base):
  831. _FACTORY_NAME = "Replicate"
  832. def __init__(self, key, model_name, base_url=None, **kwargs):
  833. super().__init__(key, model_name, base_url=base_url, **kwargs)
  834. from replicate.client import Client
  835. self.model_name = model_name
  836. self.client = Client(api_token=key)
  837. def _chat(self, history, gen_conf={}, **kwargs):
  838. system = history[0]["content"] if history and history[0]["role"] == "system" else ""
  839. prompt = "\n".join([item["role"] + ":" + item["content"] for item in history[-5:] if item["role"] != "system"])
  840. response = self.client.run(
  841. self.model_name,
  842. input={"system_prompt": system, "prompt": prompt, **gen_conf},
  843. )
  844. ans = "".join(response)
  845. return ans, num_tokens_from_string(ans)
  846. def chat_streamly(self, system, history, gen_conf={}, **kwargs):
  847. if "max_tokens" in gen_conf:
  848. del gen_conf["max_tokens"]
  849. prompt = "\n".join([item["role"] + ":" + item["content"] for item in history[-5:]])
  850. ans = ""
  851. try:
  852. response = self.client.run(
  853. self.model_name,
  854. input={"system_prompt": system, "prompt": prompt, **gen_conf},
  855. )
  856. for resp in response:
  857. ans = resp
  858. yield ans
  859. except Exception as e:
  860. yield ans + "\n**ERROR**: " + str(e)
  861. yield num_tokens_from_string(ans)
  862. class HunyuanChat(Base):
  863. _FACTORY_NAME = "Tencent Hunyuan"
  864. def __init__(self, key, model_name, base_url=None, **kwargs):
  865. super().__init__(key, model_name, base_url=base_url, **kwargs)
  866. from tencentcloud.common import credential
  867. from tencentcloud.hunyuan.v20230901 import hunyuan_client
  868. key = json.loads(key)
  869. sid = key.get("hunyuan_sid", "")
  870. sk = key.get("hunyuan_sk", "")
  871. cred = credential.Credential(sid, sk)
  872. self.model_name = model_name
  873. self.client = hunyuan_client.HunyuanClient(cred, "")
  874. def _clean_conf(self, gen_conf):
  875. _gen_conf = {}
  876. if "temperature" in gen_conf:
  877. _gen_conf["Temperature"] = gen_conf["temperature"]
  878. if "top_p" in gen_conf:
  879. _gen_conf["TopP"] = gen_conf["top_p"]
  880. return _gen_conf
  881. def _chat(self, history, gen_conf={}, **kwargs):
  882. from tencentcloud.hunyuan.v20230901 import models
  883. hist = [{k.capitalize(): v for k, v in item.items()} for item in history]
  884. req = models.ChatCompletionsRequest()
  885. params = {"Model": self.model_name, "Messages": hist, **gen_conf}
  886. req.from_json_string(json.dumps(params))
  887. response = self.client.ChatCompletions(req)
  888. ans = response.Choices[0].Message.Content
  889. return ans, response.Usage.TotalTokens
  890. def chat_streamly(self, system, history, gen_conf={}, **kwargs):
  891. from tencentcloud.common.exception.tencent_cloud_sdk_exception import (
  892. TencentCloudSDKException,
  893. )
  894. from tencentcloud.hunyuan.v20230901 import models
  895. _gen_conf = {}
  896. _history = [{k.capitalize(): v for k, v in item.items()} for item in history]
  897. if system:
  898. _history.insert(0, {"Role": "system", "Content": system})
  899. if "max_tokens" in gen_conf:
  900. del gen_conf["max_tokens"]
  901. if "temperature" in gen_conf:
  902. _gen_conf["Temperature"] = gen_conf["temperature"]
  903. if "top_p" in gen_conf:
  904. _gen_conf["TopP"] = gen_conf["top_p"]
  905. req = models.ChatCompletionsRequest()
  906. params = {
  907. "Model": self.model_name,
  908. "Messages": _history,
  909. "Stream": True,
  910. **_gen_conf,
  911. }
  912. req.from_json_string(json.dumps(params))
  913. ans = ""
  914. total_tokens = 0
  915. try:
  916. response = self.client.ChatCompletions(req)
  917. for resp in response:
  918. resp = json.loads(resp["data"])
  919. if not resp["Choices"] or not resp["Choices"][0]["Delta"]["Content"]:
  920. continue
  921. ans = resp["Choices"][0]["Delta"]["Content"]
  922. total_tokens += 1
  923. yield ans
  924. except TencentCloudSDKException as e:
  925. yield ans + "\n**ERROR**: " + str(e)
  926. yield total_tokens
  927. class SparkChat(Base):
  928. _FACTORY_NAME = "XunFei Spark"
  929. def __init__(self, key, model_name, base_url="https://spark-api-open.xf-yun.com/v1", **kwargs):
  930. if not base_url:
  931. base_url = "https://spark-api-open.xf-yun.com/v1"
  932. model2version = {
  933. "Spark-Max": "generalv3.5",
  934. "Spark-Lite": "general",
  935. "Spark-Pro": "generalv3",
  936. "Spark-Pro-128K": "pro-128k",
  937. "Spark-4.0-Ultra": "4.0Ultra",
  938. }
  939. version2model = {v: k for k, v in model2version.items()}
  940. assert model_name in model2version or model_name in version2model, f"The given model name is not supported yet. Support: {list(model2version.keys())}"
  941. if model_name in model2version:
  942. model_version = model2version[model_name]
  943. else:
  944. model_version = model_name
  945. super().__init__(key, model_version, base_url, **kwargs)
  946. class BaiduYiyanChat(Base):
  947. _FACTORY_NAME = "BaiduYiyan"
  948. def __init__(self, key, model_name, base_url=None, **kwargs):
  949. super().__init__(key, model_name, base_url=base_url, **kwargs)
  950. import qianfan
  951. key = json.loads(key)
  952. ak = key.get("yiyan_ak", "")
  953. sk = key.get("yiyan_sk", "")
  954. self.client = qianfan.ChatCompletion(ak=ak, sk=sk)
  955. self.model_name = model_name.lower()
  956. def _clean_conf(self, gen_conf):
  957. gen_conf["penalty_score"] = ((gen_conf.get("presence_penalty", 0) + gen_conf.get("frequency_penalty", 0)) / 2) + 1
  958. if "max_tokens" in gen_conf:
  959. del gen_conf["max_tokens"]
  960. return gen_conf
  961. def _chat(self, history, gen_conf):
  962. system = history[0]["content"] if history and history[0]["role"] == "system" else ""
  963. response = self.client.do(model=self.model_name, messages=[h for h in history if h["role"] != "system"], system=system, **gen_conf).body
  964. ans = response["result"]
  965. return ans, self.total_token_count(response)
  966. def chat_streamly(self, system, history, gen_conf={}, **kwargs):
  967. gen_conf["penalty_score"] = ((gen_conf.get("presence_penalty", 0) + gen_conf.get("frequency_penalty", 0)) / 2) + 1
  968. if "max_tokens" in gen_conf:
  969. del gen_conf["max_tokens"]
  970. ans = ""
  971. total_tokens = 0
  972. try:
  973. response = self.client.do(model=self.model_name, messages=history, system=system, stream=True, **gen_conf)
  974. for resp in response:
  975. resp = resp.body
  976. ans = resp["result"]
  977. total_tokens = self.total_token_count(resp)
  978. yield ans
  979. except Exception as e:
  980. return ans + "\n**ERROR**: " + str(e), 0
  981. yield total_tokens
  982. class GoogleChat(Base):
  983. _FACTORY_NAME = "Google Cloud"
  984. def __init__(self, key, model_name, base_url=None, **kwargs):
  985. super().__init__(key, model_name, base_url=base_url, **kwargs)
  986. import base64
  987. from google.oauth2 import service_account
  988. key = json.loads(key)
  989. access_token = json.loads(base64.b64decode(key.get("google_service_account_key", "")))
  990. project_id = key.get("google_project_id", "")
  991. region = key.get("google_region", "")
  992. scopes = ["https://www.googleapis.com/auth/cloud-platform"]
  993. self.model_name = model_name
  994. if "claude" in self.model_name:
  995. from anthropic import AnthropicVertex
  996. from google.auth.transport.requests import Request
  997. if access_token:
  998. credits = service_account.Credentials.from_service_account_info(access_token, scopes=scopes)
  999. request = Request()
  1000. credits.refresh(request)
  1001. token = credits.token
  1002. self.client = AnthropicVertex(region=region, project_id=project_id, access_token=token)
  1003. else:
  1004. self.client = AnthropicVertex(region=region, project_id=project_id)
  1005. else:
  1006. import vertexai.generative_models as glm
  1007. from google.cloud import aiplatform
  1008. if access_token:
  1009. credits = service_account.Credentials.from_service_account_info(access_token)
  1010. aiplatform.init(credentials=credits, project=project_id, location=region)
  1011. else:
  1012. aiplatform.init(project=project_id, location=region)
  1013. self.client = glm.GenerativeModel(model_name=self.model_name)
  1014. def _clean_conf(self, gen_conf):
  1015. if "claude" in self.model_name:
  1016. if "max_tokens" in gen_conf:
  1017. del gen_conf["max_tokens"]
  1018. else:
  1019. if "max_tokens" in gen_conf:
  1020. gen_conf["max_output_tokens"] = gen_conf["max_tokens"]
  1021. for k in list(gen_conf.keys()):
  1022. if k not in ["temperature", "top_p", "max_output_tokens"]:
  1023. del gen_conf[k]
  1024. return gen_conf
  1025. def _chat(self, history, gen_conf={}, **kwargs):
  1026. system = history[0]["content"] if history and history[0]["role"] == "system" else ""
  1027. if "claude" in self.model_name:
  1028. response = self.client.messages.create(
  1029. model=self.model_name,
  1030. messages=[h for h in history if h["role"] != "system"],
  1031. system=system,
  1032. stream=False,
  1033. **gen_conf,
  1034. ).json()
  1035. ans = response["content"][0]["text"]
  1036. if response["stop_reason"] == "max_tokens":
  1037. ans += "...\nFor the content length reason, it stopped, continue?" if is_english([ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  1038. return (
  1039. ans,
  1040. response["usage"]["input_tokens"] + response["usage"]["output_tokens"],
  1041. )
  1042. self.client._system_instruction = system
  1043. hist = []
  1044. for item in history:
  1045. if item["role"] == "system":
  1046. continue
  1047. hist.append(deepcopy(item))
  1048. item = hist[-1]
  1049. if "role" in item and item["role"] == "assistant":
  1050. item["role"] = "model"
  1051. if "content" in item:
  1052. item["parts"] = [
  1053. {
  1054. "text": item.pop("content"),
  1055. }
  1056. ]
  1057. response = self.client.generate_content(hist, generation_config=gen_conf)
  1058. ans = response.text
  1059. return ans, response.usage_metadata.total_token_count
  1060. def chat_streamly(self, system, history, gen_conf={}, **kwargs):
  1061. if "claude" in self.model_name:
  1062. if "max_tokens" in gen_conf:
  1063. del gen_conf["max_tokens"]
  1064. ans = ""
  1065. total_tokens = 0
  1066. try:
  1067. response = self.client.messages.create(
  1068. model=self.model_name,
  1069. messages=history,
  1070. system=system,
  1071. stream=True,
  1072. **gen_conf,
  1073. )
  1074. for res in response.iter_lines():
  1075. res = res.decode("utf-8")
  1076. if "content_block_delta" in res and "data" in res:
  1077. text = json.loads(res[6:])["delta"]["text"]
  1078. ans = text
  1079. total_tokens += num_tokens_from_string(text)
  1080. except Exception as e:
  1081. yield ans + "\n**ERROR**: " + str(e)
  1082. yield total_tokens
  1083. else:
  1084. self.client._system_instruction = system
  1085. if "max_tokens" in gen_conf:
  1086. gen_conf["max_output_tokens"] = gen_conf["max_tokens"]
  1087. for k in list(gen_conf.keys()):
  1088. if k not in ["temperature", "top_p", "max_output_tokens"]:
  1089. del gen_conf[k]
  1090. for item in history:
  1091. if "role" in item and item["role"] == "assistant":
  1092. item["role"] = "model"
  1093. if "content" in item:
  1094. item["parts"] = item.pop("content")
  1095. ans = ""
  1096. try:
  1097. response = self.model.generate_content(history, generation_config=gen_conf, stream=True)
  1098. for resp in response:
  1099. ans = resp.text
  1100. yield ans
  1101. except Exception as e:
  1102. yield ans + "\n**ERROR**: " + str(e)
  1103. yield response._chunks[-1].usage_metadata.total_token_count
  1104. class GPUStackChat(Base):
  1105. _FACTORY_NAME = "GPUStack"
  1106. def __init__(self, key=None, model_name="", base_url="", **kwargs):
  1107. if not base_url:
  1108. raise ValueError("Local llm url cannot be None")
  1109. base_url = urljoin(base_url, "v1")
  1110. super().__init__(key, model_name, base_url, **kwargs)
  1111. class Ai302Chat(Base):
  1112. _FACTORY_NAME = "302.AI"
  1113. def __init__(self, key, model_name, base_url="https://api.302.ai/v1", **kwargs):
  1114. if not base_url:
  1115. base_url = "https://api.302.ai/v1"
  1116. super().__init__(key, model_name, base_url, **kwargs)
  1117. class LiteLLMBase(ABC):
  1118. _FACTORY_NAME = ["Tongyi-Qianwen", "Bedrock", "Moonshot", "xAI", "DeepInfra", "Groq", "Cohere", "Gemini", "DeepSeek", "NVIDIA", "TogetherAI", "Anthropic", "Ollama"]
  1119. def __init__(self, key, model_name, base_url=None, **kwargs):
  1120. self.timeout = int(os.environ.get("LM_TIMEOUT_SECONDS", 600))
  1121. self.provider = kwargs.get("provider", "")
  1122. self.prefix = LITELLM_PROVIDER_PREFIX.get(self.provider, "")
  1123. self.model_name = f"{self.prefix}{model_name}"
  1124. self.api_key = key
  1125. self.base_url = base_url or FACTORY_DEFAULT_BASE_URL.get(self.provider, "")
  1126. # Configure retry parameters
  1127. self.max_retries = kwargs.get("max_retries", int(os.environ.get("LLM_MAX_RETRIES", 5)))
  1128. self.base_delay = kwargs.get("retry_interval", float(os.environ.get("LLM_BASE_DELAY", 2.0)))
  1129. self.max_rounds = kwargs.get("max_rounds", 5)
  1130. self.is_tools = False
  1131. self.tools = []
  1132. self.toolcall_sessions = {}
  1133. # Factory specific fields
  1134. if self.provider == SupportedLiteLLMProvider.Bedrock:
  1135. self.bedrock_ak = json.loads(key).get("bedrock_ak", "")
  1136. self.bedrock_sk = json.loads(key).get("bedrock_sk", "")
  1137. self.bedrock_region = json.loads(key).get("bedrock_region", "")
  1138. def _get_delay(self):
  1139. """Calculate retry delay time"""
  1140. return self.base_delay * random.uniform(10, 150)
  1141. def _classify_error(self, error):
  1142. """Classify error based on error message content"""
  1143. error_str = str(error).lower()
  1144. keywords_mapping = [
  1145. (["quota", "capacity", "credit", "billing", "balance", "欠费"], LLMErrorCode.ERROR_QUOTA),
  1146. (["rate limit", "429", "tpm limit", "too many requests", "requests per minute"], LLMErrorCode.ERROR_RATE_LIMIT),
  1147. (["auth", "key", "apikey", "401", "forbidden", "permission"], LLMErrorCode.ERROR_AUTHENTICATION),
  1148. (["invalid", "bad request", "400", "format", "malformed", "parameter"], LLMErrorCode.ERROR_INVALID_REQUEST),
  1149. (["server", "503", "502", "504", "500", "unavailable"], LLMErrorCode.ERROR_SERVER),
  1150. (["timeout", "timed out"], LLMErrorCode.ERROR_TIMEOUT),
  1151. (["connect", "network", "unreachable", "dns"], LLMErrorCode.ERROR_CONNECTION),
  1152. (["filter", "content", "policy", "blocked", "safety", "inappropriate"], LLMErrorCode.ERROR_CONTENT_FILTER),
  1153. (["model", "not found", "does not exist", "not available"], LLMErrorCode.ERROR_MODEL),
  1154. (["max rounds"], LLMErrorCode.ERROR_MODEL),
  1155. ]
  1156. for words, code in keywords_mapping:
  1157. if re.search("({})".format("|".join(words)), error_str):
  1158. return code
  1159. return LLMErrorCode.ERROR_GENERIC
  1160. def _clean_conf(self, gen_conf):
  1161. if "max_tokens" in gen_conf:
  1162. del gen_conf["max_tokens"]
  1163. return gen_conf
  1164. def _chat(self, history, gen_conf, **kwargs):
  1165. logging.info("[HISTORY]" + json.dumps(history, ensure_ascii=False, indent=2))
  1166. if self.model_name.lower().find("qwen3") >= 0:
  1167. kwargs["extra_body"] = {"enable_thinking": False}
  1168. completion_args = self._construct_completion_args(history=history, stream=False, tools=False, **gen_conf)
  1169. response = litellm.completion(
  1170. **completion_args,
  1171. drop_params=True,
  1172. timeout=self.timeout,
  1173. )
  1174. # response = self.client.chat.completions.create(model=self.model_name, messages=history, **gen_conf, **kwargs)
  1175. if any([not response.choices, not response.choices[0].message, not response.choices[0].message.content]):
  1176. return "", 0
  1177. ans = response.choices[0].message.content.strip()
  1178. if response.choices[0].finish_reason == "length":
  1179. ans = self._length_stop(ans)
  1180. return ans, self.total_token_count(response)
  1181. def _chat_streamly(self, history, gen_conf, **kwargs):
  1182. logging.info("[HISTORY STREAMLY]" + json.dumps(history, ensure_ascii=False, indent=4))
  1183. reasoning_start = False
  1184. completion_args = self._construct_completion_args(history=history, stream=True, tools=False, **gen_conf)
  1185. stop = kwargs.get("stop")
  1186. if stop:
  1187. completion_args["stop"] = stop
  1188. response = litellm.completion(
  1189. **completion_args,
  1190. drop_params=True,
  1191. timeout=self.timeout,
  1192. )
  1193. for resp in response:
  1194. if not hasattr(resp, "choices") or not resp.choices:
  1195. continue
  1196. delta = resp.choices[0].delta
  1197. if not hasattr(delta, "content") or delta.content is None:
  1198. delta.content = ""
  1199. if kwargs.get("with_reasoning", True) and hasattr(delta, "reasoning_content") and delta.reasoning_content:
  1200. ans = ""
  1201. if not reasoning_start:
  1202. reasoning_start = True
  1203. ans = "<think>"
  1204. ans += delta.reasoning_content + "</think>"
  1205. else:
  1206. reasoning_start = False
  1207. ans = delta.content
  1208. tol = self.total_token_count(resp)
  1209. if not tol:
  1210. tol = num_tokens_from_string(delta.content)
  1211. finish_reason = resp.choices[0].finish_reason if hasattr(resp.choices[0], "finish_reason") else ""
  1212. if finish_reason == "length":
  1213. if is_chinese(ans):
  1214. ans += LENGTH_NOTIFICATION_CN
  1215. else:
  1216. ans += LENGTH_NOTIFICATION_EN
  1217. yield ans, tol
  1218. def _length_stop(self, ans):
  1219. if is_chinese([ans]):
  1220. return ans + LENGTH_NOTIFICATION_CN
  1221. return ans + LENGTH_NOTIFICATION_EN
  1222. def _exceptions(self, e, attempt):
  1223. logging.exception("OpenAI chat_with_tools")
  1224. # Classify the error
  1225. error_code = self._classify_error(e)
  1226. if attempt == self.max_retries:
  1227. error_code = LLMErrorCode.ERROR_MAX_RETRIES
  1228. # Check if it's a rate limit error or server error and not the last attempt
  1229. should_retry = error_code == LLMErrorCode.ERROR_RATE_LIMIT or error_code == LLMErrorCode.ERROR_SERVER
  1230. if not should_retry:
  1231. return f"{ERROR_PREFIX}: {error_code} - {str(e)}"
  1232. delay = self._get_delay()
  1233. logging.warning(f"Error: {error_code}. Retrying in {delay:.2f} seconds... (Attempt {attempt + 1}/{self.max_retries})")
  1234. time.sleep(delay)
  1235. def _verbose_tool_use(self, name, args, res):
  1236. return "<tool_call>" + json.dumps({"name": name, "args": args, "result": res}, ensure_ascii=False, indent=2) + "</tool_call>"
  1237. def _append_history(self, hist, tool_call, tool_res):
  1238. hist.append(
  1239. {
  1240. "role": "assistant",
  1241. "tool_calls": [
  1242. {
  1243. "index": tool_call.index,
  1244. "id": tool_call.id,
  1245. "function": {
  1246. "name": tool_call.function.name,
  1247. "arguments": tool_call.function.arguments,
  1248. },
  1249. "type": "function",
  1250. },
  1251. ],
  1252. }
  1253. )
  1254. try:
  1255. if isinstance(tool_res, dict):
  1256. tool_res = json.dumps(tool_res, ensure_ascii=False)
  1257. finally:
  1258. hist.append({"role": "tool", "tool_call_id": tool_call.id, "content": str(tool_res)})
  1259. return hist
  1260. def bind_tools(self, toolcall_session, tools):
  1261. if not (toolcall_session and tools):
  1262. return
  1263. self.is_tools = True
  1264. self.toolcall_session = toolcall_session
  1265. self.tools = tools
  1266. def _construct_completion_args(self, history, stream: bool, tools: bool, **kwargs):
  1267. completion_args = {
  1268. "model": self.model_name,
  1269. "messages": history,
  1270. "api_key": self.api_key,
  1271. **kwargs,
  1272. }
  1273. if stream:
  1274. completion_args.update(
  1275. {
  1276. "stream": stream,
  1277. }
  1278. )
  1279. if tools and self.tools:
  1280. completion_args.update(
  1281. {
  1282. "tools": self.tools,
  1283. "tool_choice": "auto",
  1284. }
  1285. )
  1286. if self.provider in FACTORY_DEFAULT_BASE_URL:
  1287. completion_args.update({"api_base": self.base_url})
  1288. elif self.provider == SupportedLiteLLMProvider.Bedrock:
  1289. completion_args.pop("api_key", None)
  1290. completion_args.pop("api_base", None)
  1291. completion_args.update(
  1292. {
  1293. "aws_access_key_id": self.bedrock_ak,
  1294. "aws_secret_access_key": self.bedrock_sk,
  1295. "aws_region_name": self.bedrock_region,
  1296. }
  1297. )
  1298. return completion_args
  1299. def chat_with_tools(self, system: str, history: list, gen_conf: dict = {}):
  1300. gen_conf = self._clean_conf(gen_conf)
  1301. if system:
  1302. history.insert(0, {"role": "system", "content": system})
  1303. ans = ""
  1304. tk_count = 0
  1305. hist = deepcopy(history)
  1306. # Implement exponential backoff retry strategy
  1307. for attempt in range(self.max_retries + 1):
  1308. history = deepcopy(hist) # deepcopy is required here
  1309. try:
  1310. for _ in range(self.max_rounds + 1):
  1311. logging.info(f"{self.tools=}")
  1312. completion_args = self._construct_completion_args(history=history, stream=False, tools=True, **gen_conf)
  1313. response = litellm.completion(
  1314. **completion_args,
  1315. drop_params=True,
  1316. timeout=self.timeout,
  1317. )
  1318. tk_count += self.total_token_count(response)
  1319. if not hasattr(response, "choices") or not response.choices or not response.choices[0].message:
  1320. raise Exception(f"500 response structure error. Response: {response}")
  1321. message = response.choices[0].message
  1322. if not hasattr(message, "tool_calls") or not message.tool_calls:
  1323. if hasattr(message, "reasoning_content") and message.reasoning_content:
  1324. ans += f"<think>{message.reasoning_content}</think>"
  1325. ans += message.content or ""
  1326. if response.choices[0].finish_reason == "length":
  1327. ans = self._length_stop(ans)
  1328. return ans, tk_count
  1329. for tool_call in message.tool_calls:
  1330. logging.info(f"Response {tool_call=}")
  1331. name = tool_call.function.name
  1332. try:
  1333. args = json_repair.loads(tool_call.function.arguments)
  1334. tool_response = self.toolcall_session.tool_call(name, args)
  1335. history = self._append_history(history, tool_call, tool_response)
  1336. ans += self._verbose_tool_use(name, args, tool_response)
  1337. except Exception as e:
  1338. logging.exception(msg=f"Wrong JSON argument format in LLM tool call response: {tool_call}")
  1339. history.append({"role": "tool", "tool_call_id": tool_call.id, "content": f"Tool call error: \n{tool_call}\nException:\n" + str(e)})
  1340. ans += self._verbose_tool_use(name, {}, str(e))
  1341. logging.warning(f"Exceed max rounds: {self.max_rounds}")
  1342. history.append({"role": "user", "content": f"Exceed max rounds: {self.max_rounds}"})
  1343. response, token_count = self._chat(history, gen_conf)
  1344. ans += response
  1345. tk_count += token_count
  1346. return ans, tk_count
  1347. except Exception as e:
  1348. e = self._exceptions(e, attempt)
  1349. if e:
  1350. return e, tk_count
  1351. assert False, "Shouldn't be here."
  1352. def chat(self, system, history, gen_conf={}, **kwargs):
  1353. if system:
  1354. history.insert(0, {"role": "system", "content": system})
  1355. gen_conf = self._clean_conf(gen_conf)
  1356. # Implement exponential backoff retry strategy
  1357. for attempt in range(self.max_retries + 1):
  1358. try:
  1359. response = self._chat(history, gen_conf, **kwargs)
  1360. return response
  1361. except Exception as e:
  1362. e = self._exceptions(e, attempt)
  1363. if e:
  1364. return e, 0
  1365. assert False, "Shouldn't be here."
  1366. def _wrap_toolcall_message(self, stream):
  1367. final_tool_calls = {}
  1368. for chunk in stream:
  1369. for tool_call in chunk.choices[0].delta.tool_calls or []:
  1370. index = tool_call.index
  1371. if index not in final_tool_calls:
  1372. final_tool_calls[index] = tool_call
  1373. final_tool_calls[index].function.arguments += tool_call.function.arguments
  1374. return final_tool_calls
  1375. def chat_streamly_with_tools(self, system: str, history: list, gen_conf: dict = {}):
  1376. gen_conf = self._clean_conf(gen_conf)
  1377. tools = self.tools
  1378. if system:
  1379. history.insert(0, {"role": "system", "content": system})
  1380. total_tokens = 0
  1381. hist = deepcopy(history)
  1382. # Implement exponential backoff retry strategy
  1383. for attempt in range(self.max_retries + 1):
  1384. history = deepcopy(hist) # deepcopy is required here
  1385. try:
  1386. for _ in range(self.max_rounds + 1):
  1387. reasoning_start = False
  1388. logging.info(f"{tools=}")
  1389. completion_args = self._construct_completion_args(history=history, stream=True, tools=True, **gen_conf)
  1390. response = litellm.completion(
  1391. **completion_args,
  1392. drop_params=True,
  1393. timeout=self.timeout,
  1394. )
  1395. final_tool_calls = {}
  1396. answer = ""
  1397. for resp in response:
  1398. if not hasattr(resp, "choices") or not resp.choices:
  1399. continue
  1400. delta = resp.choices[0].delta
  1401. if hasattr(delta, "tool_calls") and delta.tool_calls:
  1402. for tool_call in delta.tool_calls:
  1403. index = tool_call.index
  1404. if index not in final_tool_calls:
  1405. if not tool_call.function.arguments:
  1406. tool_call.function.arguments = ""
  1407. final_tool_calls[index] = tool_call
  1408. else:
  1409. final_tool_calls[index].function.arguments += tool_call.function.arguments or ""
  1410. continue
  1411. if not hasattr(delta, "content") or delta.content is None:
  1412. delta.content = ""
  1413. if hasattr(delta, "reasoning_content") and delta.reasoning_content:
  1414. ans = ""
  1415. if not reasoning_start:
  1416. reasoning_start = True
  1417. ans = "<think>"
  1418. ans += delta.reasoning_content + "</think>"
  1419. yield ans
  1420. else:
  1421. reasoning_start = False
  1422. answer += delta.content
  1423. yield delta.content
  1424. tol = self.total_token_count(resp)
  1425. if not tol:
  1426. total_tokens += num_tokens_from_string(delta.content)
  1427. else:
  1428. total_tokens += tol
  1429. finish_reason = getattr(resp.choices[0], "finish_reason", "")
  1430. if finish_reason == "length":
  1431. yield self._length_stop("")
  1432. if answer:
  1433. yield total_tokens
  1434. return
  1435. for tool_call in final_tool_calls.values():
  1436. name = tool_call.function.name
  1437. try:
  1438. args = json_repair.loads(tool_call.function.arguments)
  1439. yield self._verbose_tool_use(name, args, "Begin to call...")
  1440. tool_response = self.toolcall_session.tool_call(name, args)
  1441. history = self._append_history(history, tool_call, tool_response)
  1442. yield self._verbose_tool_use(name, args, tool_response)
  1443. except Exception as e:
  1444. logging.exception(msg=f"Wrong JSON argument format in LLM tool call response: {tool_call}")
  1445. history.append(
  1446. {
  1447. "role": "tool",
  1448. "tool_call_id": tool_call.id,
  1449. "content": f"Tool call error: \n{tool_call}\nException:\n{str(e)}",
  1450. }
  1451. )
  1452. yield self._verbose_tool_use(name, {}, str(e))
  1453. logging.warning(f"Exceed max rounds: {self.max_rounds}")
  1454. history.append({"role": "user", "content": f"Exceed max rounds: {self.max_rounds}"})
  1455. completion_args = self._construct_completion_args(history=history, stream=True, tools=True, **gen_conf)
  1456. response = litellm.completion(
  1457. **completion_args,
  1458. drop_params=True,
  1459. timeout=self.timeout,
  1460. )
  1461. for resp in response:
  1462. if not hasattr(resp, "choices") or not resp.choices:
  1463. continue
  1464. delta = resp.choices[0].delta
  1465. if not hasattr(delta, "content") or delta.content is None:
  1466. continue
  1467. tol = self.total_token_count(resp)
  1468. if not tol:
  1469. total_tokens += num_tokens_from_string(delta.content)
  1470. else:
  1471. total_tokens += tol
  1472. yield delta.content
  1473. yield total_tokens
  1474. return
  1475. except Exception as e:
  1476. e = self._exceptions(e, attempt)
  1477. if e:
  1478. yield e
  1479. yield total_tokens
  1480. return
  1481. assert False, "Shouldn't be here."
  1482. def chat_streamly(self, system, history, gen_conf: dict = {}, **kwargs):
  1483. if system:
  1484. history.insert(0, {"role": "system", "content": system})
  1485. gen_conf = self._clean_conf(gen_conf)
  1486. ans = ""
  1487. total_tokens = 0
  1488. try:
  1489. for delta_ans, tol in self._chat_streamly(history, gen_conf, **kwargs):
  1490. yield delta_ans
  1491. total_tokens += tol
  1492. except openai.APIError as e:
  1493. yield ans + "\n**ERROR**: " + str(e)
  1494. yield total_tokens
  1495. def total_token_count(self, resp):
  1496. try:
  1497. return resp.usage.total_tokens
  1498. except Exception:
  1499. pass
  1500. try:
  1501. return resp["usage"]["total_tokens"]
  1502. except Exception:
  1503. pass
  1504. return 0
  1505. def _calculate_dynamic_ctx(self, history):
  1506. """Calculate dynamic context window size"""
  1507. def count_tokens(text):
  1508. """Calculate token count for text"""
  1509. # Simple calculation: 1 token per ASCII character
  1510. # 2 tokens for non-ASCII characters (Chinese, Japanese, Korean, etc.)
  1511. total = 0
  1512. for char in text:
  1513. if ord(char) < 128: # ASCII characters
  1514. total += 1
  1515. else: # Non-ASCII characters (Chinese, Japanese, Korean, etc.)
  1516. total += 2
  1517. return total
  1518. # Calculate total tokens for all messages
  1519. total_tokens = 0
  1520. for message in history:
  1521. content = message.get("content", "")
  1522. # Calculate content tokens
  1523. content_tokens = count_tokens(content)
  1524. # Add role marker token overhead
  1525. role_tokens = 4
  1526. total_tokens += content_tokens + role_tokens
  1527. # Apply 1.2x buffer ratio
  1528. total_tokens_with_buffer = int(total_tokens * 1.2)
  1529. if total_tokens_with_buffer <= 8192:
  1530. ctx_size = 8192
  1531. else:
  1532. ctx_multiplier = (total_tokens_with_buffer // 8192) + 1
  1533. ctx_size = ctx_multiplier * 8192
  1534. return ctx_size